From f1ead75ad2d7a3bd95d0229ee55c67f961836d80 Mon Sep 17 00:00:00 2001 From: Abhi Bhat Date: Fri, 5 Jun 2026 15:48:35 +0530 Subject: [PATCH] feat(agentos): registry ObjectId addressing, cascade delete, session-transcript fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Registry data model + addressing - agent_registry/_id is now a Mongo ObjectId with `name` as a separate unique-indexed field (chat_pins/agent_policies likewise → agentName). - Public API + SPA address agents by ObjectId (/agents/:id, agentId params); a resolve-by-id helper maps id → registry doc → name for the name-keyed cross-collection FKs (sessions, logs, messages, schedules, S3 prefix). - Boot migration converts legacy string-_id rows + ensures unique indexes. - Python/library telemetry ingest stays name-addressed (server mints _id). Cascade delete - Deleting an agent removes its sessions, live sandboxes, S3 snapshots, logs, messages, schedules, and pins; per-session delete mirrors it. Session transcript display fix - Rebuild runtime-local harness-bundle.mjs so the pinSessionStoreKey wrapper is actually shipped — the running harness was writing sessions._id under the derived engine UUID instead of the harness sessionId, so the dashboard couldn't find transcripts ("Resumed — no stored transcript"). - Harden the projectKey-suffix fallback (looseProjectKeySuffix) so agent names with spaces match the CLI's hyphen-sanitized projectKey; recovers transcripts orphaned under the engine UUID. SPA - Sidebar items are real routed pages (/agents/:id); modal legibility + auto-close; observability default range 15m; register shows typed name. scripts/ - drop-collections.mjs: guarded clean-slate admin tool (requires CONFIRM_DROP to echo the DB name; dry-run otherwise). Co-Authored-By: Claude Opus 4.8 (1M context) --- agentos/src/App.tsx | 8 +- agentos/src/api.ts | 46 +- agentos/src/components/AgentDashboard.tsx | 19 +- agentos/src/components/ChatTab.tsx | 30 +- agentos/src/components/HomePage.tsx | 12 +- agentos/src/components/LogsTab.tsx | 8 +- agentos/src/components/PolicyTab.tsx | 10 +- agentos/src/components/RegisterAgentForm.tsx | 13 +- agentos/src/components/RegistryPage.tsx | 16 +- agentos/src/components/SchedulesTab.tsx | 8 +- agentos/src/components/WorkspaceTab.tsx | 22 +- agentos/src/components/ui/alert-dialog.tsx | 4 +- agentos/src/components/ui/dialog.tsx | 4 +- .../scripts/drop-collections.mjs | 65 + packages/agentos-server/src/agent-defs.ts | 44 +- packages/agentos-server/src/index.ts | 15 +- packages/agentos-server/src/mongo.ts | 71 +- packages/agentos-server/src/routes/agents.ts | 37 +- packages/agentos-server/src/routes/chat.ts | 23 +- packages/agentos-server/src/routes/logs.ts | 10 +- .../agentos-server/src/routes/policies.ts | 32 +- packages/agentos-server/src/routes/run.ts | 7 +- .../agentos-server/src/routes/schedules.ts | 19 +- .../agentos-server/src/routes/sessions.ts | 44 +- .../src/stores/telemetry-projection.ts | 8 +- .../runtime-local/assets/harness-bundle.mjs | 218682 ++++++++------- 26 files changed, 115478 insertions(+), 103779 deletions(-) create mode 100644 packages/agentos-server/scripts/drop-collections.mjs diff --git a/agentos/src/App.tsx b/agentos/src/App.tsx index 2c650c0..58eb408 100644 --- a/agentos/src/App.tsx +++ b/agentos/src/App.tsx @@ -18,7 +18,7 @@ export default function App() { } /> } /> } /> - } /> + } /> } /> @@ -74,8 +74,8 @@ function HomeRoute() { return ( navigate(`/agents/${encodeURIComponent(name)}`, { state: { message } })} - onOpenDashboard={() => navigate(agents[0] ? `/agents/${encodeURIComponent(agents[0].name)}` : "/registry")} + onLaunch={(agentId, message) => navigate(`/agents/${encodeURIComponent(agentId)}`, { state: { message } })} + onOpenDashboard={() => navigate(agents[0] ? `/agents/${encodeURIComponent(agents[0].id)}` : "/registry")} /> ); } @@ -89,7 +89,7 @@ function RegistryRoute() { loaded={loaded} err={err} selected={null} - onOpenAgent={(name) => navigate(`/agents/${encodeURIComponent(name)}`)} + onOpenAgent={(agentId) => navigate(`/agents/${encodeURIComponent(agentId)}`)} onReload={reload} /> ); diff --git a/agentos/src/api.ts b/agentos/src/api.ts index 29c122a..eb01962 100644 --- a/agentos/src/api.ts +++ b/agentos/src/api.ts @@ -10,6 +10,10 @@ export type IdentitySource = | { type: "inline"; manifest: Record; files?: Record }; export interface Agent { + /** Registry surrogate key (Mongo ObjectId, stringified). The public/API + * identifier — routes are `/agents/:id` and all agent-scoped calls pass it. + * `name` is the human label/FK; never use it as the addressing key. */ + id: string; name: string; label: string; harness: string; @@ -207,7 +211,7 @@ export interface Schedule { lastResult?: string | null; } export interface NewSchedule { - agentName: string; + agentId: string; prompt: string; kind: "interval" | "daily"; intervalMinutes?: number; @@ -247,24 +251,24 @@ async function reqJSON(method: string, path: string, body?: unknown): Promise export const api = { agents: () => getJSON<{ agents: Agent[] }>("/agents").then((d) => d.agents), registerAgent: (input: RegisterAgentInput) => - postJSON<{ ok: boolean; name: string }>("/agents/register", input), - unregisterAgent: (name: string) => - reqJSON("DELETE", `/agents/${encodeURIComponent(name)}`), - patchAgent: (name: string, fields: Partial>) => - reqJSON<{ ok: boolean }>("PATCH", `/agents/${encodeURIComponent(name)}`, fields), - logs: (bot?: string, limit = 100) => - getJSON<{ logs: LogEntry[] }>(`/logs?limit=${limit}${bot ? `&bot=${encodeURIComponent(bot)}` : ""}`).then((d) => d.logs), - sessions: (bot?: string, limit = 100) => - getJSON<{ sessions: SessionSummary[] }>(`/sessions?limit=${limit}${bot ? `&bot=${encodeURIComponent(bot)}` : ""}`).then((d) => d.sessions), + postJSON<{ ok: boolean; id: string; name: string }>("/agents/register", input), + unregisterAgent: (agentId: string) => + reqJSON("DELETE", `/agents/${encodeURIComponent(agentId)}`), + patchAgent: (agentId: string, fields: Partial>) => + reqJSON<{ ok: boolean }>("PATCH", `/agents/${encodeURIComponent(agentId)}`, fields), + logs: (agentId?: string, limit = 100) => + getJSON<{ logs: LogEntry[] }>(`/logs?limit=${limit}${agentId ? `&agentId=${encodeURIComponent(agentId)}` : ""}`).then((d) => d.logs), + sessions: (agentId?: string, limit = 100) => + getJSON<{ sessions: SessionSummary[] }>(`/sessions?limit=${limit}${agentId ? `&agentId=${encodeURIComponent(agentId)}` : ""}`).then((d) => d.sessions), session: (id: string) => getJSON(`/sessions/${encodeURIComponent(id)}`), - deleteSession: (id: string, bot?: string) => + deleteSession: (id: string, agentId?: string) => reqJSON( "DELETE", - `/sessions/${encodeURIComponent(id)}${bot ? `?bot=${encodeURIComponent(bot)}` : ""}`, + `/sessions/${encodeURIComponent(id)}${agentId ? `?agentId=${encodeURIComponent(agentId)}` : ""}`, ), - chatSandbox: (agent: string, opts?: { sessionId?: string; forceNew?: boolean }) => + chatSandbox: (agentId: string, opts?: { sessionId?: string; forceNew?: boolean }) => postJSON<{ sandboxId: string; sessionId: string; bot: string }>( - `/agents/${encodeURIComponent(agent)}/chat-sandbox`, + `/agents/${encodeURIComponent(agentId)}/chat-sandbox`, opts?.sessionId ? { sessionId: opts.sessionId } : opts?.forceNew ? { forceNew: true } : {}, ), logWebTurn: (entry: { bot: string; sessionId: string; query: string; reply: string; ok: boolean }) => @@ -272,10 +276,10 @@ export const api = { // SSE chat — caller reads the stream. Path goes through the same /api proxy. chatStreamUrl: (sandboxId: string) => `/api/sandboxes/${encodeURIComponent(sandboxId)}/chat`, // SSE one-shot run (deepagents). Server builds the /run body from {message}. - runStreamUrl: (agent: string) => `/api/agents/${encodeURIComponent(agent)}/run`, + runStreamUrl: (agentId: string) => `/api/agents/${encodeURIComponent(agentId)}/run`, // Schedules - schedules: (agent?: string) => - getJSON<{ schedules: Schedule[] }>(`/schedules${agent ? `?agent=${encodeURIComponent(agent)}` : ""}`).then((d) => d.schedules), + schedules: (agentId?: string) => + getJSON<{ schedules: Schedule[] }>(`/schedules${agentId ? `?agentId=${encodeURIComponent(agentId)}` : ""}`).then((d) => d.schedules), createSchedule: (s: NewSchedule) => postJSON<{ schedule: Schedule }>("/schedules", s).then((d) => d.schedule), updateSchedule: (id: string, fields: Partial & { enabled?: boolean }) => reqJSON<{ schedule: Schedule }>("PATCH", `/schedules/${encodeURIComponent(id)}`, fields).then((d) => d.schedule), @@ -290,10 +294,10 @@ export const api = { deletePolicy: (id: string) => reqJSON<{ success?: boolean }>("DELETE", `/policies/${encodeURIComponent(id)}`), // Per-agent policy binding (Mongo, ours). - getAgentPolicy: (agent: string) => - getJSON<{ binding: AgentPolicyBinding | null }>(`/agents/${encodeURIComponent(agent)}/policy`).then((d) => d.binding), - setAgentPolicy: (agent: string, policyId: string | null) => - reqJSON<{ binding: AgentPolicyBinding | null }>("PUT", `/agents/${encodeURIComponent(agent)}/policy`, { policy_id: policyId }).then((d) => d.binding), + getAgentPolicy: (agentId: string) => + getJSON<{ binding: AgentPolicyBinding | null }>(`/agents/${encodeURIComponent(agentId)}/policy`).then((d) => d.binding), + setAgentPolicy: (agentId: string, policyId: string | null) => + reqJSON<{ binding: AgentPolicyBinding | null }>("PUT", `/agents/${encodeURIComponent(agentId)}/policy`, { policy_id: policyId }).then((d) => d.binding), // OPA rego policies (managed by SRS, referenced from RAI policies' opa_guardrail). opaPolicies: () => getJSON<{ policies: OPAPolicyDoc[] } | OPAPolicyDoc[]>("/opa-policies").then((d) => (Array.isArray(d) ? d : d.policies)), opaPolicy: (id: string) => getJSON(`/opa-policies/${encodeURIComponent(id)}`), diff --git a/agentos/src/components/AgentDashboard.tsx b/agentos/src/components/AgentDashboard.tsx index 917d527..71bb943 100644 --- a/agentos/src/components/AgentDashboard.tsx +++ b/agentos/src/components/AgentDashboard.tsx @@ -40,7 +40,7 @@ function TypeBadge({ agent, className = "" }: { agent: Agent; className?: string } export function AgentDashboard() { - const { name } = useParams<{ name: string }>(); + const { id } = useParams<{ id: string }>(); const { agents, loaded } = useAgents(); const navigate = useNavigate(); const location = useLocation(); @@ -51,7 +51,7 @@ export function AgentDashboard() { (location.state as { message?: string } | null)?.message ?? null, ); - const agent = agents.find((a) => a.name === name) ?? null; + const agent = agents.find((a) => a.id === id) ?? null; if (!loaded) { return
Loading…
; @@ -60,7 +60,7 @@ export function AgentDashboard() { return (
-
Unknown agent {name}.
+
Unknown agent {id}.
Back to registry
@@ -98,24 +98,25 @@ export function AgentDashboard() {
{tab === "chat" && ( setLaunchMessage(null)} /> )} - {tab === "schedules" && } + {tab === "schedules" && } {tab === "policy" && ( navigate("/policies")} /> )} - {tab === "logs" && } + {tab === "logs" && }
); diff --git a/agentos/src/components/ChatTab.tsx b/agentos/src/components/ChatTab.tsx index b9655f6..e60edb9 100644 --- a/agentos/src/components/ChatTab.tsx +++ b/agentos/src/components/ChatTab.tsx @@ -25,7 +25,8 @@ const CONTINUE_PROMPT = "Continue from where you left off — keep building until the project is complete, then summarize what you built and give me the deploy URL."; export function ChatTab({ - agent, + agentId, + agentName, sandboxCapable, resumeSessionId, onConsumedResume, @@ -33,7 +34,10 @@ export function ChatTab({ onConsumedInitial, onSessionStarted, }: { - agent: string; + /** Registry ObjectId — used to address the agent in API calls. */ + agentId: string; + /** Human name — used for display + the `bot` field on logged turns. */ + agentName: string; sandboxCapable: boolean; resumeSessionId: string | null; onConsumedResume: () => void; @@ -61,7 +65,7 @@ export function ChatTab({ setSessionId(null); setMsgs([]); setErr(null); - }, [agent]); + }, [agentId]); useEffect(() => { if (!resumeSessionId) return; @@ -97,12 +101,14 @@ export function ChatTab({ try { // No `resume` → this is a fresh "New chat": force a brand-new session so // the server doesn't silently resume the agent's pinned (last) session. - const r = await api.chatSandbox(agent, resume ? { sessionId: resume } : { forceNew: true }); + const r = await api.chatSandbox(agentId, resume ? { sessionId: resume } : { forceNew: true }); setSandboxId(r.sandboxId); setSessionId(r.sessionId); - // Tell the parent a session now exists so the sidebar can show/highlight - // it — a freshly-created chat has no row in the list until this fires. - onSessionStarted?.(r.sessionId); + // Only notify the parent for a genuinely NEW session — it adds the row to + // the sidebar. Resuming an existing session must NOT fire this: the row + // already exists and re-fetching the list on every click is the bug that + // refetched sessions repeatedly. + if (!resume) onSessionStarted?.(r.sessionId); return r.sandboxId; } catch (e) { setErr(String(e)); @@ -125,7 +131,7 @@ export function ChatTab({ } streamUrl = api.chatStreamUrl(curSandbox); } else { - streamUrl = api.runStreamUrl(agent); + streamUrl = api.runStreamUrl(agentId); } if (textArg === undefined) setInput(""); @@ -173,8 +179,8 @@ export function ChatTab({ setBusy(false); api.logWebTurn({ - bot: agent, - sessionId: sessionId ?? `oneshot-${agent}`, + bot: agentName, + sessionId: sessionId ?? `oneshot-${agentName}`, query: text, reply: finalText, ok: true, @@ -219,7 +225,7 @@ export function ChatTab({ )} {msgs.length === 0 && !err && (
- Talk to {agent}. It runs with its configured identity and tools. + Talk to {agentName}. It runs with its configured identity and tools.
)} {msgs.map((m, i) => { @@ -248,7 +254,7 @@ export function ChatTab({ send(); } }} - placeholder={`Message ${agent}… (Enter to send, Shift+Enter for newline)`} + placeholder={`Message ${agentName}… (Enter to send, Shift+Enter for newline)`} rows={2} className="flex-1 resize-none rounded-xl bg-card px-3.5 py-2.5" /> diff --git a/agentos/src/components/HomePage.tsx b/agentos/src/components/HomePage.tsx index 2daeccd..2359cb3 100644 --- a/agentos/src/components/HomePage.tsx +++ b/agentos/src/components/HomePage.tsx @@ -98,6 +98,7 @@ export function HomePage({ // mode agents (Python harness) have a non-resolvable source and so cannot // start a live chat, even though their harness is sandboxable. const resolveTarget = (): { + id: string | null; name: string; sandboxCapable: boolean; liveChatCapable: boolean; @@ -106,7 +107,7 @@ export function HomePage({ const found = agents.find((a) => a.name === name); const sandboxCap = found ? found.sandboxCapable : selected.id !== "deep-agent"; const liveCap = found ? found.liveChatCapable !== false : sandboxCap; - return { name, sandboxCapable: sandboxCap, liveChatCapable: liveCap }; + return { id: found?.id ?? null, name, sandboxCapable: sandboxCap, liveChatCapable: liveCap }; }; const submit = async () => { @@ -167,10 +168,15 @@ export function HomePage({ setBusy(false); return; } + if (!target.id) { + setAssistant(`⚠️ "${target.name}" isn't a registered agent yet — register it first.`); + setBusy(false); + return; + } if (target.sandboxCapable) { let sb = sandboxId; if (!sb) { - const created = await api.chatSandbox(target.name); + const created = await api.chatSandbox(target.id); sb = created.sandboxId; turnSession = created.sessionId; setSandboxId(created.sandboxId); @@ -179,7 +185,7 @@ export function HomePage({ streamUrl = api.chatStreamUrl(sb); } else { // One-shot agents (deepagents): no warm sandbox, no cross-turn memory. - streamUrl = api.runStreamUrl(target.name); + streamUrl = api.runStreamUrl(target.id); } await streamChat(streamUrl, msg, { diff --git a/agentos/src/components/LogsTab.tsx b/agentos/src/components/LogsTab.tsx index 404fbca..e757d14 100644 --- a/agentos/src/components/LogsTab.tsx +++ b/agentos/src/components/LogsTab.tsx @@ -13,7 +13,7 @@ const SOURCE_VARIANT: Record([]); const [loading, setLoading] = useState(true); const [expanded, setExpanded] = useState(null); @@ -25,7 +25,7 @@ export function LogsTab({ agent }: { agent: string }) { if (!quiet) setLoading(true); else setRefreshing(true); api - .logs(agent, 200) + .logs(agentId, 200) .then((l) => { setLogs(l); setErr(null); @@ -40,13 +40,13 @@ export function LogsTab({ agent }: { agent: string }) { useEffect(() => { load(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [agent]); + }, [agentId]); useEffect(() => { const t = setInterval(() => load(true), 15_000); return () => clearInterval(t); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [agent]); + }, [agentId]); const shown = filter === "schedule" ? logs.filter((l) => l.source === "schedule") : logs; const scheduleCount = logs.filter((l) => l.source === "schedule").length; diff --git a/agentos/src/components/PolicyTab.tsx b/agentos/src/components/PolicyTab.tsx index e5b03be..603c6e1 100644 --- a/agentos/src/components/PolicyTab.tsx +++ b/agentos/src/components/PolicyTab.tsx @@ -7,11 +7,11 @@ import { api, type PolicyDoc, type AgentPolicyBinding } from "../api.ts"; * every chat sandbox the agent boots (see runtime SrsPolicyDecider). */ export function PolicyTab({ - agent, + agentId, agentLabel, onManagePolicies, }: { - agent: string; + agentId: string; agentLabel: string; onManagePolicies: () => void; }) { @@ -25,7 +25,7 @@ export function PolicyTab({ setLoading(true); setErr(null); try { - const [pols, b] = await Promise.all([api.policies(), api.getAgentPolicy(agent)]); + const [pols, b] = await Promise.all([api.policies(), api.getAgentPolicy(agentId)]); setPolicies(pols); setBinding(b); } catch (e) { @@ -36,12 +36,12 @@ export function PolicyTab({ }; useEffect(() => { void load(); - }, [agent]); + }, [agentId]); const attach = async (policyId: string | null) => { setSaving(true); try { - const b = await api.setAgentPolicy(agent, policyId); + const b = await api.setAgentPolicy(agentId, policyId); setBinding(b); } catch (e) { setErr(String(e)); diff --git a/agentos/src/components/RegisterAgentForm.tsx b/agentos/src/components/RegisterAgentForm.tsx index 89e8c97..24203e4 100644 --- a/agentos/src/components/RegisterAgentForm.tsx +++ b/agentos/src/components/RegisterAgentForm.tsx @@ -10,6 +10,7 @@ */ import { useState } from "react"; import { Plus } from "lucide-react"; +import { toast } from "sonner"; import { api, type RegisterAgentInput } from "../api.ts"; import { Button } from "./ui/button.tsx"; import { @@ -61,12 +62,15 @@ export function RegisterAgentForm({ onRegistered }: { onRegistered?: (name: stri if (label.trim()) body.label = label.trim(); if (model.trim()) body.model = model.trim(); const res = await api.registerAgent(body); - setOk(`Registered "${res.name}".`); + // Action done → close the modal and confirm via toast. Reset the fields + // so the next open starts clean. + toast.success(`Registered "${res.name}"`); setName(""); setLabel(""); - // Keep source/model pre-filled so registering multiple agents in a row - // doesn't make you re-type the same values. + setErr(null); + setOk(null); onRegistered?.(res.name); + setOpen(false); } catch (e) { setErr(String(e)); } finally { @@ -96,8 +100,7 @@ export function RegisterAgentForm({ onRegistered }: { onRegistered?: (name: stri Register an agent - Only a name is required. Defaults: {DEFAULTS.harness} on{" "} - {DEFAULTS.source}. Open Advanced to override. + Only a name is required diff --git a/agentos/src/components/RegistryPage.tsx b/agentos/src/components/RegistryPage.tsx index 6e8e01a..616b1cf 100644 --- a/agentos/src/components/RegistryPage.tsx +++ b/agentos/src/components/RegistryPage.tsx @@ -46,7 +46,7 @@ export function RegistryPage({ loaded: boolean; err: string | null; selected: string | null; - onOpenAgent: (name: string) => void; + onOpenAgent: (agentId: string) => void; onReload: () => void; }) { const [search, setSearch] = useState(""); @@ -57,7 +57,7 @@ export function RegistryPage({ if (!pendingDelete) return; setDeleting(true); try { - const res = await api.unregisterAgent(pendingDelete.name); + const res = await api.unregisterAgent(pendingDelete.id); const d = res.deleted; toast.success(`Deleted "${pendingDelete.name}"`, { description: `${d.sessions} session(s), ${d.sandboxes} sandbox(es), ${d.snapshots} snapshot(s) removed.`, @@ -157,10 +157,10 @@ export function RegistryPage({
{grouped.hosted.map((a) => ( onOpenAgent(a.name)} + selected={selected === a.id} + onClick={() => onOpenAgent(a.id)} onDelete={() => setPendingDelete(a)} /> ))} @@ -174,10 +174,10 @@ export function RegistryPage({
{grouped.library.map((a) => ( onOpenAgent(a.name)} + selected={selected === a.id} + onClick={() => onOpenAgent(a.id)} onDelete={() => setPendingDelete(a)} /> ))} diff --git a/agentos/src/components/SchedulesTab.tsx b/agentos/src/components/SchedulesTab.tsx index 91220c0..bc0e2c0 100644 --- a/agentos/src/components/SchedulesTab.tsx +++ b/agentos/src/components/SchedulesTab.tsx @@ -35,7 +35,7 @@ import { EmptyState } from "./composite/EmptyState.tsx"; const INTERVAL_OPTIONS = [5, 10, 15, 30, 60, 180, 360, 720, 1440]; const fmtInterval = (m: number) => (m % 60 === 0 ? `${m / 60}h` : `${m}m`); -export function SchedulesTab({ agent, agentLabel }: { agent: string; agentLabel: string }) { +export function SchedulesTab({ agentId, agentLabel }: { agentId: string; agentLabel: string }) { const [schedules, setSchedules] = useState([]); const [loading, setLoading] = useState(true); const [err, setErr] = useState(null); @@ -49,16 +49,16 @@ export function SchedulesTab({ agent, agentLabel }: { agent: string; agentLabel: const load = () => { setLoading(true); - api.schedules(agent).then(setSchedules).catch((e) => setErr(String(e))).finally(() => setLoading(false)); + api.schedules(agentId).then(setSchedules).catch((e) => setErr(String(e))).finally(() => setLoading(false)); }; - useEffect(load, [agent]); + useEffect(load, [agentId]); const create = async () => { if (!prompt.trim() || creating) return; setCreating(true); try { await api.createSchedule({ - agentName: agent, + agentId, prompt: prompt.trim(), kind, ...(kind === "interval" ? { intervalMinutes } : { hourUtc, minuteUtc }), diff --git a/agentos/src/components/WorkspaceTab.tsx b/agentos/src/components/WorkspaceTab.tsx index 156d64f..6b8e2f2 100644 --- a/agentos/src/components/WorkspaceTab.tsx +++ b/agentos/src/components/WorkspaceTab.tsx @@ -20,13 +20,15 @@ import { import { cn } from "../lib/cn.ts"; export function WorkspaceTab({ - agent, + agentId, + agentName, sandboxCapable, liveChatCapable = true, initialMessage, onConsumedInitial, }: { - agent: string; + agentId: string; + agentName: string; sandboxCapable: boolean; // True when the agent can spin up a live chat sandbox. False for // library-mode agents (Python harness etc.) whose ``source`` doesn't @@ -49,17 +51,17 @@ export function WorkspaceTab({ const loadSessions = () => { setLoading(true); - api.sessions(agent, 100) + api.sessions(agentId, 100) .then(setSessions) .catch(() => setSessions([])) .finally(() => setLoading(false)); }; - useEffect(loadSessions, [agent]); + useEffect(loadSessions, [agentId]); useEffect(() => { setResumeId(null); - setChatKey(`new-${agent}-${Date.now()}`); - }, [agent]); + setChatKey(`new-${agentId}-${Date.now()}`); + }, [agentId]); const openSession = (sid: string) => { setResumeId(sid); @@ -83,7 +85,7 @@ export function WorkspaceTab({ const sid = pendingDelete.sessionId; setDeleting(true); try { - const res = await api.deleteSession(sid, pendingDelete.bot || agent); + const res = await api.deleteSession(sid, agentId); const d = res.deleted; toast.success("Session deleted", { description: `${d.sandboxes} sandbox(es), ${d.snapshots} snapshot(s) removed.`, @@ -127,7 +129,8 @@ export function WorkspaceTab({
{}} @@ -231,7 +234,8 @@ export function WorkspaceTab({
{}} diff --git a/agentos/src/components/ui/alert-dialog.tsx b/agentos/src/components/ui/alert-dialog.tsx index 8f624c4..08ca8ce 100644 --- a/agentos/src/components/ui/alert-dialog.tsx +++ b/agentos/src/components/ui/alert-dialog.tsx @@ -13,7 +13,7 @@ export const AlertDialogOverlay = React.forwardRef< >(({ className, ...props }, ref) => ( c.name).sort(); + + console.log(`\nDatabase: ${dbName}`); + console.log(`Collections (${colls.length}):`); + for (const name of colls) { + const count = await db.collection(name).estimatedDocumentCount(); + console.log(` - ${name} (~${count} docs)`); + } + + if (colls.length === 0) { + console.log("\nNothing to drop — database is already empty."); + process.exit(0); + } + + if (confirm !== dbName) { + console.log( + `\n⚠️ DRY RUN — nothing dropped.\n` + + `To DROP all ${colls.length} collection(s) above, re-run with:\n` + + ` CONFIRM_DROP=${dbName}\n`, + ); + process.exit(0); + } + + console.log(`\nDropping all ${colls.length} collection(s)…`); + for (const name of colls) { + await db.collection(name).drop().catch((e) => { + console.warn(` ! ${name}: ${e.message}`); + }); + console.log(` ✓ dropped ${name}`); + } + console.log("\nDone. The agentos-server recreates collections + indexes on next boot."); +} finally { + await client.close(); +} diff --git a/packages/agentos-server/src/agent-defs.ts b/packages/agentos-server/src/agent-defs.ts index 57a76b0..f6fc05b 100644 --- a/packages/agentos-server/src/agent-defs.ts +++ b/packages/agentos-server/src/agent-defs.ts @@ -9,10 +9,14 @@ // are stitched in at sandbox-create time by `defaultEnvsFor()`. This means // the registry can be world-readable without leaking provider keys. +import { ObjectId } from "mongodb"; import { IdentitySource, type IdentitySource as IdentitySourceT } from "@open-gitagent/protocol"; -import { getDb, registryColl, type RegistryDoc } from "./mongo.js"; +import { agentPoliciesColl, registryColl, type RegistryDoc } from "./mongo.js"; export interface AgentDef { + /** Surrogate key — the registry doc's ObjectId, stringified. The public + * API + frontend address agents by this. */ + id: string; name: string; label: string; harness: string; @@ -61,13 +65,29 @@ export function defaultEnvsFor(harness: string): Record { } /** - * Lookup an agent by name in the Mongo registry. The dashboard creates rows - * via POST /agents/register; library-mode SDKs write directly via the - * MongoTelemetry hook. Either way the row schema is the same. + * Lookup an agent by NAME in the Mongo registry. Used by the internal + * name-based callers (the Python/library telemetry ingest, the boot seed). + * The public API resolves by id via `resolveAgentById`. */ export async function resolveAgent(name: string): Promise { try { - const doc = await (await registryColl()).findOne({ _id: name }); + const doc = await (await registryColl()).findOne({ name }); + if (!doc) return undefined; + return registryDocToAgentDef(doc); + } catch { + return undefined; + } +} + +/** + * Lookup an agent by its registry ObjectId (the public identifier carried in + * `/agents/:id` routes and `agentId` params). Returns undefined for a + * malformed id or a missing row so callers can 404 cleanly. + */ +export async function resolveAgentById(id: string): Promise { + if (!ObjectId.isValid(id)) return undefined; + try { + const doc = await (await registryColl()).findOne({ _id: new ObjectId(id) }); if (!doc) return undefined; return registryDocToAgentDef(doc); } catch { @@ -112,8 +132,9 @@ export function registryDocToAgentDef(doc: RegistryDoc): AgentDef { } return { - name: doc._id, - label: doc.label ?? doc._id, + id: doc._id.toString(), + name: doc.name, + label: doc.label ?? doc.name, harness: doc.harness ?? "claude-agent-sdk", source: resolvedSource, ...(doc.model ? { model: doc.model } : {}), @@ -197,9 +218,7 @@ export function runBodyFor(agent: AgentDef, message: string): Record | null> { const endpoint = process.env["SRS_BASE_URL"]; if (!endpoint) return null; - const doc = await (await getDb()) - .collection<{ _id: string; policyId: string }>("agent_policies") - .findOne({ _id: agentName }); + const doc = await (await agentPoliciesColl()).findOne({ agentName }); if (!doc?.policyId) return null; return { kind: "srs", @@ -226,10 +245,11 @@ export async function seedDefaultAgentIfRequested(): Promise { if (count > 0) return; const now = new Date(); await coll.updateOne( - { _id: "claude-code" }, + { name: "claude-code" }, { + // No `_id` here — Mongo mints the surrogate ObjectId on insert. $setOnInsert: { - _id: "claude-code", + name: "claude-code", label: "Claude Code", harness: "claude-agent-sdk", source: process.env["AGENTOS_DEFAULT_SOURCE"] ?? "github.com/shreyas-lyzr/general-agent", diff --git a/packages/agentos-server/src/index.ts b/packages/agentos-server/src/index.ts index d74486a..fe74bc7 100644 --- a/packages/agentos-server/src/index.ts +++ b/packages/agentos-server/src/index.ts @@ -45,7 +45,7 @@ import { obsFieldsRouter } from "./routes/obs-fields.js"; import { pingClickHouse } from "./clickhouse.js"; import { pingNewRelic } from "./new-relic.js"; -import { pingMongo, migrateLegacyWebSessions } from "./mongo.js"; +import { pingMongo, migrateLegacyWebSessions, migrateRegistryObjectIds, ensureRegistryIndexes } from "./mongo.js"; import { ensureFieldValueMVs } from "./migrations.js"; import { startScheduler } from "./scheduler.js"; import { seedDefaultAgentIfRequested } from "./agent-defs.js"; @@ -156,6 +156,19 @@ app.listen(PORT, async () => { // Mongo-side bootstrap — seed default agent and start the scheduler tick. if (mongoOk) { + // One-time, idempotent: convert legacy `_id == name` rows in agent_registry + // / chat_pins / agent_policies to surrogate ObjectId `_id` + name field, + // then ensure the unique name indexes. Runs before everything else so new + // writes (seed, ingest) land in the ObjectId world. + try { + const m = await migrateRegistryObjectIds(); + if (m.registry || m.pins || m.policies) { + console.log(`[agentos-server] migrated registry ids — registry:${m.registry} pins:${m.pins} policies:${m.policies}`); + } + await ensureRegistryIndexes(); + } catch (err) { + console.warn("[agentos-server] registry id migration/index failed:", (err as Error).message); + } try { await seedDefaultAgentIfRequested(); } catch (err) { diff --git a/packages/agentos-server/src/mongo.ts b/packages/agentos-server/src/mongo.ts index b8149b7..ed3d924 100644 --- a/packages/agentos-server/src/mongo.ts +++ b/packages/agentos-server/src/mongo.ts @@ -18,7 +18,7 @@ // The dashboard's web chat used to piggyback on it; that coupling was removed // in favour of the dedicated `chat_sessions` collection above. -import { MongoClient, type Collection, type Db } from "mongodb"; +import { MongoClient, ObjectId, type Collection, type Db } from "mongodb"; let _client: MongoClient | null = null; let _db: Db | null = null; @@ -91,7 +91,8 @@ export interface SessionDoc { } export interface RegistryDoc { - _id: string; // agent name + _id: ObjectId; // surrogate key (Mongo-minted) + name: string; // the agent's human identifier (unique index) label?: string; harness?: string; source?: unknown; // string OR IdentitySource shape @@ -103,11 +104,19 @@ export interface RegistryDoc { } export interface ChatPinDoc { - _id: string; // agent name + _id: ObjectId; + agentName: string; // owning agent name (unique index) sessionId: string; updatedAt: Date; } +export interface PolicyBindingDoc { + _id: ObjectId; + agentName: string; // owning agent name (unique index) + policyId: string; + updatedAt: Date; +} + export interface MessageDoc { _id: string; sessionId: string | null; @@ -139,6 +148,10 @@ export async function chatPinsColl(): Promise> { return (await getDb()).collection("chat_pins"); } +export async function agentPoliciesColl(): Promise> { + return (await getDb()).collection("agent_policies"); +} + export async function messagesColl(): Promise> { return (await getDb()).collection("agent_messages"); } @@ -177,3 +190,55 @@ export async function migrateLegacyWebSessions(): Promise { } return backfilled; } + +/** + * Convert legacy `_id == name` rows to surrogate ObjectId `_id` + a name field, + * for the three collections that used the agent name as their primary key: + * agent_registry → name, chat_pins → agentName, agent_policies → agentName. + * + * Idempotent: only rows whose `_id` is still a string (the old name) are + * touched. Each gets a fresh ObjectId `_id`, the old name copied into the name + * field, all other fields preserved; the old row is deleted. If a migrated row + * for that name already exists (partial prior run), the legacy row is just + * dropped. Cross-collection FKs are by name, so nothing else needs rewriting. + * MUST run before `ensureRegistryIndexes()` so the unique name index isn't + * created while duplicate legacy rows still exist. + */ +export async function migrateRegistryObjectIds(): Promise<{ registry: number; pins: number; policies: number }> { + const db = await getDb(); + const convert = async (collName: string, nameField: string): Promise => { + const coll = db.collection(collName); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const legacy = await coll.find({ _id: { $type: "string" } } as any).toArray(); + let converted = 0; + for (const doc of legacy) { + const oldId = doc["_id"] as unknown as string; + const { _id: _drop, ...rest } = doc; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const already = await coll.findOne({ [nameField]: oldId } as any); + if (!already) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await coll.insertOne({ ...rest, _id: new ObjectId(), [nameField]: oldId } as any); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await coll.deleteOne({ _id: oldId } as any); + converted++; + } + return converted; + }; + const registry = await convert("agent_registry", "name"); + const pins = await convert("chat_pins", "agentName"); + const policies = await convert("agent_policies", "agentName"); + return { registry, pins, policies }; +} + +/** + * Ensure the unique name indexes that back id-based addressing. Idempotent — + * `createIndex` is a no-op when the index already exists. + */ +export async function ensureRegistryIndexes(): Promise { + const db = await getDb(); + await db.collection("agent_registry").createIndex({ name: 1 }, { unique: true }); + await db.collection("chat_pins").createIndex({ agentName: 1 }, { unique: true }); + await db.collection("agent_policies").createIndex({ agentName: 1 }, { unique: true }); +} diff --git a/packages/agentos-server/src/routes/agents.ts b/packages/agentos-server/src/routes/agents.ts index 4f19968..56528f3 100644 --- a/packages/agentos-server/src/routes/agents.ts +++ b/packages/agentos-server/src/routes/agents.ts @@ -17,7 +17,7 @@ import { listLiveSandboxes } from "../upstream.js"; import { agentLogStore } from "../stores/agent-log-store.js"; import { scheduleStore } from "../stores/schedule-store.js"; import { deleteAgentSnapshots, disposeLiveSandboxes } from "../cleanup.js"; -import { hasResolvableSource, normalizeSource, registryDocToAgentDef, sandboxCapable } from "../agent-defs.js"; +import { hasResolvableSource, normalizeSource, registryDocToAgentDef, resolveAgentById, sandboxCapable } from "../agent-defs.js"; export const agentsRouter: IRouter = Router(); @@ -52,6 +52,7 @@ agentsRouter.get("/agents", async (_req, res, next) => { const { source, sourceUrl } = normalizeSource(r.source); const sCap = sandboxCapable(agent.harness); out.push({ + id: agent.id, name: agent.name, label: agent.label, harness: agent.harness, @@ -85,7 +86,7 @@ agentsRouter.get("/agents/by-source", async (req, res, next) => { if (!url) return res.status(400).json({ error: { code: "BAD_REQUEST", message: "`url` required" } }); const rows = await (await registryColl()).find({}).toArray(); const matches = rows - .map((r) => ({ name: r._id, ...normalizeSource(r.source) })) + .map((r) => ({ id: r._id.toString(), name: r.name, ...normalizeSource(r.source) })) .filter((m) => m.sourceUrl === url); res.json({ url, matches }); } catch (err) { next(err); } @@ -113,26 +114,30 @@ agentsRouter.post("/agents/register", async (req, res, next) => { if (body["source"] !== undefined) set.source = body["source"]; if (typeof body["model"] === "string") set.model = body["model"]; if (typeof body["registeredBy"] === "string") set.registeredBy = body["registeredBy"]; - await (await registryColl()).updateOne( - { _id: name }, - { $set: set, $setOnInsert: { _id: name, registeredAt: now } }, + // Upsert by the unique `name`; Mongo mints the ObjectId `_id` on insert. + const coll = await registryColl(); + await coll.updateOne( + { name }, + { $set: set, $setOnInsert: { name, registeredAt: now } }, { upsert: true }, ); - res.json({ ok: true, name }); + const doc = await coll.findOne({ name }); + res.json({ ok: true, id: doc?._id.toString() ?? null, name }); } catch (err) { next(err); } }); -agentsRouter.patch("/agents/:name", async (req, res, next) => { +agentsRouter.patch("/agents/:id", async (req, res, next) => { try { - const name = req.params["name"]!; + const agent = await resolveAgentById(req.params["id"]!); + if (!agent) return res.status(404).json({ error: { code: "NOT_FOUND" } }); const body = (req.body ?? {}) as Record; const set: Partial = { updatedAt: new Date() }; if (typeof body["label"] === "string") set.label = body["label"]; if (typeof body["harness"] === "string") set.harness = body["harness"]; if (body["source"] !== undefined) set.source = body["source"]; if (typeof body["model"] === "string") set.model = body["model"]; - const r = await (await registryColl()).updateOne({ _id: name }, { $set: set }); - if (r.matchedCount === 0) return res.status(404).json({ error: { code: "NOT_FOUND" } }); + // Update by surrogate id (name stays the immutable FK across collections). + await (await registryColl()).updateOne({ name: agent.name }, { $set: set }); res.json({ ok: true }); } catch (err) { next(err); } }); @@ -142,12 +147,12 @@ agentsRouter.patch("/agents/:name", async (req, res, next) => { // (sessions, chat_sessions, chat pin, logs, messages, schedules). The registry doc // is removed last so a mid-cascade crash leaves the agent listed (and thus // re-deletable) rather than orphaning state under a vanished name. -agentsRouter.delete("/agents/:name", async (req, res, next) => { +agentsRouter.delete("/agents/:id", async (req, res, next) => { try { - const name = req.params["name"]!; + const agent = await resolveAgentById(req.params["id"]!); + if (!agent) return res.status(404).json({ error: { code: "NOT_FOUND" } }); + const name = agent.name; const registry = await registryColl(); - const existing = await registry.findOne({ _id: name }); - if (!existing) return res.status(404).json({ error: { code: "NOT_FOUND" } }); const chatSessions = await chatSessionsColl(); const chatDocs = await chatSessions.find({ agent: name }).toArray(); @@ -175,12 +180,12 @@ agentsRouter.delete("/agents/:name", async (req, res, next) => { const sessionsDeleted = (await sessions.deleteMany({ $or: sessionOr })).deletedCount ?? 0; await chatSessions.deleteMany({ agent: name }); - await (await chatPinsColl()).deleteOne({ _id: name }); + await (await chatPinsColl()).deleteOne({ agentName: name }); const logsDeleted = await agentLogStore.deleteByBot(name); const messagesDeleted = (await (await messagesColl()).deleteMany({ agentName: name })).deletedCount ?? 0; await scheduleStore.deleteByAgent(name); - await registry.deleteOne({ _id: name }); + await registry.deleteOne({ name }); res.json({ ok: true, diff --git a/packages/agentos-server/src/routes/chat.ts b/packages/agentos-server/src/routes/chat.ts index 1396f97..9284005 100644 --- a/packages/agentos-server/src/routes/chat.ts +++ b/packages/agentos-server/src/routes/chat.ts @@ -2,8 +2,8 @@ // deletion. The harness owns sandbox lifecycle; we just orchestrate session // pinning and pipe its SSE back to the browser. // -// POST /agentos/api/agents/:name/chat-sandbox -// DELETE /agentos/api/agents/:name/chat-pin +// POST /agentos/api/agents/:id/chat-sandbox +// DELETE /agentos/api/agents/:id/chat-pin // POST /agentos/api/sandboxes/:id/chat (SSE) // GET /agentos/api/sandboxes/:id/artifact (binary) @@ -12,14 +12,13 @@ import { randomUUID } from "node:crypto"; import { caAuthHeader } from "../auth.js"; import { caBase, pipeUpstream } from "../upstream.js"; import { chatPinsColl, chatSessionsColl } from "../mongo.js"; -import { hasResolvableSource, resolveAgent, sandboxBodyFor, sandboxCapable, srsPolicyForAgent } from "../agent-defs.js"; +import { hasResolvableSource, resolveAgentById, sandboxBodyFor, sandboxCapable, srsPolicyForAgent } from "../agent-defs.js"; export const chatRouter: IRouter = Router(); -chatRouter.post("/agents/:name/chat-sandbox", async (req, res, next) => { +chatRouter.post("/agents/:id/chat-sandbox", async (req, res, next) => { try { - const name = req.params["name"]!; - const agent = await resolveAgent(name); + const agent = await resolveAgentById(req.params["id"]!); if (!agent) return res.status(404).json({ error: { code: "UNKNOWN_AGENT" } }); if (!sandboxCapable(agent.harness)) { return res.status(400).json({ @@ -51,7 +50,7 @@ chatRouter.post("/agents/:name/chat-sandbox", async (req, res, next) => { let sessionId = body.sessionId; if (!sessionId && !body.forceNew) { try { - const pin = await (await chatPinsColl()).findOne({ _id: agent.name }); + const pin = await (await chatPinsColl()).findOne({ agentName: agent.name }); if (pin?.sessionId) sessionId = pin.sessionId; } catch { /* fall through */ } } @@ -96,7 +95,7 @@ chatRouter.post("/agents/:name/chat-sandbox", async (req, res, next) => { result.code === "SANDBOX_CREATE_FAILED" && /already exists and is not an empty directory|destination path .* already exists/i.test(result.detail ?? "") ) { - try { await (await chatPinsColl()).deleteOne({ _id: agent.name }); } catch { /* best-effort */ } + try { await (await chatPinsColl()).deleteOne({ agentName: agent.name }); } catch { /* best-effort */ } sessionId = `agentos-${agent.name}-${randomUUID().slice(0, 12)}`; result = await tryCreate(sessionId); } @@ -110,7 +109,7 @@ chatRouter.post("/agents/:name/chat-sandbox", async (req, res, next) => { try { await (await chatPinsColl()).updateOne( - { _id: agent.name }, + { agentName: agent.name }, { $set: { sessionId, updatedAt: new Date() } }, { upsert: true }, ); @@ -135,9 +134,11 @@ chatRouter.post("/agents/:name/chat-sandbox", async (req, res, next) => { } catch (err) { next(err); } }); -chatRouter.delete("/agents/:name/chat-pin", async (req, res, next) => { +chatRouter.delete("/agents/:id/chat-pin", async (req, res, next) => { try { - await (await chatPinsColl()).deleteOne({ _id: req.params["name"]! }); + const agent = await resolveAgentById(req.params["id"]!); + if (!agent) return res.status(404).json({ error: { code: "UNKNOWN_AGENT" } }); + await (await chatPinsColl()).deleteOne({ agentName: agent.name }); res.json({ ok: true }); } catch (err) { next(err); } }); diff --git a/packages/agentos-server/src/routes/logs.ts b/packages/agentos-server/src/routes/logs.ts index eaa26ab..ff4d083 100644 --- a/packages/agentos-server/src/routes/logs.ts +++ b/packages/agentos-server/src/routes/logs.ts @@ -4,12 +4,20 @@ import { Router, type Router as IRouter } from "express"; import { agentLogStore } from "../stores/agent-log-store.js"; +import { resolveAgentById } from "../agent-defs.js"; export const logsRouter: IRouter = Router(); logsRouter.get("/logs", async (req, res, next) => { try { - const bot = typeof req.query["bot"] === "string" ? req.query["bot"] : undefined; + // Scope by agent id → name (agent_logs key the per-agent `bot` field on name). + const agentId = typeof req.query["agentId"] === "string" ? req.query["agentId"] : undefined; + let bot: string | undefined; + if (agentId) { + const agent = await resolveAgentById(agentId); + if (!agent) return res.json({ logs: [] }); + bot = agent.name; + } const limit = req.query["limit"] ? parseInt(String(req.query["limit"]), 10) : 50; const beforeRaw = typeof req.query["before"] === "string" ? req.query["before"] : undefined; const before = beforeRaw ? new Date(beforeRaw) : undefined; diff --git a/packages/agentos-server/src/routes/policies.ts b/packages/agentos-server/src/routes/policies.ts index 231c29a..984bd8f 100644 --- a/packages/agentos-server/src/routes/policies.ts +++ b/packages/agentos-server/src/routes/policies.ts @@ -14,7 +14,8 @@ // the UI's empty states still render. import { Router, type Router as IRouter, type Response } from "express"; -import { getDb } from "../mongo.js"; +import { agentPoliciesColl } from "../mongo.js"; +import { resolveAgentById } from "../agent-defs.js"; export const policiesRouter: IRouter = Router(); @@ -109,37 +110,34 @@ policiesRouter.delete("/opa-policies/:id", (req, res) => ); // ── Per-agent policy binding (agentos-local, Mongo) ─────────────────────── -interface PolicyBindingDoc { - _id: string; // agent name - policyId: string; - updatedAt: Date; -} - -async function bindingsColl() { - return (await getDb()).collection("agent_policies"); -} +// Addressed by the registry ObjectId; stored keyed on the agent NAME +// (`agentName`) so srsPolicyForAgent — called name-side at sandbox/run create — +// resolves the same row. -policiesRouter.get("/agents/:name/policy", async (req, res, next) => { +policiesRouter.get("/agents/:id/policy", async (req, res, next) => { try { - const doc = await (await bindingsColl()).findOne({ _id: req.params["name"]! }); + const agent = await resolveAgentById(req.params["id"]!); + if (!agent) return res.status(404).json({ error: { code: "UNKNOWN_AGENT" } }); + const doc = await (await agentPoliciesColl()).findOne({ agentName: agent.name }); res.json({ binding: doc ? { policyId: doc.policyId } : null }); } catch (err) { next(err); } }); -policiesRouter.put("/agents/:name/policy", async (req, res, next) => { +policiesRouter.put("/agents/:id/policy", async (req, res, next) => { try { - const name = req.params["name"]!; + const agent = await resolveAgentById(req.params["id"]!); + if (!agent) return res.status(404).json({ error: { code: "UNKNOWN_AGENT" } }); const body = (req.body ?? {}) as Record; const policyId = typeof body["policy_id"] === "string" ? (body["policy_id"] as string) : null; - const coll = await bindingsColl(); + const coll = await agentPoliciesColl(); if (!policyId) { - await coll.deleteOne({ _id: name }); + await coll.deleteOne({ agentName: agent.name }); res.json({ binding: null }); return; } - await coll.updateOne({ _id: name }, { $set: { policyId, updatedAt: new Date() } }, { upsert: true }); + await coll.updateOne({ agentName: agent.name }, { $set: { policyId, updatedAt: new Date() } }, { upsert: true }); res.json({ binding: { policyId } }); } catch (err) { next(err); diff --git a/packages/agentos-server/src/routes/run.ts b/packages/agentos-server/src/routes/run.ts index a3f759f..89dded5 100644 --- a/packages/agentos-server/src/routes/run.ts +++ b/packages/agentos-server/src/routes/run.ts @@ -4,14 +4,13 @@ import { Router, type Router as IRouter } from "express"; import { caAuthHeader } from "../auth.js"; import { caBase, pipeUpstream } from "../upstream.js"; -import { resolveAgent, runBodyFor, srsPolicyForAgent } from "../agent-defs.js"; +import { resolveAgentById, runBodyFor, srsPolicyForAgent } from "../agent-defs.js"; export const runRouter: IRouter = Router(); -runRouter.post("/agents/:name/run", async (req, res, next) => { +runRouter.post("/agents/:id/run", async (req, res, next) => { try { - const name = req.params["name"]!; - const agent = await resolveAgent(name); + const agent = await resolveAgentById(req.params["id"]!); if (!agent) return res.status(404).json({ error: { code: "UNKNOWN_AGENT" } }); const message = String((req.body as Record | undefined)?.["message"] ?? ""); diff --git a/packages/agentos-server/src/routes/schedules.ts b/packages/agentos-server/src/routes/schedules.ts index 772fbe3..2aa2a8d 100644 --- a/packages/agentos-server/src/routes/schedules.ts +++ b/packages/agentos-server/src/routes/schedules.ts @@ -9,7 +9,7 @@ import { type ScheduleKind, } from "../stores/schedule-store.js"; import { agentLogStore } from "../stores/agent-log-store.js"; -import { resolveAgent } from "../agent-defs.js"; +import { resolveAgent, resolveAgentById } from "../agent-defs.js"; import { runAgentOnce } from "../scheduler.js"; export const schedulesRouter: IRouter = Router(); @@ -20,8 +20,15 @@ const withDesc = { try { - const agent = typeof req.query["agent"] === "string" ? req.query["agent"] : undefined; - const list = await scheduleStore.list(agent); + // Scope by agent id → name (schedules key on agentName). + const agentId = typeof req.query["agentId"] === "string" ? req.query["agentId"] : undefined; + let agentName: string | undefined; + if (agentId) { + const agent = await resolveAgentById(agentId); + if (!agent) return res.json({ schedules: [] }); + agentName = agent.name; + } + const list = await scheduleStore.list(agentName); res.json({ schedules: list.map(withDesc) }); } catch (err) { next(err); } }); @@ -29,10 +36,12 @@ schedulesRouter.get("/schedules", async (req, res, next) => { schedulesRouter.post("/schedules", async (req, res, next) => { try { const b = (req.body ?? {}) as Record; - const agentName = String(b.agentName ?? ""); - if (!agentName || !(await resolveAgent(agentName))) { + // Body carries the agent id; resolve to the name the schedule store stores. + const agent = b.agentId ? await resolveAgentById(String(b.agentId)) : undefined; + if (!agent) { return res.status(400).json({ error: { code: "UNKNOWN_AGENT" } }); } + const agentName = agent.name; if (!b.prompt || !String(b.prompt).trim()) { return res.status(400).json({ error: { code: "MISSING_PROMPT" } }); } diff --git a/packages/agentos-server/src/routes/sessions.ts b/packages/agentos-server/src/routes/sessions.ts index 1eda304..22bbdbf 100644 --- a/packages/agentos-server/src/routes/sessions.ts +++ b/packages/agentos-server/src/routes/sessions.ts @@ -10,18 +10,44 @@ import { Router, type Router as IRouter } from "express"; import { chatPinsColl, chatSessionsColl, messagesColl, sessionsColl } from "../mongo.js"; import { agentLogStore } from "../stores/agent-log-store.js"; import { deleteAgentSnapshots, disposeLiveSandboxes } from "../cleanup.js"; +import { resolveAgentById } from "../agent-defs.js"; import { warmSessions } from "../upstream.js"; export const sessionsRouter: IRouter = Router(); +// The durable `sessions` row is keyed by the harness sessionId (the pinned +// store unifies `_id` across chat_sessions / transcript / gitagent). As a +// safety net for rows NOT written through the pin (older sessions, or engines +// that derive their own key), we also match by `projectKey` suffix. The Claude +// CLI derives projectKey from the workdir path, replacing path separators, +// spaces, and other punctuation with "-": a sessionId like +// "agentos-General Agent-abc" lands as "...-agentos-General-Agent-abc". So a +// literal regex with the original space never matches. Build a LOOSE suffix +// regex where every run of non-alphanumerics in the id matches one-or-more +// non-alphanumerics in the stored projectKey. +function looseProjectKeySuffix(id: string): string { + const tokens = id + .split(/[^a-zA-Z0-9]+/) + .filter(Boolean) + .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); + return `${tokens.join("[^a-zA-Z0-9]+")}$`; +} + sessionsRouter.get("/sessions", async (req, res, next) => { try { - const bot = typeof req.query["bot"] === "string" ? req.query["bot"] : undefined; + const agentId = typeof req.query["agentId"] === "string" ? req.query["agentId"] : undefined; const limit = Math.min( Math.max(parseInt(String(req.query["limit"] ?? "50"), 10) || 50, 1), 200, ); - const q = bot ? { agent: bot } : {}; + // Scope to one agent by resolving its id → name (chat_sessions keys on name). + // An id that doesn't resolve returns no sessions rather than leaking all. + let q: Record = {}; + if (agentId) { + const agent = await resolveAgentById(agentId); + if (!agent) return res.json({ sessions: [] }); + q = { agent: agent.name }; + } const [docs, warm] = await Promise.all([ (await chatSessionsColl()).find(q).sort({ lastMessageAt: -1 }).limit(limit).toArray(), warmSessions(), @@ -42,10 +68,9 @@ sessionsRouter.get("/sessions/:id", async (req, res, next) => { try { const id = req.params["id"]!; const sessions = await sessionsColl(); - const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const session = (await sessions.findOne({ _id: id })) ?? - (await sessions.findOne({ projectKey: { $regex: `${escapedId}$` } })); + (await sessions.findOne({ projectKey: { $regex: looseProjectKeySuffix(id) } })); const [chat, warm] = await Promise.all([ (await chatSessionsColl()).findOne({ _id: id }), warmSessions(), @@ -83,14 +108,16 @@ sessionsRouter.get("/sessions/:id", async (req, res, next) => { // Hard delete one session — disposes its live sandbox (no auto-save), deletes // its S3 snapshots, and removes the session transcript + chat_sessions row + // logs + messages. The S3 prefix is per-agent, so the owning agent is resolved -// from the chat_sessions row's `agent`; pass `?bot=` for sessions that +// from the chat_sessions row's `agent`; pass `?agentId=` for sessions that // never got one. The chat pin is only cleared when it points at this session. sessionsRouter.delete("/sessions/:id", async (req, res, next) => { try { const id = req.params["id"]!; const chatSessions = await chatSessionsColl(); const chat = await chatSessions.findOne({ _id: id }); - const bot = (typeof req.query["bot"] === "string" && req.query["bot"]) || chat?.agent || null; + const agentId = typeof req.query["agentId"] === "string" ? req.query["agentId"] : undefined; + const fallback = agentId ? (await resolveAgentById(agentId))?.name : undefined; + const bot = chat?.agent || fallback || null; const warnings: string[] = []; const disp = await disposeLiveSandboxes(new Set([id])); @@ -105,15 +132,14 @@ sessionsRouter.delete("/sessions/:id", async (req, res, next) => { } const sessions = await sessionsColl(); - const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const sessionsDeleted = (await sessions.deleteMany({ - $or: [{ _id: id }, { projectKey: { $regex: `${escaped}$` } }], + $or: [{ _id: id }, { projectKey: { $regex: looseProjectKeySuffix(id) } }], })).deletedCount ?? 0; await chatSessions.deleteOne({ _id: id }); const logsDeleted = await agentLogStore.deleteBySession(id); const messagesDeleted = (await (await messagesColl()).deleteMany({ sessionId: id })).deletedCount ?? 0; - if (bot) await (await chatPinsColl()).deleteOne({ _id: bot, sessionId: id }); + if (bot) await (await chatPinsColl()).deleteOne({ agentName: bot, sessionId: id }); res.json({ ok: true, diff --git a/packages/agentos-server/src/stores/telemetry-projection.ts b/packages/agentos-server/src/stores/telemetry-projection.ts index 0b775c0..580e5b5 100644 --- a/packages/agentos-server/src/stores/telemetry-projection.ts +++ b/packages/agentos-server/src/stores/telemetry-projection.ts @@ -138,11 +138,13 @@ async function onSessionStarted(ev: IngestEvent): Promise { ? librarySourceFor(name, payload, description) : inlineSourceFor(name, payload, description); - // agent_registry upsert (idempotent on agent name). + // agent_registry upsert (idempotent on agent name). Mongo mints the + // surrogate ObjectId `_id` on first insert; `name` is the unique key the + // Python/library ingest addresses agents by. await (await registryColl()).updateOne( - { _id: name }, + { name }, { - $setOnInsert: { _id: name, registeredAt: now }, + $setOnInsert: { name, registeredAt: now }, $set: { harness: "claude-agent-sdk", source, diff --git a/packages/runtime-local/assets/harness-bundle.mjs b/packages/runtime-local/assets/harness-bundle.mjs index fc972c8..9a4c585 100644 --- a/packages/runtime-local/assets/harness-bundle.mjs +++ b/packages/runtime-local/assets/harness-bundle.mjs @@ -14671,10 +14671,10 @@ var init_zod = __esm(() => { init_external(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/_virtual/_rolldown/runtime.js +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/_virtual/_rolldown/runtime.js var init_runtime = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/_virtual/_rolldown/runtime.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/_virtual/_rolldown/runtime.js var __defProp2, __exportAll = (all, no_symbols) => { let target = {}; for (var name in all) @@ -14690,7 +14690,7 @@ var init_runtime2 = __esm(() => { __defProp2 = Object.defineProperty; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/namespace.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/namespace.js function createNamespace(path) { const symbol2 = Symbol.for(path); return { @@ -14722,7 +14722,7 @@ var init_namespace = __esm(() => { ns = createNamespace("langchain"); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/errors/index.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/errors/index.js function addLangChainErrorFields(error51, lc_error_code) { error51.lc_error_code = lc_error_code; error51.message = `${error51.message} @@ -14773,7 +14773,7 @@ var init_errors3 = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/content/data.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/content/data.js function isDataContentBlock(content_block) { return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); } @@ -14869,7 +14869,7 @@ function convertToProviderContentBlock(block, converter) { } var init_data = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/map_keys.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/map_keys.js function snakeCase(key) { return key.replace(UPPER_TO_WORD_BOUNDARY, "$1_$2").replace(LOWER_TO_UPPER_BOUNDARY, "$1_$2").replace(SEPARATORS, "_").toLowerCase(); } @@ -14899,7 +14899,7 @@ var init_map_keys = __esm(() => { SEPARATORS = /[-_\s]+/g; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/validation.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/validation.js function needsEscaping(obj) { return "lc" in obj || Object.keys(obj).length === 1 && "__lc_escaped__" in obj; } @@ -14966,7 +14966,7 @@ function unescapeValue(obj) { var LC_ESCAPED_KEY = "__lc_escaped__"; var init_validation = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/serializable.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/serializable.js function shallowCopy(obj) { return Array.isArray(obj) ? [...obj] : { ...obj }; } @@ -15082,7 +15082,7 @@ var init_serializable = __esm(() => { }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/utils.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/utils.js function _isContentBlock(block, type) { return _isObject(block) && block.type === type; } @@ -15111,7 +15111,7 @@ function safeParseJson(value) { var iife = (fn) => fn(); var init_utils = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/anthropic.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/anthropic.js function convertAnthropicAnnotation(citation) { if (citation.type === "char_location" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) { const { document_title, start_char_index, end_char_index, cited_text, ...rest } = citation; @@ -15426,7 +15426,7 @@ var init_anthropic = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/data.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/data.js function convertToV1FromDataContentBlock(block) { if (isURLContentBlock(block)) return { @@ -15504,7 +15504,7 @@ var init_data2 = __esm(() => { init_utils(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/openai.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/openai.js function convertToV1FromChatCompletions(message) { const blocks = []; if (typeof message.content === "string") { @@ -15811,13 +15811,13 @@ var init_openai = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/message.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/message.js function isMessage(message) { return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content)); } var init_message = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/format.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/format.js function convertToFormattedString(message, format = "pretty") { if (format === "pretty") return convertToPrettyString(message); @@ -15858,7 +15858,7 @@ function convertToPrettyString(message) { } var init_format = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/base.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/base.js function contentBlocksFromNonStringFirst(firstContent) { if (Array.isArray(firstContent)) return firstContent; @@ -16215,7 +16215,7 @@ var init_base = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js function convertFileFormatToMimeType(format) { switch (format) { case "csv": @@ -16456,7 +16456,7 @@ var init_bedrock_converse = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/deepseek.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/deepseek.js function convertToV1FromDeepSeekMessage(message) { const blocks = []; const reasoningContent = message.additional_kwargs?.reasoning_content; @@ -16496,7 +16496,7 @@ var init_deepseek = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/google_genai.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/google_genai.js function convertToV1FromChatGoogleMessage(message) { function* iterateContent() { const content = typeof message.content === "string" ? [{ @@ -16575,7 +16575,7 @@ var init_google_genai = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js function convertToV1FromChatVertexMessage(message) { function* iterateContent() { const content = typeof message.content === "string" ? [{ @@ -16660,7 +16660,7 @@ var init_google_vertexai = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/groq.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/groq.js function convertToV1FromGroqMessage(message) { const blocks = []; const parsedReasoning = message.additional_kwargs?.reasoning; @@ -16724,7 +16724,7 @@ var init_groq = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/ollama.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/ollama.js function convertToV1FromOllamaMessage(message) { const blocks = []; const reasoningContent = message.additional_kwargs?.reasoning_content; @@ -16764,7 +16764,76 @@ var init_ollama = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/xai.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/openrouter.js +function convertToV1FromOpenRouterMessage(message) { + const blocks = []; + const reasoningDetails = message.additional_kwargs?.reasoning_details; + let hasVisibleReasoningFromDetails = false; + if (Array.isArray(reasoningDetails) && reasoningDetails.length > 0) + for (const detail of reasoningDetails) { + if (detail == null || typeof detail !== "object") + continue; + const type = detail.type; + if (type === "reasoning.summary") { + const summary = detail.summary; + if (_isString(summary) && summary.length > 0) { + blocks.push({ + type: "reasoning", + reasoning: summary + }); + hasVisibleReasoningFromDetails = true; + } + } else if (type === "reasoning.text") { + const text = detail.text; + if (_isString(text) && text.length > 0) { + blocks.push({ + type: "reasoning", + reasoning: text + }); + hasVisibleReasoningFromDetails = true; + } + } + } + if (!hasVisibleReasoningFromDetails) { + const reasoningContent = message.additional_kwargs?.reasoning_content; + if (_isString(reasoningContent) && reasoningContent.length > 0) + blocks.push({ + type: "reasoning", + reasoning: reasoningContent + }); + } + if (typeof message.content === "string") { + if (message.content.length > 0) + blocks.push({ + type: "text", + text: message.content + }); + } else + for (const block of message.content) + if (typeof block === "object" && "type" in block && block.type === "text" && "text" in block && _isString(block.text)) + blocks.push({ + type: "text", + text: block.text + }); + for (const toolCall of message.tool_calls ?? []) + blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +var ChatOpenRouterTranslator; +var init_openrouter = __esm(() => { + init_utils(); + ChatOpenRouterTranslator = { + translateContent: convertToV1FromOpenRouterMessage, + translateContentChunk: convertToV1FromOpenRouterMessage + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/xai.js function convertToV1FromXAIMessage(message) { const blocks = []; if (_isObject(message.additional_kwargs?.reasoning)) { @@ -16819,7 +16888,7 @@ var init_xai = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/google.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/google.js function convertToV1FromChatGoogleMessage2(message) { function* iterateContent() { const content = iife(() => { @@ -16930,7 +16999,7 @@ var init_google = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/block_translators/index.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/block_translators/index.js function getTranslator(modelProvider) { return globalThis.lc_block_translators_registry.get(modelProvider); } @@ -16943,6 +17012,7 @@ var init_block_translators = __esm(() => { init_google_vertexai(); init_groq(); init_ollama(); + init_openrouter(); init_xai(); init_google(); globalThis.lc_block_translators_registry ??= new Map([ @@ -16955,11 +17025,12 @@ var init_block_translators = __esm(() => { ["groq", ChatGroqTranslator], ["ollama", ChatOllamaTranslator], ["openai", ChatOpenAITranslator], + ["openrouter", ChatOpenRouterTranslator], ["xai", ChatXAITranslator] ]); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/metadata.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/metadata.js function mergeResponseMetadata(a, b) { return _mergeDicts(a, b) ?? {}; } @@ -17004,7 +17075,7 @@ var init_metadata = __esm(() => { init_base(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/tool.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/tool.js function isDirectToolOutput(x) { return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; } @@ -17124,7 +17195,7 @@ var init_tool = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tools/utils.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tools/utils.js function _isToolCall(toolCall) { return !!(toolCall && typeof toolCall === "object" && ("type" in toolCall) && toolCall.type === "tool_call"); } @@ -17142,7 +17213,7 @@ var init_utils2 = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/json.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/json.js function parseJsonMarkdown(s, parser = parsePartialJson) { s = s.trim(); const firstFenceIndex = s.indexOf("```"); @@ -17390,7 +17461,7 @@ function parsePartialJson(s) { } var init_json = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/chat.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/chat.js function isChatMessage(x) { return x._getType() === "generic"; } @@ -17465,7 +17536,7 @@ var init_chat = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/function.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/function.js function isFunctionMessage(x) { return x._getType() === "function"; } @@ -17504,7 +17575,7 @@ var init_function = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/human.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/human.js function isHumanMessage(x) { return x.getType() === "human"; } @@ -17549,7 +17620,7 @@ var init_human = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/modifier.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/modifier.js var RemoveMessage; var init_modifier = __esm(() => { init_base(); @@ -17575,7 +17646,7 @@ var init_modifier = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/system.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/system.js function isSystemMessage(x) { return x._getType() === "system"; } @@ -17645,7 +17716,10 @@ var init_system = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/utils.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/utils.js +function chunkUsesRawInputArgs(chunk) { + return chunk.isCustomTool === true; +} function _coerceToolCall(toolCall) { if (_isToolCall(toolCall)) return toolCall; @@ -17899,10 +17973,21 @@ function collapseToolCallChunks(chunks) { const invalidToolCalls = []; for (const chunks2 of groupedToolCallChunks) { let parsedArgs = null; + const usesRawInputArgs = chunks2.some(chunkUsesRawInputArgs); const name = chunks2[0]?.name ?? ""; - const joinedArgs = chunks2.map((c) => c.args || "").join("").trim(); + const joinedArgsRaw = chunks2.map((c) => c.args || "").join(""); + const joinedArgs = usesRawInputArgs ? joinedArgsRaw : joinedArgsRaw.trim(); const argsStr = joinedArgs.length ? joinedArgs : "{}"; - const id = chunks2[0]?.id; + const id = chunks2.find((c) => c.id)?.id ?? chunks2[0]?.id; + if (usesRawInputArgs && id) { + toolCalls.push({ + name, + args: { input: joinedArgs }, + id, + type: "tool_call" + }); + continue; + } try { parsedArgs = parsePartialJson(argsStr); if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) @@ -17944,7 +18029,7 @@ var init_utils3 = __esm(() => { init_system(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/ai.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/ai.js function isAIMessage(x) { return x._getType() === "ai"; } @@ -18187,7 +18272,7 @@ Please upgrade your packages to versions that set`, }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/env.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/env.js function getRuntimeEnvironment() { if (runtimeEnvironment === undefined) runtimeEnvironment = { @@ -18238,13 +18323,21 @@ var init_env = __esm(() => { }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/regex.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/max.js +var max_default = "ffffffff-ffff-ffff-ffff-ffffffffffff"; +var init_max = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/nil.js +var nil_default = "00000000-0000-0000-0000-000000000000"; +var init_nil = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/regex.js var regex_default2; var init_regex = __esm(() => { regex_default2 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/validate.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/validate.js function validate2(uuid3) { return typeof uuid3 === "string" && regex_default2.test(uuid3); } @@ -18252,7 +18345,18 @@ var init_validate = __esm(() => { init_regex(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/stringify.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/parse.js +function parse6(uuid3) { + if (!validate2(uuid3)) + throw TypeError("Invalid UUID"); + let v; + return Uint8Array.of((v = parseInt(uuid3.slice(0, 8), 16)) >>> 24, v >>> 16 & 255, v >>> 8 & 255, v & 255, (v = parseInt(uuid3.slice(9, 13), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(14, 18), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(19, 23), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(24, 36), 16)) / 1099511627776 & 255, v / 4294967296 & 255, v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255); +} +var init_parse3 = __esm(() => { + init_validate(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/stringify.js function unsafeStringify2(arr, offset = 0) { return (byteToHex2[arr[offset + 0]] + byteToHex2[arr[offset + 1]] + byteToHex2[arr[offset + 2]] + byteToHex2[arr[offset + 3]] + "-" + byteToHex2[arr[offset + 4]] + byteToHex2[arr[offset + 5]] + "-" + byteToHex2[arr[offset + 6]] + byteToHex2[arr[offset + 7]] + "-" + byteToHex2[arr[offset + 8]] + byteToHex2[arr[offset + 9]] + "-" + byteToHex2[arr[offset + 10]] + byteToHex2[arr[offset + 11]] + byteToHex2[arr[offset + 12]] + byteToHex2[arr[offset + 13]] + byteToHex2[arr[offset + 14]] + byteToHex2[arr[offset + 15]]).toLowerCase(); } @@ -18270,7 +18374,7 @@ var init_stringify = __esm(() => { byteToHex2.push((i + 256).toString(16).slice(1)); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/rng.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/rng.js function rng() { return crypto.getRandomValues(rnds8); } @@ -18279,7 +18383,272 @@ var init_rng = __esm(() => { rnds8 = new Uint8Array(16); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/v7.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v1.js +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === "_v6") + options = undefined; + } + if (options) + bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + else { + const now = Date.now(); + const rnds = rng(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? unsafeStringify2(bytes); +} +function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 1e4) { + state.node = undefined; + state.nsecs = 0; + } + } else if (now > state.msecs) + state.nsecs = 0; + else if (now < state.msecs) + state.node = undefined; + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 1; + state.clockseq = (rnds[8] << 8 | rnds[9]) & 16383; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) + throw new Error("Random bytes length must be >= 16"); + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } else if (offset < 0 || offset + 16 > buf.length) + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= (rnds[8] << 8 | rnds[9]) & 16383; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + buf[offset++] = tl >>> 24 & 255; + buf[offset++] = tl >>> 16 & 255; + buf[offset++] = tl >>> 8 & 255; + buf[offset++] = tl & 255; + const tmh = msecs / 4294967296 * 1e4 & 268435455; + buf[offset++] = tmh >>> 8 & 255; + buf[offset++] = tmh & 255; + buf[offset++] = tmh >>> 24 & 15 | 16; + buf[offset++] = tmh >>> 16 & 255; + buf[offset++] = clockseq >>> 8 | 128; + buf[offset++] = clockseq & 255; + for (let n = 0;n < 6; ++n) + buf[offset++] = node[n]; + return buf; +} +var _state; +var init_v1 = __esm(() => { + init_stringify(); + init_rng(); + _state = {}; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v4.js +function v4(options, buf, offset) { + if (!buf && !options && crypto.randomUUID) + return crypto.randomUUID(); + return _v4(options, buf, offset); +} +function _v4(options, buf, offset) { + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) + throw new Error("Random bytes length must be >= 16"); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0;i < 16; ++i) + buf[offset + i] = rnds[i]; + return buf; + } + return unsafeStringify2(rnds); +} +var init_v4 = __esm(() => { + init_stringify(); + init_rng(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/sha1.js +function f(s, x, y, z2) { + switch (s) { + case 0: + return x & y ^ ~x & z2; + case 1: + return x ^ y ^ z2; + case 2: + return x & y ^ x & z2 ^ y & z2; + case 3: + return x ^ y ^ z2; + } +} +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} +function sha12(bytes) { + const K = [ + 1518500249, + 1859775393, + 2400959708, + 3395469782 + ]; + const H = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 128; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0;i < N; ++i) { + const arr = new Uint32Array(16); + for (let j = 0;j < 16; ++j) + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + M[i] = arr; + } + M[N - 1][14] = (bytes.length - 1) * 8 / 2 ** 32; + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295; + for (let i = 0;i < N; ++i) { + const W = new Uint32Array(80); + for (let t = 0;t < 16; ++t) + W[t] = M[i][t]; + for (let t = 16;t < 80; ++t) + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0;t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +var init_sha1 = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v35.js +function stringToBytes2(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0;i < str.length; ++i) + bytes[i] = str.charCodeAt(i); + return bytes; +} +function v352(version2, hash2, value, namespace, buf, offset) { + const valueBytes = typeof value === "string" ? stringToBytes2(value) : value; + const namespaceBytes = typeof namespace === "string" ? parse6(namespace) : namespace; + if (typeof namespace === "string") + namespace = parse6(namespace); + if (namespace?.length !== 16) + throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash2(bytes); + bytes[6] = bytes[6] & 15 | version2; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset ??= 0; + if (offset < 0 || offset + 16 > buf.length) + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0;i < 16; ++i) + buf[offset + i] = bytes[i]; + return buf; + } + return unsafeStringify2(bytes); +} +var DNS2 = "6ba7b810-9dad-11d1-80b4-00c04fd430c8", URL3 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +var init_v35 = __esm(() => { + init_parse3(); + init_stringify(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v5.js +function v52(value, namespace, buf, offset) { + return v352(80, sha12, value, namespace, buf, offset); +} +var init_v5 = __esm(() => { + init_sha1(); + init_v35(); + v52.DNS = DNS2; + v52.URL = URL3; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v1ToV6.js +function v1ToV6(uuid3) { + const v6Bytes = _v1ToV6(typeof uuid3 === "string" ? parse6(uuid3) : uuid3); + return typeof uuid3 === "string" ? unsafeStringify2(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes2) { + return Uint8Array.of((v1Bytes2[6] & 15) << 4 | v1Bytes2[7] >> 4 & 15, (v1Bytes2[7] & 15) << 4 | (v1Bytes2[4] & 240) >> 4, (v1Bytes2[4] & 15) << 4 | (v1Bytes2[5] & 240) >> 4, (v1Bytes2[5] & 15) << 4 | (v1Bytes2[0] & 240) >> 4, (v1Bytes2[0] & 15) << 4 | (v1Bytes2[1] & 240) >> 4, (v1Bytes2[1] & 15) << 4 | (v1Bytes2[2] & 240) >> 4, 96 | v1Bytes2[2] & 15, v1Bytes2[3], v1Bytes2[8], v1Bytes2[9], v1Bytes2[10], v1Bytes2[11], v1Bytes2[12], v1Bytes2[13], v1Bytes2[14], v1Bytes2[15]); +} +var init_v1ToV6 = __esm(() => { + init_parse3(); + init_stringify(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v6.js +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1({ + ...options, + _v6: true + }, new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + if (offset < 0 || offset + 16 > buf.length) + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + for (let i = 0;i < 16; i++) + buf[offset + i] = bytes[i]; + return buf; + } + return unsafeStringify2(bytes); +} +var init_v6 = __esm(() => { + init_stringify(); + init_v1(); + init_v1ToV6(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/v7.js function v7(options, buf, offset) { let bytes; if (options) @@ -18287,8 +18656,8 @@ function v7(options, buf, offset) { else { const now = Date.now(); const rnds = rng(); - updateV7State(_state, now, rnds); - bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + updateV7State(_state2, now, rnds); + bytes = v7Bytes(rnds, _state2.msecs, _state2.seq, buf, offset); } return buf ?? unsafeStringify2(bytes); } @@ -18333,261 +18702,14 @@ function v7Bytes(rnds, msecs, seq, buf, offset = 0) { buf[offset++] = rnds[15]; return buf; } -var _state; -var init_v7 = __esm(() => { - init_stringify(); - init_rng(); - _state = {}; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/max.js -var max_default = "ffffffff-ffff-ffff-ffff-ffffffffffff"; -var init_max = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/nil.js -var nil_default = "00000000-0000-0000-0000-000000000000"; -var init_nil = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/parse.js -function parse6(uuid3) { - if (!validate2(uuid3)) - throw TypeError("Invalid UUID"); - let v; - return Uint8Array.of((v = parseInt(uuid3.slice(0, 8), 16)) >>> 24, v >>> 16 & 255, v >>> 8 & 255, v & 255, (v = parseInt(uuid3.slice(9, 13), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(14, 18), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(19, 23), 16)) >>> 8, v & 255, (v = parseInt(uuid3.slice(24, 36), 16)) / 1099511627776 & 255, v / 4294967296 & 255, v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255); -} -var init_parse3 = __esm(() => { - init_validate(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/v1.js -function v1(options, buf, offset) { - let bytes; - const isV6 = options?._v6 ?? false; - if (options) { - const optionsKeys = Object.keys(options); - if (optionsKeys.length === 1 && optionsKeys[0] === "_v6") - options = undefined; - } - if (options) - bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); - else { - const now = Date.now(); - const rnds = rng(); - updateV1State(_state2, now, rnds); - bytes = v1Bytes(rnds, _state2.msecs, _state2.nsecs, isV6 ? undefined : _state2.clockseq, isV6 ? undefined : _state2.node, buf, offset); - } - return buf ?? unsafeStringify2(bytes); -} -function updateV1State(state, now, rnds) { - state.msecs ??= -Infinity; - state.nsecs ??= 0; - if (now === state.msecs) { - state.nsecs++; - if (state.nsecs >= 1e4) { - state.node = undefined; - state.nsecs = 0; - } - } else if (now > state.msecs) - state.nsecs = 0; - else if (now < state.msecs) - state.node = undefined; - if (!state.node) { - state.node = rnds.slice(10, 16); - state.node[0] |= 1; - state.clockseq = (rnds[8] << 8 | rnds[9]) & 16383; - } - state.msecs = now; - return state; -} -function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { - if (rnds.length < 16) - throw new Error("Random bytes length must be >= 16"); - if (!buf) { - buf = new Uint8Array(16); - offset = 0; - } else if (offset < 0 || offset + 16 > buf.length) - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); - msecs ??= Date.now(); - nsecs ??= 0; - clockseq ??= (rnds[8] << 8 | rnds[9]) & 16383; - node ??= rnds.slice(10, 16); - msecs += 12219292800000; - const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; - buf[offset++] = tl >>> 24 & 255; - buf[offset++] = tl >>> 16 & 255; - buf[offset++] = tl >>> 8 & 255; - buf[offset++] = tl & 255; - const tmh = msecs / 4294967296 * 1e4 & 268435455; - buf[offset++] = tmh >>> 8 & 255; - buf[offset++] = tmh & 255; - buf[offset++] = tmh >>> 24 & 15 | 16; - buf[offset++] = tmh >>> 16 & 255; - buf[offset++] = clockseq >>> 8 | 128; - buf[offset++] = clockseq & 255; - for (let n = 0;n < 6; ++n) - buf[offset++] = node[n]; - return buf; -} var _state2; -var init_v1 = __esm(() => { +var init_v7 = __esm(() => { init_stringify(); init_rng(); _state2 = {}; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/v4.js -function v4(options, buf, offset) { - if (!buf && !options && crypto.randomUUID) - return crypto.randomUUID(); - return _v4(options, buf, offset); -} -function _v4(options, buf, offset) { - options = options || {}; - const rnds = options.random ?? options.rng?.() ?? rng(); - if (rnds.length < 16) - throw new Error("Random bytes length must be >= 16"); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - offset = offset || 0; - if (offset < 0 || offset + 16 > buf.length) - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); - for (let i = 0;i < 16; ++i) - buf[offset + i] = rnds[i]; - return buf; - } - return unsafeStringify2(rnds); -} -var init_v4 = __esm(() => { - init_stringify(); - init_rng(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/sha1.js -function f(s, x, y, z2) { - switch (s) { - case 0: - return x & y ^ ~x & z2; - case 1: - return x ^ y ^ z2; - case 2: - return x & y ^ x & z2 ^ y & z2; - case 3: - return x ^ y ^ z2; - } -} -function ROTL(x, n) { - return x << n | x >>> 32 - n; -} -function sha12(bytes) { - const K = [ - 1518500249, - 1859775393, - 2400959708, - 3395469782 - ]; - const H = [ - 1732584193, - 4023233417, - 2562383102, - 271733878, - 3285377520 - ]; - const newBytes = new Uint8Array(bytes.length + 1); - newBytes.set(bytes); - newBytes[bytes.length] = 128; - bytes = newBytes; - const l = bytes.length / 4 + 2; - const N = Math.ceil(l / 16); - const M = new Array(N); - for (let i = 0;i < N; ++i) { - const arr = new Uint32Array(16); - for (let j = 0;j < 16; ++j) - arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; - M[i] = arr; - } - M[N - 1][14] = (bytes.length - 1) * 8 / 2 ** 32; - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 4294967295; - for (let i = 0;i < N; ++i) { - const W = new Uint32Array(80); - for (let t = 0;t < 16; ++t) - W[t] = M[i][t]; - for (let t = 16;t < 80; ++t) - W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); - let a = H[0]; - let b = H[1]; - let c = H[2]; - let d = H[3]; - let e = H[4]; - for (let t = 0;t < 80; ++t) { - const s = Math.floor(t / 20); - const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; - } - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); -} -var init_sha1 = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/v35.js -function stringToBytes2(str) { - str = unescape(encodeURIComponent(str)); - const bytes = new Uint8Array(str.length); - for (let i = 0;i < str.length; ++i) - bytes[i] = str.charCodeAt(i); - return bytes; -} -function v352(version2, hash2, value, namespace, buf, offset) { - const valueBytes = typeof value === "string" ? stringToBytes2(value) : value; - const namespaceBytes = typeof namespace === "string" ? parse6(namespace) : namespace; - if (typeof namespace === "string") - namespace = parse6(namespace); - if (namespace?.length !== 16) - throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); - let bytes = new Uint8Array(16 + valueBytes.length); - bytes.set(namespaceBytes); - bytes.set(valueBytes, namespaceBytes.length); - bytes = hash2(bytes); - bytes[6] = bytes[6] & 15 | version2; - bytes[8] = bytes[8] & 63 | 128; - if (buf) { - offset ??= 0; - if (offset < 0 || offset + 16 > buf.length) - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); - for (let i = 0;i < 16; ++i) - buf[offset + i] = bytes[i]; - return buf; - } - return unsafeStringify2(bytes); -} -var DNS2 = "6ba7b810-9dad-11d1-80b4-00c04fd430c8", URL3 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; -var init_v35 = __esm(() => { - init_parse3(); - init_stringify(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/v5.js -function v52(value, namespace, buf, offset) { - return v352(80, sha12, value, namespace, buf, offset); -} -var init_v5 = __esm(() => { - init_sha1(); - init_v35(); - v52.DNS = DNS2; - v52.URL = URL3; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/version.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/version.js function version2(uuid3) { if (!validate2(uuid3)) throw TypeError("Invalid UUID"); @@ -18597,8 +18719,8 @@ var init_version = __esm(() => { init_validate(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/uuid/index.js -var uuid_exports; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/uuid/index.js +var uuid_exports, MAX, NIL, parse7, stringify2, v12, v42, v53, v62, v72, validate3, version3; var init_uuid = __esm(() => { init_runtime2(); init_max(); @@ -18609,23 +18731,36 @@ var init_uuid = __esm(() => { init_v1(); init_v4(); init_v5(); + init_v6(); init_v7(); init_version(); uuid_exports = /* @__PURE__ */ __exportAll({ - MAX: () => max_default, - NIL: () => nil_default, - parse: () => parse6, - stringify: () => stringify, - v1: () => v1, - v4: () => v4, - v5: () => v52, - v7: () => v7, - validate: () => validate2, - version: () => version2 - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/callbacks/base.js + MAX: () => MAX, + NIL: () => NIL, + parse: () => parse7, + stringify: () => stringify2, + v1: () => v12, + v4: () => v42, + v5: () => v53, + v6: () => v62, + v7: () => v72, + validate: () => validate3, + version: () => version3 + }); + MAX = max_default; + NIL = nil_default; + parse7 = parse6; + stringify2 = stringify; + v12 = v1; + v42 = v4; + v53 = v52; + v62 = v6; + v72 = v7; + validate3 = validate2; + version3 = version2; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/callbacks/base.js function callbackHandlerPrefersStreaming(x) { return "lc_prefer_streaming" in x && x.lc_prefer_streaming; } @@ -18640,7 +18775,6 @@ var base_exports, BaseCallbackHandlerMethodsClass = class { var init_base2 = __esm(() => { init_runtime2(); init_serializable(); - init_v7(); init_uuid(); init_env(); base_exports = /* @__PURE__ */ __exportAll({ @@ -18701,7 +18835,7 @@ var init_base2 = __esm(() => { static fromMethods(methods) { class Handler extends BaseCallbackHandler { - name = v7(); + name = v72(); constructor() { super(); Object.assign(this, methods); @@ -18711,24 +18845,24 @@ var init_base2 = __esm(() => { } }; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/regex.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/regex.js var regex_default3; var init_regex2 = __esm(() => { regex_default3 = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/validate.js -function validate3(uuid3) { +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/validate.js +function validate4(uuid3) { return typeof uuid3 === "string" && regex_default3.test(uuid3); } var validate_default2; var init_validate2 = __esm(() => { init_regex2(); - validate_default2 = validate3; + validate_default2 = validate4; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/parse.js -function parse7(uuid3) { +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/parse.js +function parse8(uuid3) { if (!validate_default2(uuid3)) { throw TypeError("Invalid UUID"); } @@ -18738,10 +18872,10 @@ function parse7(uuid3) { var parse_default2; var init_parse4 = __esm(() => { init_validate2(); - parse_default2 = parse7; + parse_default2 = parse8; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/stringify.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/stringify.js function unsafeStringify3(arr, offset = 0) { return (byteToHex3[arr[offset + 0]] + byteToHex3[arr[offset + 1]] + byteToHex3[arr[offset + 2]] + byteToHex3[arr[offset + 3]] + "-" + byteToHex3[arr[offset + 4]] + byteToHex3[arr[offset + 5]] + "-" + byteToHex3[arr[offset + 6]] + byteToHex3[arr[offset + 7]] + "-" + byteToHex3[arr[offset + 8]] + byteToHex3[arr[offset + 9]] + "-" + byteToHex3[arr[offset + 10]] + byteToHex3[arr[offset + 11]] + byteToHex3[arr[offset + 12]] + byteToHex3[arr[offset + 13]] + byteToHex3[arr[offset + 14]] + byteToHex3[arr[offset + 15]]).toLowerCase(); } @@ -18754,7 +18888,7 @@ var init_stringify2 = __esm(() => { } }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/rng.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/rng.js function rng2() { return crypto.getRandomValues(rnds82); } @@ -18763,8 +18897,8 @@ var init_rng2 = __esm(() => { rnds82 = new Uint8Array(16); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/v4.js -function v42(options, buf, offset) { +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/v4.js +function v43(options, buf, offset) { if (!buf && !options && crypto.randomUUID) { return crypto.randomUUID(); } @@ -18794,10 +18928,10 @@ var v4_default; var init_v42 = __esm(() => { init_rng2(); init_stringify2(); - v4_default = v42; + v4_default = v43; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/sha1.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/sha1.js function f2(s, x, y, z2) { switch (s) { case 0: @@ -18868,7 +19002,7 @@ var init_sha12 = __esm(() => { sha1_default2 = sha13; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/v35.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/v35.js function stringToBytes3(str) { str = unescape(encodeURIComponent(str)); const bytes = new Uint8Array(str.length); @@ -18877,7 +19011,7 @@ function stringToBytes3(str) { } return bytes; } -function v353(version3, hash2, value, namespace, buf, offset) { +function v353(version4, hash2, value, namespace, buf, offset) { const valueBytes = typeof value === "string" ? stringToBytes3(value) : value; const namespaceBytes = typeof namespace === "string" ? parse_default2(namespace) : namespace; if (typeof namespace === "string") { @@ -18890,7 +19024,7 @@ function v353(version3, hash2, value, namespace, buf, offset) { bytes.set(namespaceBytes); bytes.set(valueBytes, namespaceBytes.length); bytes = hash2(bytes); - bytes[6] = bytes[6] & 15 | version3; + bytes[6] = bytes[6] & 15 | version4; bytes[8] = bytes[8] & 63 | 128; if (buf) { offset ??= 0; @@ -18910,8 +19044,8 @@ var init_v352 = __esm(() => { init_stringify2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/v5.js -function v53(value, namespace, buf, offset) { +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/v5.js +function v54(value, namespace, buf, offset) { return v353(80, sha1_default2, value, namespace, buf, offset); } var v5_default2; @@ -18919,13 +19053,13 @@ var init_v52 = __esm(() => { init_sha12(); init_v352(); init_v352(); - v53.DNS = DNS3; - v53.URL = URL4; - v5_default2 = v53; + v54.DNS = DNS3; + v54.URL = URL4; + v5_default2 = v54; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/v7.js -function v72(options, buf, offset) { +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/v7.js +function v73(options, buf, offset) { let bytes; if (options) { bytes = v7Bytes2(options.random ?? options.rng?.() ?? rng2(), options.msecs, options.seq, buf, offset); @@ -18988,15 +19122,15 @@ var init_v72 = __esm(() => { init_rng2(); init_stringify2(); _state3 = {}; - v7_default = v72; + v7_default = v73; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/version.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/version.js var init_version2 = __esm(() => { init_validate2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/uuid/src/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/uuid/src/index.js var init_src = __esm(() => { init_parse4(); init_stringify2(); @@ -19007,11 +19141,11 @@ var init_src = __esm(() => { init_version2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/experimental/otel/constants.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/experimental/otel/constants.js var GEN_AI_OPERATION_NAME = "gen_ai.operation.name", GEN_AI_SYSTEM = "gen_ai.system", GEN_AI_REQUEST_MODEL = "gen_ai.request.model", GEN_AI_RESPONSE_MODEL = "gen_ai.response.model", GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens", GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens", GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens", GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens", GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature", GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p", GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty", GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty", GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons", GENAI_PROMPT = "gen_ai.prompt", GENAI_COMPLETION = "gen_ai.completion", GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query", GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body", GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name", GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature", GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc", GEN_AI_RESPONSE_ID = "gen_ai.response.id", GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier", GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint", GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details", GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details", LANGSMITH_SESSION_ID = "langsmith.trace.session_id", LANGSMITH_SESSION_NAME = "langsmith.trace.session_name", LANGSMITH_RUN_TYPE = "langsmith.span.kind", LANGSMITH_NAME = "langsmith.trace.name", LANGSMITH_METADATA = "langsmith.metadata", LANGSMITH_TAGS = "langsmith.span.tags", LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming", LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers", LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; var init_constants = () => {}; -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/singletons/fetch.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/singletons/fetch.js var DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args), globalFetchSupportsWebStreaming = undefined, LANGSMITH_FETCH_IMPLEMENTATION_KEY, _shouldStreamForGlobalFetchImplementation = () => { const overriddenFetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; if (overriddenFetchImpl === undefined) { @@ -19036,7 +19170,7 @@ var init_fetch = __esm(() => { LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/project.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/project.js var getDefaultProjectName = () => { return getLangSmithEnvironmentVariable("PROJECT") ?? getEnvironmentVariable2("LANGCHAIN_SESSION") ?? "default"; }; @@ -19044,7 +19178,7 @@ var init_project = __esm(() => { init_env2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/warn.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/warn.js function warnOnce(message) { if (!warnedMessages[message]) { console.warn(message); @@ -19056,7 +19190,7 @@ var init_warn = __esm(() => { warnedMessages = {}; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/xxhash/xxhash.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/xxhash/xxhash.js function hexToBytes(hex3) { const bytes = new Uint8Array(hex3.length / 2); for (let i = 0;i < hex3.length; i += 2) { @@ -19331,7 +19465,7 @@ var init_xxhash = __esm(() => { ACC_NB = STRIPE_LEN / 8; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/_uuid.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/_uuid.js function assertUuid(str, which) { if (!UUID_REGEX.test(str)) { const msg = which !== undefined ? `Invalid UUID for ${which}: ${str}` : `Invalid UUID: ${str}`; @@ -19371,8 +19505,8 @@ function nonCryptographicUuid7Deterministic(originalId, key) { const hashInput = `${originalId}:${key}`; const h = _fastHash128(hashInput); const b = new Uint8Array(16); - const version3 = getUuidVersion(originalId); - if (version3 === 7) { + const version4 = getUuidVersion(originalId); + if (version4 === 7) { const originalBytes = uuidToBytes(originalId); b.set(originalBytes.slice(0, 6), 0); } else { @@ -19399,13 +19533,13 @@ var init__uuid = __esm(() => { _textEncoder = new TextEncoder; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/uuid.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/uuid.js var init_uuid2 = __esm(() => { init_src(); init__uuid(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/fs.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/fs.js import * as nodeFs from "node:fs"; import * as nodeFsPromises from "node:fs/promises"; import * as nodePath from "node:path"; @@ -19449,7 +19583,7 @@ var init_fs = __esm(() => { path = nodePath; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/prompt_cache/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/prompt_cache/index.js function isStale(entry, ttlSeconds) { if (ttlSeconds === null) { return false; @@ -19674,8 +19808,8 @@ var init_prompt_cache = __esm(() => { promptCacheSingleton = new PromptCache; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/index.js -var __version__ = "0.7.1"; +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/index.js +var __version__ = "0.7.3"; var init_dist = __esm(() => { init_client(); init_run_trees(); @@ -19685,7 +19819,7 @@ var init_dist = __esm(() => { init_prompt_cache(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/env.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/env.js function getRuntimeEnvironment2() { if (runtimeEnvironment2 === undefined) { const env = getEnv2(); @@ -19838,7 +19972,7 @@ var init_env2 = __esm(() => { _VALID_TRACING_MODES = new Set(["langsmith", "otel"]); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/singletons/otel.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/singletons/otel.js class MockTracer { constructor() { Object.defineProperty(this, "hasWarned", { @@ -19951,7 +20085,7 @@ var init_otel = __esm(() => { OTELProviderSingleton = new OTELProvider; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/experimental/otel/translator.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/experimental/otel/translator.js function getOperationName(runType) { return WELL_KNOWN_OPERATION_NAMES[runType] || runType; } @@ -20303,7 +20437,7 @@ var init_translator = __esm(() => { }; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/is-network-error/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/is-network-error/index.js function isNetworkError(error51) { const isValid = error51 && isError(error51) && error51.name === "TypeError" && typeof error51.message === "string"; if (!isValid) { @@ -20334,7 +20468,7 @@ var init_is_network_error = __esm(() => { ]); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/p-retry/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/p-retry/index.js function validateRetries(retries) { if (typeof retries === "number") { if (retries < 0) { @@ -21022,14 +21156,14 @@ var require_dist = __commonJS((exports) => { exports.default = PQueue; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/p-queue.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/p-queue.js var import_p_queue, PQueue; var init_p_queue = __esm(() => { import_p_queue = __toESM(require_dist(), 1); PQueue = "default" in import_p_queue.default ? import_p_queue.default.default : import_p_queue.default; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/async_caller.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/async_caller.js class AsyncCaller { constructor(params) { Object.defineProperty(this, "maxConcurrency", { @@ -21153,7 +21287,7 @@ var init_async_caller = __esm(() => { ]; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/messages.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/messages.js function isLangChainMessage(message) { return typeof message?._getType === "function"; } @@ -21168,7 +21302,7 @@ function convertLangChainMessageToExample(message) { return converted; } -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/error.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/error.js function getInvalidPromptIdentifierMsg(identifier) { return `Invalid prompt identifier format: "${identifier}". ` + `Expected one of: ` + ` - "prompt-name" (for private prompts) @@ -21266,7 +21400,7 @@ var init_error = __esm(() => { }; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/prompts.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/prompts.js function parseHubIdentifier(identifier) { if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) { throw new Error(getInvalidPromptIdentifierMsg(identifier)); @@ -21290,7 +21424,7 @@ var init_prompts = __esm(() => { init_error(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/profiles.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/profiles.js function isBrowserLikeRuntime() { const env = getEnv2(); return env === "browser" || env === "webworker"; @@ -21537,7 +21671,7 @@ var init_profiles = __esm(() => { init_fs(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js function defaultOptions() { return { depthLimit: Number.MAX_SAFE_INTEGER, @@ -21830,14 +21964,14 @@ var init_fast_safe_stringify = __esm(() => { encoder = new TextEncoder; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/worker_threads.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/worker_threads.js import { Worker as NodeWorker } from "node:worker_threads"; var Worker, WORKER_THREADS_AVAILABLE = true; var init_worker_threads = __esm(() => { Worker = NodeWorker; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/serialize_worker.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/serialize_worker.js class SerializeWorker { constructor() { Object.defineProperty(this, "worker", { @@ -22105,7 +22239,7 @@ var init_serialize_worker = __esm(() => { LARGE_STRING_THRESHOLD = 64 * 1024; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/client.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/client.js function assertPullPublicPromptAllowed(promptIdentifier, dangerouslyPullPublicPrompt) { const [owner] = parseHubIdentifier(promptIdentifier); if (owner !== "-" && !dangerouslyPullPublicPrompt) { @@ -22674,7 +22808,7 @@ var init_client = __esm(() => { enumerable: true, configurable: true, writable: true, - value: false + value: getLangSmithEnvironmentVariable("DISABLE_MULTIPART_STREAMING") === "true" }); Object.defineProperty(this, "_multipartDisabled", { enumerable: true, @@ -25510,6 +25644,24 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(` const run2 = await response.json(); return _normalizeRunTimestamps(run2); } + async* listRunsFromAnnotationQueue(queueId, options = {}) { + const { status, limit: userLimit } = options; + const params = new URLSearchParams; + const limit = userLimit !== undefined && Number.isFinite(userLimit) ? Math.min(userLimit, 100) : 100; + if (status) + params.append("status", status); + params.append("limit", limit.toString()); + let count = 0; + const path2 = `/annotation-queues/${assertUuid(queueId, "queueId")}/runs`; + for await (const runs of this._getPaginated(path2, params)) { + for (const run2 of runs) { + yield _normalizeRunTimestamps(run2); + count++; + if (count >= limit) + return; + } + } + } async deleteRunFromAnnotationQueue(queueId, queueRunId) { await this.caller.call(async () => { const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { @@ -26045,9 +26197,9 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(` yield* repos; } } - async _pullDirectory(identifier, repoType, version3) { + async _pullDirectory(identifier, repoType, version4) { const [owner, name, parsedVersion] = parseHubIdentifier(identifier); - const resolvedVersion = version3 ?? (parsedVersion !== "latest" ? parsedVersion : undefined); + const resolvedVersion = version4 ?? (parsedVersion !== "latest" ? parsedVersion : undefined); const url2 = new URL(`${this.apiUrl}/v1/platform/hub/repos/${owner}/${name}/directories`); url2.searchParams.set("repo_type", repoType); if (resolvedVersion) { @@ -26104,12 +26256,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(` }); const data = await response.json(); const commitHash = data.commit.commit_hash; - let ownerForUrl = owner; - if (owner === "-") { - const settings = await this._getSettings(); - ownerForUrl = settings.tenant_handle || owner; - } - return `${this.getHostUrl()}/hub/${ownerForUrl}/${name}:${commitHash.slice(0, 8)}`; + return `${this.getHostUrl()}/context/${name}/${commitHash.slice(0, 8)}`; } async _deleteDirectory(identifier) { const [owner, name] = parseHubIdentifier(identifier); @@ -26303,7 +26450,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(` }); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/env.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/env.js var isTracingEnabled = (tracingEnabled) => { if (tracingEnabled !== undefined) { return tracingEnabled; @@ -26315,7 +26462,7 @@ var init_env3 = __esm(() => { init_env2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/singletons/constants.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/singletons/constants.js var _LC_CONTEXT_VARIABLES_KEY, _LC_CHILD_RUN_END_PROMISES_KEY, _REPLICA_TRACE_ROOTS_KEY; var init_constants2 = __esm(() => { _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); @@ -26323,7 +26470,7 @@ var init_constants2 = __esm(() => { _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots"); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/utils/context_vars.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/utils/context_vars.js function getContextVar(runTree, key) { if (_LC_CONTEXT_VARIABLES_KEY in runTree) { const contextVars = runTree[_LC_CONTEXT_VARIABLES_KEY]; @@ -26340,7 +26487,7 @@ var init_context_vars = __esm(() => { init_constants2(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/run_trees.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/run_trees.js function getReplicaKey(replica) { const sortedKeys = Object.keys(replica).sort(); const keyData = sortedKeys.map((key) => `${key}:${replica[key] ?? ""}`).join("|"); @@ -27250,12 +27397,12 @@ var init_run_trees = __esm(() => { }); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/run_trees.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/run_trees.js var init_run_trees2 = __esm(() => { init_run_trees(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/base.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/base.js function convertRunToRunTree(run2, parentRun) { if (!run2) return; @@ -27701,7 +27848,7 @@ ${error51.stack}` : ""); }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/console.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/console.js function wrap(style, text) { return `${style.open}${text}${style.close}`; } @@ -27843,12 +27990,12 @@ var init_console = __esm(() => { }; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/index.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/index.js var init_langsmith = __esm(() => { init_dist(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/tracer.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/tracer.js var client, getDefaultLangChainClientSingleton = () => { if (client === undefined) client = new Client(getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {}); @@ -27859,7 +28006,7 @@ var init_tracer = __esm(() => { init_langsmith(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/singletons/traceable.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/singletons/traceable.js class MockAsyncLocalStorage { getStore() { return; @@ -27899,12 +28046,12 @@ var init_traceable = __esm(() => { ROOT = Symbol.for("langsmith:traceable:root"); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/singletons/traceable.js +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/singletons/traceable.js var init_traceable2 = __esm(() => { init_traceable(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/tracer_langchain.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/tracer_langchain.js function _getUsageMetadataFromGenerations(generations) { let output = undefined; for (const generationBatch of generations) @@ -28084,7 +28231,7 @@ var init_tracer_langchain = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js var TRACING_ALS_KEY2, _CONTEXT_VARIABLES_KEY, setGlobalAsyncLocalStorageInstance = (instance) => { globalThis[TRACING_ALS_KEY2] = instance; }, getGlobalAsyncLocalStorageInstance = () => { @@ -28095,7 +28242,7 @@ var init_globals = __esm(() => { _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/callbacks.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/callbacks.js function createQueue() { return new ("default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default)({ autoStart: true, @@ -28136,7 +28283,7 @@ var init_callbacks = __esm(() => { import_p_queue3 = __toESM(require_dist(), 1); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/callbacks/promises.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/callbacks/promises.js var promises_exports; var init_promises = __esm(() => { init_runtime2(); @@ -28147,7 +28294,7 @@ var init_promises = __esm(() => { }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/callbacks.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/callbacks.js var isTracingEnabled2 = (tracingEnabled) => { if (tracingEnabled !== undefined) return tracingEnabled; @@ -28162,7 +28309,7 @@ var init_callbacks2 = __esm(() => { init_env(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/async_local_storage/context.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/async_local_storage/context.js function getContextVariable(name) { const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); if (asyncLocalStorageInstance === undefined) @@ -28176,7 +28323,7 @@ var init_context = __esm(() => { LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/callbacks/manager.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/callbacks/manager.js function parseCallbackConfigArg(arg) { if (!arg) return {}; @@ -28234,7 +28381,6 @@ var manager_exports, BaseCallbackManager = class { var init_manager = __esm(() => { init_runtime2(); init_utils3(); - init_v7(); init_uuid(); init_env(); init_base2(); @@ -28473,7 +28619,7 @@ var init_manager = __esm(() => { } async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { return Promise.all(prompts.map(async (prompt, idx) => { - const runId_ = idx === 0 && runId ? runId : v7(); + const runId_ = idx === 0 && runId ? runId : v72(); await Promise.all(this.handlers.map((handler) => { if (handler.ignoreLLM) return; @@ -28494,7 +28640,7 @@ var init_manager = __esm(() => { } async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { return Promise.all(messages.map(async (messageGroup, idx) => { - const runId_ = idx === 0 && runId ? runId : v7(); + const runId_ = idx === 0 && runId ? runId : v72(); await Promise.all(this.handlers.map((handler) => { if (handler.ignoreLLM) return; @@ -28518,7 +28664,7 @@ var init_manager = __esm(() => { return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); })); } - async handleChainStart(chain, inputs, runId = v7(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined, _parentRunId = undefined, extra = undefined) { + async handleChainStart(chain, inputs, runId = v72(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined, _parentRunId = undefined, extra = undefined) { await Promise.all(this.handlers.map((handler) => { if (handler.ignoreChain) return; @@ -28536,7 +28682,7 @@ var init_manager = __esm(() => { })); return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } - async handleToolStart(tool, input, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined, toolCallId = undefined) { + async handleToolStart(tool, input, runId = v72(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined, toolCallId = undefined) { await Promise.all(this.handlers.map((handler) => { if (handler.ignoreAgent) return; @@ -28554,7 +28700,7 @@ var init_manager = __esm(() => { })); return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } - async handleRetrieverStart(retriever, query3, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + async handleRetrieverStart(retriever, query3, runId = v72(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { await Promise.all(this.handlers.map((handler) => { if (handler.ignoreRetriever) return; @@ -28650,7 +28796,7 @@ var init_manager = __esm(() => { static fromHandlers(handlers) { class Handler extends BaseCallbackHandler { - name = v7(); + name = v72(); constructor() { super(); Object.assign(this, handlers); @@ -28746,7 +28892,7 @@ var init_manager = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/async_local_storage/index.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/async_local_storage/index.js var MockAsyncLocalStorage2 = class { getStore() {} run(_store, callback) { @@ -28800,7 +28946,7 @@ var init_async_local_storage = __esm(() => { AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/singletons/index.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/singletons/index.js var singletons_exports; var init_singletons = __esm(() => { init_runtime2(); @@ -28813,7 +28959,7 @@ var init_singletons = __esm(() => { }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/config.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/config.js function _getTracingInheritableMetadataFromConfig(config2) { const configurable = config2.configurable ?? {}; const metadata = config2.metadata ?? {}; @@ -28991,7 +29137,7 @@ var init_config = __esm(() => { ]); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/signal.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/signal.js async function raceWithSignal(promise2, signal) { if (signal === undefined) return promise2; @@ -29019,7 +29165,7 @@ function getAbortSignalError(signal) { } var init_signal = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/stream.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/stream.js function atee(iter, length = 2) { const buffers = Array.from({ length }, () => []); return buffers.map(async function* makeIter(buffer) { @@ -29216,7 +29362,7 @@ var init_stream = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/outputs.js +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/outputs.js var outputs_exports, RUN_KEY = "__run", GenerationChunk = class GenerationChunk2 { text; generationInfo; @@ -29260,1452 +29406,1604 @@ var init_outputs = __esm(() => { }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/types/zod.js -function isZodSchemaV4(schema) { - if (typeof schema !== "object" || schema === null) - return false; - const obj = schema; - if (!("_zod" in obj)) - return false; - const zod = obj._zod; - return typeof zod === "object" && zod !== null && "def" in zod; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js +function $constructor2(name, initializer3, params) { + function init(inst, def) { + var _a3; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false + }); + (_a3 = inst._zod).traits ?? (_a3.traits = new Set); + inst._zod.traits.add(name); + initializer3(inst, def); + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + } + inst._zod.constr = _; + inst._zod.def = def; + } + const Parent = params?.Parent ?? Object; + + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a3; + const inst = params?.Parent ? new Definition : this; + init(inst, def); + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; } -function isZodSchemaV3(schema) { - if (typeof schema !== "object" || schema === null) - return false; - const obj = schema; - if (!("_def" in obj) || "_zod" in obj) - return false; - const def = obj._def; - return typeof def === "object" && def != null && "typeName" in def; +function config2(newConfig) { + if (newConfig) + Object.assign(globalConfig2, newConfig); + return globalConfig2; } -function isZodSchema(schema) { - if (isZodSchemaV4(schema)) - console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); - return isZodSchemaV3(schema); +var NEVER2, $brand2, $ZodAsyncError2, globalConfig2; +var init_core3 = __esm(() => { + NEVER2 = Object.freeze({ + status: "aborted" + }); + $brand2 = Symbol("zod_brand"); + $ZodAsyncError2 = class $ZodAsyncError2 extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + globalConfig2 = {}; +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js +var exports_util2 = {}; +__export(exports_util2, { + unwrapMessage: () => unwrapMessage2, + stringifyPrimitive: () => stringifyPrimitive2, + required: () => required2, + randomString: () => randomString2, + propertyKeyTypes: () => propertyKeyTypes2, + promiseAllObject: () => promiseAllObject2, + primitiveTypes: () => primitiveTypes2, + prefixIssues: () => prefixIssues2, + pick: () => pick2, + partial: () => partial2, + optionalKeys: () => optionalKeys2, + omit: () => omit2, + numKeys: () => numKeys2, + nullish: () => nullish3, + normalizeParams: () => normalizeParams2, + merge: () => merge2, + jsonStringifyReplacer: () => jsonStringifyReplacer2, + joinValues: () => joinValues2, + issue: () => issue2, + isPlainObject: () => isPlainObject2, + isObject: () => isObject2, + getSizableOrigin: () => getSizableOrigin2, + getParsedType: () => getParsedType2, + getLengthableOrigin: () => getLengthableOrigin2, + getEnumValues: () => getEnumValues2, + getElementAtPath: () => getElementAtPath2, + floatSafeRemainder: () => floatSafeRemainder2, + finalizeIssue: () => finalizeIssue2, + extend: () => extend2, + escapeRegex: () => escapeRegex2, + esc: () => esc2, + defineLazy: () => defineLazy2, + createTransparentProxy: () => createTransparentProxy2, + clone: () => clone2, + cleanRegex: () => cleanRegex2, + cleanEnum: () => cleanEnum2, + captureStackTrace: () => captureStackTrace2, + cached: () => cached2, + assignProp: () => assignProp2, + assertNotEqual: () => assertNotEqual2, + assertNever: () => assertNever2, + assertIs: () => assertIs2, + assertEqual: () => assertEqual2, + assert: () => assert3, + allowsEval: () => allowsEval2, + aborted: () => aborted2, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES2, + Class: () => Class2, + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES2 +}); +function assertEqual2(val) { + return val; } -function isInteropZodSchema(input) { - if (!input) - return false; - if (typeof input !== "object") - return false; - if (Array.isArray(input)) - return false; - if (isZodSchemaV4(input) || isZodSchemaV3(input)) - return true; - return false; +function assertNotEqual2(val) { + return val; } -function isZodLiteralV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") - return true; - return false; +function assertIs2(_arg) {} +function assertNever2(_x) { + throw new Error; } -function isZodLiteralV4(obj) { - if (!isZodSchemaV4(obj)) - return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") - return true; - return false; +function assert3(_) {} +function getEnumValues2(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values; } -function isInteropZodLiteral(obj) { - if (isZodLiteralV3(obj)) - return true; - if (isZodLiteralV4(obj)) - return true; - return false; +function joinValues2(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive2(val)).join(separator); } -async function interopSafeParseAsync(schema, input) { - if (isZodSchemaV4(schema)) - try { - return { - success: true, - data: await parseAsync(schema, input) - }; - } catch (error51) { - return { - success: false, - error: error51 - }; +function jsonStringifyReplacer2(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached2(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); } - if (isZodSchemaV3(schema)) - return await schema.safeParseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); + }; } -async function interopParseAsync(schema, input) { - if (isZodSchemaV4(schema)) - return await parseAsync(schema, input); - if (isZodSchemaV3(schema)) - return await schema.parseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +function nullish3(input) { + return input === null || input === undefined; } -function interopSafeParse(schema, input) { - if (isZodSchemaV4(schema)) - try { - return { - success: true, - data: parse(schema, input) - }; - } catch (error51) { - return { - success: false, - error: error51 - }; - } - if (isZodSchemaV3(schema)) - return schema.safeParse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +function cleanRegex2(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); } -function interopParse(schema, input) { - if (isZodSchemaV4(schema)) - return parse(schema, input); - if (isZodSchemaV3(schema)) - return schema.parse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +function floatSafeRemainder2(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; } -function getSchemaDescription(schema) { - if (isZodSchemaV4(schema)) - return globalRegistry.get(schema)?.description; - if (isZodSchemaV3(schema)) - return schema.description; - if ("description" in schema && typeof schema.description === "string") - return schema.description; +function defineLazy2(object2, key, getter) { + const set2 = false; + Object.defineProperty(object2, key, { + get() { + if (!set2) { + const value = getter(); + object2[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object2, key, { + value: v + }); + }, + configurable: true + }); } -function isShapelessZodSchema(schema) { - if (!isInteropZodSchema(schema)) - return false; - if (isZodSchemaV3(schema)) { - const def = schema._def; - if (def.typeName === "ZodObject") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; - } - if (def.typeName === "ZodRecord") - return true; - } - if (isZodSchemaV4(schema)) { - const def = schema._zod.def; - if (def.type === "object") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; +function assignProp2(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function getElementAtPath2(obj, path2) { + if (!path2) + return obj; + return path2.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject2(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0;i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; } - if (def.type === "record") - return true; + return resolvedObj; + }); +} +function randomString2(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0;i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; } - if (typeof schema === "object" && schema !== null && !("shape" in schema)) - return true; - return false; + return str; } -function isSimpleStringZodSchema(schema) { - if (!isInteropZodSchema(schema)) - return false; - if (isZodSchemaV3(schema)) - return schema._def.typeName === "ZodString"; - if (isZodSchemaV4(schema)) - return schema._zod.def.type === "string"; - return false; +function esc2(str) { + return JSON.stringify(str); } -function isZodObjectV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") - return true; - return false; +function isObject2(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); } -function isZodObjectV4(obj) { - if (!isZodSchemaV4(obj)) +function isPlainObject2(o) { + if (isObject2(o) === false) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") + const ctor = o.constructor; + if (ctor === undefined) return true; - return false; -} -function isZodArrayV4(obj) { - if (!isZodSchemaV4(obj)) + const prot = ctor.prototype; + if (isObject2(prot) === false) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") - return true; - return false; -} -function isZodOptionalV4(obj) { - if (!isZodSchemaV4(obj)) + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional") - return true; - return false; + } + return true; } -function isZodNullableV4(obj) { - if (!isZodSchemaV4(obj)) - return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable") - return true; - return false; +function numKeys2(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; } -function isInteropZodObject(obj) { - if (isZodObjectV3(obj)) - return true; - if (isZodObjectV4(obj)) - return true; - return false; +function escapeRegex2(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function getInteropZodObjectShape(schema) { - if (isZodSchemaV3(schema)) - return schema.shape; - if (isZodSchemaV4(schema)) - return schema._zod.def.shape; - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +function clone2(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; } -function extendInteropZodObject(schema, extension) { - if (isZodSchemaV3(schema)) - return schema.extend(extension); - if (isZodSchemaV4(schema)) - return exports_util.extend(schema, extension); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +function normalizeParams2(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; } -function interopZodObjectPartial(schema) { - if (isZodSchemaV3(schema)) - return schema.partial(); - if (isZodSchemaV4(schema)) - return exports_util.partial($ZodOptional, schema, undefined); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +function createTransparentProxy2(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); } -function interopZodObjectStrict(schema, recursive = false) { - if (isZodObjectV3(schema)) - return schema.strict(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) - for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) - outputShape[key] = interopZodObjectStrict(keySchema, recursive); - else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) - elementSchema = interopZodObjectStrict(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else - outputShape[key] = keySchema; - const meta4 = globalRegistry.get(keySchema); - if (meta4) - globalRegistry.add(outputShape[key], meta4); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _never($ZodNever) - }); - const meta3 = globalRegistry.get(schema); - if (meta3) - globalRegistry.add(modifiedSchema, meta3); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +function stringifyPrimitive2(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; } -function interopZodObjectPassthrough(schema, recursive = false) { - if (isZodObjectV3(schema)) - return schema.passthrough(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) - for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) - outputShape[key] = interopZodObjectPassthrough(keySchema, recursive); - else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) - elementSchema = interopZodObjectPassthrough(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else - outputShape[key] = keySchema; - const meta4 = globalRegistry.get(keySchema); - if (meta4) - globalRegistry.add(outputShape[key], meta4); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _unknown($ZodUnknown) - }); - const meta3 = globalRegistry.get(schema); - if (meta3) - globalRegistry.add(modifiedSchema, meta3); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +function optionalKeys2(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); } -function getInteropZodDefaultGetter(schema) { - if (isZodSchemaV3(schema)) - try { - const defaultValue = schema.parse(undefined); - return () => defaultValue; - } catch { - return; +function pick2(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } - if (isZodSchemaV4(schema)) - try { - const defaultValue = parse(schema, undefined); - return () => defaultValue; - } catch { - return; + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + return clone2(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); +} +function omit2(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } + if (!mask[key]) + continue; + delete newShape[key]; + } + return clone2(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); } -function isZodTransformV3(schema) { - return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; +function extend2(schema, shape) { + if (!isPlainObject2(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp2(this, "shape", _shape); + return _shape; + }, + checks: [] + }; + return clone2(schema, def); } -function isZodTransformV4(schema) { - return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +function merge2(a, b) { + return clone2(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp2(this, "shape", _shape); + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [] + }); } -function interopZodTransformInputSchemaImpl(schema, recursive, cache) { - const cached2 = cache.get(schema); - if (cached2 !== undefined) - return cached2; - if (isZodSchemaV3(schema)) { - if (isZodTransformV3(schema)) - return interopZodTransformInputSchemaImpl(schema._def.schema, recursive, cache); - return schema; +function partial2(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } } - if (isZodSchemaV4(schema)) { - let outputSchema = schema; - if (isZodTransformV4(schema)) - outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache); - if (recursive) { - if (isZodObjectV4(outputSchema)) { - const outputShape = {}; - for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) - outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - shape: outputShape - }); - } else if (isZodArrayV4(outputSchema)) { - const elementSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.element, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - element: elementSchema - }); - } else if (isZodOptionalV4(outputSchema)) { - const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - innerType: innerSchema - }); - } else if (isZodNullableV4(outputSchema)) { - const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - innerType: innerSchema - }); + return clone2(schema, { + ...schema._zod.def, + shape, + checks: [] + }); +} +function required2(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); } - const meta3 = globalRegistry.get(schema); - if (meta3) - globalRegistry.add(outputSchema, meta3); - cache.set(schema, outputSchema); - return outputSchema; } - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); + return clone2(schema, { + ...schema._zod.def, + shape, + checks: [] + }); } -function interopZodTransformInputSchema(schema, recursive = false) { - return interopZodTransformInputSchemaImpl(schema, recursive, /* @__PURE__ */ new WeakMap); +function aborted2(x, startIndex = 0) { + for (let i = startIndex;i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) + return true; + } + return false; } -function interopZodObjectMakeFieldsOptional(schema, predicate) { - if (isZodSchemaV3(schema)) { - const shape = getInteropZodObjectShape(schema); - const modifiedShape = {}; - for (const [key, value] of Object.entries(shape)) - if (predicate(key, value)) - modifiedShape[key] = value.optional(); - else - modifiedShape[key] = value; - return schema.extend(modifiedShape); +function prefixIssues2(path2, issues) { + return issues.map((iss) => { + var _a3; + (_a3 = iss).path ?? (_a3.path = []); + iss.path.unshift(path2); + return iss; + }); +} +function unwrapMessage2(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue2(iss, ctx, config3) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message = unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config3.customError?.(iss)) ?? unwrapMessage2(config3.localeError?.(iss)) ?? "Invalid input"; + full.message = message; } - if (isZodSchemaV4(schema)) { - const shape = getInteropZodObjectShape(schema); - const outputShape = { ...schema._zod.def.shape }; - for (const [key, value] of Object.entries(shape)) - if (predicate(key, value)) - outputShape[key] = new $ZodOptional({ - type: "optional", - innerType: value - }); - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape - }); - const meta3 = globalRegistry.get(schema); - if (meta3) - globalRegistry.add(modifiedSchema, meta3); - return modifiedSchema; + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); + return full; } -function isInteropZodError(e) { - return e instanceof Error && (e.constructor.name === "ZodError" || e.constructor.name === "$ZodError"); +function getSizableOrigin2(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; } -var init_zod2 = __esm(() => { - init_core2(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/standard_schema.js -function isStandardSchema(schema) { - return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +function getLengthableOrigin2(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; } -function isStandardJsonSchema(schema) { - return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +function issue2(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; } -function isSerializableSchema(schema) { - return isStandardSchema(schema) && isStandardJsonSchema(schema); +function cleanEnum2(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); } -var standard_schema_exports; -var init_standard_schema = __esm(() => { - init_runtime2(); - standard_schema_exports = /* @__PURE__ */ __exportAll({ - isSerializableSchema: () => isSerializableSchema, - isStandardJsonSchema: () => isStandardJsonSchema, - isStandardSchema: () => isStandardSchema - }); -}); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js -var ignoreOverride, defaultOptions2, getDefaultOptions = (options) => typeof options === "string" ? { - ...defaultOptions2, - name: options -} : { - ...defaultOptions2, - ...options -}; -var init_Options = __esm(() => { - ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); - defaultOptions2 = { - name: undefined, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js -var getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== undefined ? [ - ..._options.basePath, - _options.definitionPath, - _options.name - ] : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath, - propertyPath: undefined, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { - def: def._def, - path: [ - ..._options.basePath, - _options.definitionPath, - name - ], - jsonSchema: undefined - }])) - }; -}; -var init_Refs = __esm(() => { - init_Options(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js -var getRelativePath = (pathA, pathB) => { - let i = 0; - for (;i < pathA.length && i < pathB.length; i++) - if (pathA[i] !== pathB[i]) - break; - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; -var init_getRelativePath = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js -function parseAnyDef(refs) { - if (refs.target !== "openAi") - return {}; - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; -} -var init_any = __esm(() => { - init_getRelativePath(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); +class Class2 { + constructor(..._args) {} } -var init_errorMessages = () => {}; - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/util.js -var util, objectUtil, ZodParsedType, getParsedType2 = (data) => { +var captureStackTrace2, allowsEval2, getParsedType2 = (data) => { const t = typeof data; switch (t) { case "undefined": - return ZodParsedType.undefined; + return "undefined"; case "string": - return ZodParsedType.string; + return "string"; case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + return Number.isNaN(data) ? "nan" : "number"; case "boolean": - return ZodParsedType.boolean; + return "boolean"; case "function": - return ZodParsedType.function; + return "function"; case "bigint": - return ZodParsedType.bigint; + return "bigint"; case "symbol": - return ZodParsedType.symbol; + return "symbol"; case "object": if (Array.isArray(data)) { - return ZodParsedType.array; + return "array"; } if (data === null) { - return ZodParsedType.null; + return "null"; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; + return "promise"; } if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; + return "map"; } if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; + return "set"; } if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; + return "date"; } - return ZodParsedType.object; + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; default: - return ZodParsedType.unknown; + throw new Error(`Unknown data type: ${t}`); } -}; +}, propertyKeyTypes2, primitiveTypes2, NUMBER_FORMAT_RANGES2, BIGINT_FORMAT_RANGES2; var init_util2 = __esm(() => { - (function(util2) { - util2.assertEqual = (_) => {}; - function assertIs2(_arg) {} - util2.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error; + captureStackTrace2 = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {}; + allowsEval2 = cached2(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; } - util2.assertNever = assertNever2; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { - const keys = []; - for (const key in object2) { - if (Object.prototype.hasOwnProperty.call(object2, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr2, checker) => { - for (const item of arr2) { - if (checker(item)) - return item; - } - return; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; } - util2.joinValues = joinValues2; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; - })(util || (util = {})); - (function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; - })(objectUtil || (objectUtil = {})); - ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" - ]); + }); + propertyKeyTypes2 = new Set(["string", "number", "symbol"]); + primitiveTypes2 = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES2 = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES2 = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; }); -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/ZodError.js -var ZodIssueCode2, quotelessJson = (obj) => { - const json2 = JSON.stringify(obj, null, 2); - return json2.replace(/"([^"]+)":/g, "$1:"); -}, ZodError2; -var init_ZodError = __esm(() => { - init_util2(); - ZodIssueCode2 = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" - ]); - ZodError2 = class ZodError2 extends Error { - get errors() { - return this.issues; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js +function flattenError2(error51, mapper = (issue3) => issue3.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error51.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); + } + return { formErrors, fieldErrors }; +} +function formatError3(error51, _mapper) { + const mapper = _mapper || function(issue3) { + return issue3.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error52) => { + for (const issue3 of error52.issues) { + if (issue3.code === "invalid_union" && issue3.errors.length) { + issue3.errors.map((issues) => processError({ issues })); + } else if (issue3.code === "invalid_key") { + processError({ issues: issue3.issues }); + } else if (issue3.code === "invalid_element") { + processError({ issues: issue3.issues }); + } else if (issue3.path.length === 0) { + fieldErrors._errors.push(mapper(issue3)); } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error51) => { - for (const issue2 of error51.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); + let curr = fieldErrors; + let i = 0; + while (i < issue3.path.length) { + const el = issue3.path[i]; + const terminal = i === issue3.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; } else { - let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i++; - } + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue3)); } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError2)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = Object.create(null); - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); + curr = curr[el]; + i++; } } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); } }; - ZodError2.create = (issues) => { - const error51 = new ZodError2(issues); - return error51; + processError(error51); + return fieldErrors; +} +function treeifyError2(error51, _mapper) { + const mapper = _mapper || function(issue3) { + return issue3.message; }; -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/locales/en.js -var errorMap = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode2.invalid_type: - if (issue2.received === ZodParsedType.undefined) { - message = "Required"; + const result = { errors: [] }; + const processError = (error52, path2 = []) => { + var _a3, _b; + for (const issue3 of error52.issues) { + if (issue3.code === "invalid_union" && issue3.errors.length) { + issue3.errors.map((issues) => processError({ issues }, issue3.path)); + } else if (issue3.code === "invalid_key") { + processError({ issues: issue3.issues }, issue3.path); + } else if (issue3.code === "invalid_element") { + processError({ issues: issue3.issues }, issue3.path); } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode2.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode2.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode2.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; - break; - case ZodIssueCode2.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode2.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode2.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode2.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode2.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; - } else { - util.assertNever(issue2.validation); + const fullpath = [...path2, ...issue3.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue3)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a3 = curr.properties)[el] ?? (_a3[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue3)); + } + i++; } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; } - break; - case ZodIssueCode2.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode2.custom: - message = `Invalid input`; - break; - case ZodIssueCode2.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode2.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode2.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue2); + } + }; + processError(error51); + return result; +} +function toDotPath2(path2) { + const segs = []; + for (const seg of path2) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } } - return { message }; -}, en_default2; -var init_en2 = __esm(() => { - init_ZodError(); - init_util2(); - en_default2 = errorMap; -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/errors.js -function setErrorMap2(map2) { - overrideErrorMap = map2; + return segs.join(""); } -function getErrorMap2() { - return overrideErrorMap; +function prettifyError2(error51) { + const lines = []; + const issues = [...error51.issues].sort((a, b) => a.path.length - b.path.length); + for (const issue3 of issues) { + lines.push(`✖ ${issue3.message}`); + if (issue3.path?.length) + lines.push(` → at ${toDotPath2(issue3.path)}`); + } + return lines.join(` +`); } -var overrideErrorMap; +var initializer3 = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer2, 2); + }, + enumerable: true + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); +}, $ZodError2, $ZodRealError2; var init_errors4 = __esm(() => { - init_en2(); - overrideErrorMap = en_default2; + init_core3(); + init_util2(); + $ZodError2 = $constructor2("$ZodError", initializer3); + $ZodRealError2 = $constructor2("$ZodError", initializer3, { Parent: Error }); }); -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/parseUtil.js -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap2(); - const issue2 = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default2 ? undefined : en_default2 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue2); -} - -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js +var _parse2 = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError2; } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); + captureStackTrace2(e, _params?.callee); + throw e; } -} -var makeIssue = (params) => { - const { data, path: path2, errorMaps, issueData } = params; - const fullPath = [...path2, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; + return result.value; +}, parse9, _parseAsync2 = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); + captureStackTrace2(e, params?.callee); + throw e; } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map2 of maps) { - errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; + return result.value; +}, parseAsync3, _safeParse2 = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError2; } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}, EMPTY_PATH, INVALID, DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x) => x.status === "aborted", isDirty = (x) => x.status === "dirty", isValid = (x) => x.status === "valid", isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var init_parseUtil = __esm(() => { + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError2)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) + } : { success: true, data: result.value }; +}, safeParse3, _safeParseAsync2 = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) + } : { success: true, data: result.value }; +}, safeParseAsync3; +var init_parse5 = __esm(() => { + init_core3(); init_errors4(); - init_en2(); - EMPTY_PATH = []; - INVALID = Object.freeze({ - status: "aborted" - }); + init_util2(); + parse9 = /* @__PURE__ */ _parse2($ZodRealError2); + parseAsync3 = /* @__PURE__ */ _parseAsync2($ZodRealError2); + safeParse3 = /* @__PURE__ */ _safeParse2($ZodRealError2); + safeParseAsync3 = /* @__PURE__ */ _safeParseAsync2($ZodRealError2); }); -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/typeAliases.js -var init_typeAliases = () => {}; - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/errorUtil.js -var errorUtil; -var init_errorUtil = __esm(() => { - (function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; - })(errorUtil || (errorUtil = {})); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js +var exports_regexes2 = {}; +__export(exports_regexes2, { + xid: () => xid3, + uuid7: () => uuid73, + uuid6: () => uuid62, + uuid4: () => uuid42, + uuid: () => uuid3, + uppercase: () => uppercase2, + unicodeEmail: () => unicodeEmail2, + undefined: () => _undefined4, + ulid: () => ulid3, + time: () => time3, + string: () => string4, + rfc5322Email: () => rfc5322Email2, + number: () => number4, + null: () => _null4, + nanoid: () => nanoid3, + lowercase: () => lowercase2, + ksuid: () => ksuid3, + ipv6: () => ipv63, + ipv4: () => ipv43, + integer: () => integer2, + html5Email: () => html5Email2, + hostname: () => hostname3, + guid: () => guid3, + extendedDuration: () => extendedDuration2, + emoji: () => emoji3, + email: () => email3, + e164: () => e1643, + duration: () => duration3, + domain: () => domain2, + datetime: () => datetime3, + date: () => date5, + cuid2: () => cuid23, + cuid: () => cuid5, + cidrv6: () => cidrv63, + cidrv4: () => cidrv43, + browserEmail: () => browserEmail2, + boolean: () => boolean4, + bigint: () => bigint4, + base64url: () => base64url3, + base64: () => base643, + _emoji: () => _emoji3 }); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/types.js -class ParseInputLazyPath { - constructor(parent, value, path2, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path2; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } +function emoji3() { + return new RegExp(_emoji3, "u"); } -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; +function timeSource2(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time3(args) { + return new RegExp(`^${timeSource2(args)}$`); +} +function datetime3(args) { + const time4 = timeSource2({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex = `${time4}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource2}T(?:${timeRegex})$`); } +var cuid5, cuid23, ulid3, xid3, ksuid3, nanoid3, duration3, extendedDuration2, guid3, uuid3 = (version4) => { + if (!version4) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}, uuid42, uuid62, uuid73, email3, html5Email2, rfc5322Email2, unicodeEmail2, browserEmail2, _emoji3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, ipv43, ipv63, cidrv43, cidrv63, base643, base64url3, hostname3, domain2, e1643, dateSource2 = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`, date5, string4 = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}, bigint4, integer2, number4, boolean4, _null4, _undefined4, lowercase2, uppercase2; +var init_regexes2 = __esm(() => { + cuid5 = /^[cC][^\s-]{8,}$/; + cuid23 = /^[0-9a-z]+$/; + ulid3 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + xid3 = /^[0-9a-vA-V]{20}$/; + ksuid3 = /^[A-Za-z0-9]{27}$/; + nanoid3 = /^[a-zA-Z0-9_-]{21}$/; + duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + extendedDuration2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; + uuid42 = /* @__PURE__ */ uuid3(4); + uuid62 = /* @__PURE__ */ uuid3(6); + uuid73 = /* @__PURE__ */ uuid3(7); + email3 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + html5Email2 = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + rfc5322Email2 = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + unicodeEmail2 = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + browserEmail2 = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + ipv43 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; + cidrv43 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; + cidrv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base643 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base64url3 = /^[A-Za-z0-9_-]*$/; + hostname3 = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; + domain2 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + e1643 = /^\+(?:[0-9]){6,14}[0-9]$/; + date5 = /* @__PURE__ */ new RegExp(`^${dateSource2}$`); + bigint4 = /^\d+n?$/; + integer2 = /^\d+$/; + number4 = /^-?\d+(?:\.\d+)?/i; + boolean4 = /true|false/i; + _null4 = /null/i; + _undefined4 = /undefined/i; + lowercase2 = /^[^A-Z]*$/; + uppercase2 = /^[^a-z]*$/; +}); -class ZodType2 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType2(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType2(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js +function handleCheckPropertyResult2(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues2(property, result.issues)); } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; +} +var $ZodCheck2, numericOriginMap2, $ZodCheckLessThan2, $ZodCheckGreaterThan2, $ZodCheckMultipleOf2, $ZodCheckNumberFormat2, $ZodCheckBigIntFormat2, $ZodCheckMaxSize2, $ZodCheckMinSize2, $ZodCheckSizeEquals2, $ZodCheckMaxLength2, $ZodCheckMinLength2, $ZodCheckLengthEquals2, $ZodCheckStringFormat2, $ZodCheckRegex2, $ZodCheckLowerCase2, $ZodCheckUpperCase2, $ZodCheckIncludes2, $ZodCheckStartsWith2, $ZodCheckEndsWith2, $ZodCheckProperty2, $ZodCheckMimeType2, $ZodCheckOverwrite2; +var init_checks3 = __esm(() => { + init_core3(); + init_regexes2(); + init_util2(); + $ZodCheck2 = /* @__PURE__ */ $constructor2("$ZodCheck", (inst, def) => { + var _a3; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a3 = inst._zod).onattach ?? (_a3.onattach = []); + }); + numericOriginMap2 = { + number: "number", + bigint: "bigint", + object: "date" + }; + $ZodCheckLessThan2 = /* @__PURE__ */ $constructor2("$ZodCheckLessThan", (inst, def) => { + $ZodCheck2.init(inst, def); + const origin = numericOriginMap2[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType2(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode2.custom, - ...getIssueProperties(val) + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; + }; + }); + $ZodCheckGreaterThan2 = /* @__PURE__ */ $constructor2("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck2.init(inst, def); + const origin = numericOriginMap2[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; } }); - } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; } + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMultipleOf2 = /* @__PURE__ */ $constructor2("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck2.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a3; + (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value); }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); }; - } - optional() { - return ZodOptional2.create(this, this._def); - } - nullable() { - return ZodNullable2.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray2.create(this); - } - promise() { - return ZodPromise2.create(this, this._def); - } - or(option) { - return ZodUnion2.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection2.create(this, incoming, this._def); - } - transform(transform2) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect: { type: "transform", transform: transform2 } + }); + $ZodCheckNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck2.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES2[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer2; }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault2({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodDefault + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst + }); + } + }; + }); + $ZodCheckBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck2.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES2[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind2.ZodBranded, - type: this, - ...processCreateParams(this._def) + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst + }); + } + }; + }); + $ZodCheckMaxSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxSize", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.size !== undefined; }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch2({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind2.ZodCatch + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin2(input), + code: "too_big", + maximum: def.maximum, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMinSize", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.size !== undefined; }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin2(input), + code: "too_small", + minimum: def.minimum, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckSizeEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckSizeEquals", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.size !== undefined; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin2(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMaxLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxLength", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin2(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMinLength", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin2(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLengthEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckLengthEquals", (inst, def) => { + var _a3; + $ZodCheck2.init(inst, def); + (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => { + const val = payload.value; + return !nullish3(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin2(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckStringFormat", (inst, def) => { + var _a3, _b; + $ZodCheck2.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a3 = inst._zod).check ?? (_a3.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => {}); + }); + $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat2.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase2); + $ZodCheckStringFormat2.init(inst, def); + }); + $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase2); + $ZodCheckStringFormat2.init(inst, def); + }); + $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => { + $ZodCheck2.init(inst, def); + const escapedRegex = escapeRegex2(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = new Set); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStartsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck2.init(inst, def); + const pattern = new RegExp(`^${escapeRegex2(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = new Set); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckEndsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck2.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex2(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = new Set); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckProperty2 = /* @__PURE__ */ $constructor2("$ZodCheckProperty", (inst, def) => { + $ZodCheck2.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult2(result2, payload, def.property)); + } + handleCheckPropertyResult2(result, payload, def.property); + return; + }; + }); + $ZodCheckMimeType2 = /* @__PURE__ */ $constructor2("$ZodCheckMimeType", (inst, def) => { + $ZodCheck2.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst + }); + }; + }); + $ZodCheckOverwrite2 = /* @__PURE__ */ $constructor2("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck2.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; + }); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js +class Doc2 { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly2.create(this); - } - isOptional() { - return this.safeParse(undefined).success; + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; } - isNullable() { - return this.safeParse(null).success; + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split(` +`).filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } } -} -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join(` +`)); } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); } -function isValidIP(ip, version3) { - if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) { + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js +var version4; +var init_versions2 = __esm(() => { + version4 = { + major: 4, + minor: 0, + patch: 0 + }; +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js +function isValidBase642(data) { + if (data === "") return true; - } - if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) { + if (data.length % 4 !== 0) + return false; + try { + atob(data); return true; + } catch { + return false; } - return false; } -function isValidJWT2(jwt2, alg) { - if (!jwtRegex.test(jwt2)) +function isValidBase64URL2(data) { + if (!base64url3.test(data)) return false; + const base644 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base644.padEnd(Math.ceil(base644.length / 4) * 4, "="); + return isValidBase642(padded); +} +function isValidJWT2(token, algorithm = null) { try { - const [header] = jwt2.split("."); - if (!header) + const tokensParts = token.split("."); + if (tokensParts.length !== 3) return false; - const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base643)); - if (typeof decoded !== "object" || decoded === null) + const [header] = tokensParts; + if (!header) return false; - if ("typ" in decoded && decoded?.typ !== "JWT") + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false; - if (!decoded.alg) + if (!parsedHeader.alg) return false; - if (alg && decoded.alg !== alg) + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; } catch { return false; } } -function isValidCidr(ip, version3) { - if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) { - return true; +function handleArrayResult2(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues2(index, result.issues)); } - return false; + final.value[index] = result.value; } -function floatSafeRemainder2(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; +function handleObjectResult(result, final, key) { + if (result.issues.length) { + final.issues.push(...prefixIssues2(key, result.issues)); + } + final.value[key] = result.value; } -function deepPartialify(schema) { - if (schema instanceof ZodObject2) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); +function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + if (input[key] === undefined) { + if (key in input) { + final.value[key] = undefined; + } else { + final.value[key] = result.value; + } + } else { + final.issues.push(...prefixIssues2(key, result.issues)); } - return new ZodObject2({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray2) { - return new ZodArray2({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional2) { - return ZodOptional2.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable2) { - return ZodNullable2.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple2) { - return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); + } else if (result.value === undefined) { + if (key in input) + final.value[key] = undefined; } else { - return schema; + final.value[key] = result.value; } } +function handleUnionResults2(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) + }); + return final; +} function mergeValues2(a, b) { - const aType = getParsedType2(a); - const bType = getParsedType2(b); if (a === b) { return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject2(a) && isPlainObject2(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues2(a[key], b[key]); if (!sharedValue.valid) { - return { valid: false }; + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + } + if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { - return { valid: false }; + return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0;index < a.length; index++) { @@ -30713,108929 +31011,120033 @@ function mergeValues2(a, b) { const itemB = b[index]; const sharedValue = mergeValues2(itemA, itemB); if (!sharedValue.valid) { - return { valid: false }; + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; } + return { valid: false, mergeErrorPath: [] }; } -function createZodEnum(values, params) { - return new ZodEnum2({ - values, - typeName: ZodFirstPartyTypeKind2.ZodEnum, - ...processCreateParams(params) - }); +function handleIntersectionResults2(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (aborted2(result)) + return result; + const merged = mergeValues2(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; } -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; +function handleTupleResult2(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues2(index, result.issues)); + } + final.value[index] = result.value; } -function custom2(check2, _params = {}, fatal) { - if (check2) - return ZodAny2.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; +function handleMapResult2(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes2.has(typeof key)) { + final.issues.push(...prefixIssues2(key, keyResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_key", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes2.has(typeof key)) { + final.issues.push(...prefixIssues2(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +function handleSetResult2(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +function handleDefaultResult2(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +function handleNonOptionalResult2(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst }); - return ZodAny2.create(); + } + return payload; } -var handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error51 = new ZodError2(ctx.common.issues); - this._error = error51; - return this._error; - } - }; +function handlePipeResult2(left, def, ctx) { + if (aborted2(left)) { + return left; } -}, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator = (type) => { - if (type instanceof ZodLazy2) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral2) { - return [type.value]; - } else if (type instanceof ZodEnum2) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault2) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined2) { - return [undefined]; - } else if (type instanceof ZodNull2) { - return [null]; - } else if (type instanceof ZodOptional2) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable2) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly2) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch2) { - return getDiscriminator(type._def.innerType); - } else { - return []; + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); +} +function handleReadonlyResult2(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +function handleRefineResult2(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + path: [...inst._zod.def.path ?? []], + continue: !inst._zod.def.abort + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue2(_iss)); } -}, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum, ZodPromise2, ZodEffects, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND, ZodBranded, ZodPipeline, ZodReadonly2, late, ZodFirstPartyTypeKind2, instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom2((data) => data instanceof cls, params), stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce, NEVER2; -var init_types = __esm(() => { - init_ZodError(); - init_errors4(); - init_errorUtil(); - init_parseUtil(); +} +var $ZodType2, $ZodString2, $ZodStringFormat2, $ZodGUID2, $ZodUUID2, $ZodEmail2, $ZodURL2, $ZodEmoji2, $ZodNanoID2, $ZodCUID3, $ZodCUID22, $ZodULID2, $ZodXID2, $ZodKSUID2, $ZodISODateTime2, $ZodISODate2, $ZodISOTime2, $ZodISODuration2, $ZodIPv42, $ZodIPv62, $ZodCIDRv42, $ZodCIDRv62, $ZodBase642, $ZodBase64URL2, $ZodE1642, $ZodJWT2, $ZodCustomStringFormat2, $ZodNumber2, $ZodNumberFormat2, $ZodBoolean2, $ZodBigInt2, $ZodBigIntFormat2, $ZodSymbol2, $ZodUndefined2, $ZodNull2, $ZodAny2, $ZodUnknown2, $ZodNever2, $ZodVoid2, $ZodDate2, $ZodArray2, $ZodObject2, $ZodUnion2, $ZodDiscriminatedUnion2, $ZodIntersection2, $ZodTuple2, $ZodRecord2, $ZodMap2, $ZodSet2, $ZodEnum2, $ZodLiteral2, $ZodFile2, $ZodTransform2, $ZodOptional2, $ZodNullable2, $ZodDefault2, $ZodPrefault2, $ZodNonOptional2, $ZodSuccess2, $ZodCatch2, $ZodNaN2, $ZodPipe2, $ZodReadonly2, $ZodTemplateLiteral2, $ZodPromise2, $ZodLazy2, $ZodCustom2; +var init_schemas3 = __esm(() => { + init_checks3(); + init_core3(); + init_parse5(); + init_regexes2(); init_util2(); - cuidRegex = /^c[^\s-]{8,}$/i; - cuid2Regex = /^[0-9a-z]+$/; - ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; - uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; - nanoidRegex = /^[a-z0-9_-]{21}$/i; - jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; - durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; - ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; - ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; - ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; - dateRegex = new RegExp(`^${dateRegexSource}$`); - ZodString2 = class ZodString2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; + init_versions2(); + init_util2(); + $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => { + var _a3; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version4; + const checks3 = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks3.unshift(inst); + } + for (const ch of checks3) { + for (const fn of ch._zod.onattach) { + fn(inst); } - const status = new ParseStatus; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); + } + if (checks3.length === 0) { + (_a3 = inst._zod).deferred ?? (_a3.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks4, ctx) => { + let isAborted = aborted2(payload); + let asyncResult; + for (const ch of checks4) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted) { + continue; } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError2; } - } else if (check2.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode2.invalid_string, - message: check2.message + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted2(payload, currLen); }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted2(payload, currLen); } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT2(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cidr") { - if (!isValidCidr(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode2.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode2.invalid_string, - message: check2.message + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError2; + return result.then((result2) => runChecks(result2, checks3, ctx)); + } + return runChecks(result, checks3, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse3(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync3(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + }; + }); + $ZodString2 = /* @__PURE__ */ $constructor2("$ZodString", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string4(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) {} + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodStringFormat2 = /* @__PURE__ */ $constructor2("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat2.init(inst, def); + $ZodString2.init(inst, def); + }); + $ZodGUID2 = /* @__PURE__ */ $constructor2("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid3); + $ZodStringFormat2.init(inst, def); + }); + $ZodUUID2 = /* @__PURE__ */ $constructor2("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid3(v)); + } else + def.pattern ?? (def.pattern = uuid3()); + $ZodStringFormat2.init(inst, def); + }); + $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email3); + $ZodStringFormat2.init(inst, def); + }); + $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => { + $ZodStringFormat2.init(inst, def); + inst._zod.check = (payload) => { + try { + const orig = payload.value; + const url2 = new URL(orig); + const href = url2.href; + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: hostname3.source, + input: payload.value, + inst, + continue: !def.abort }); - status.dirty(); } - } else if (check2.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode2.invalid_string, - message: check2.message + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort }); - status.dirty(); } + } + if (!orig.endsWith("/") && href.endsWith("/")) { + payload.value = href.slice(0, -1); } else { - util.assertNever(check2); + payload.value = href; } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode2.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check2) { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options + }; + }); + $ZodEmoji2 = /* @__PURE__ */ $constructor2("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji3()); + $ZodStringFormat2.init(inst, def); + }); + $ZodNanoID2 = /* @__PURE__ */ $constructor2("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid3); + $ZodStringFormat2.init(inst, def); + }); + $ZodCUID3 = /* @__PURE__ */ $constructor2("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid5); + $ZodStringFormat2.init(inst, def); + }); + $ZodCUID22 = /* @__PURE__ */ $constructor2("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid23); + $ZodStringFormat2.init(inst, def); + }); + $ZodULID2 = /* @__PURE__ */ $constructor2("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid3); + $ZodStringFormat2.init(inst, def); + }); + $ZodXID2 = /* @__PURE__ */ $constructor2("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid3); + $ZodStringFormat2.init(inst, def); + }); + $ZodKSUID2 = /* @__PURE__ */ $constructor2("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid3); + $ZodStringFormat2.init(inst, def); + }); + $ZodISODateTime2 = /* @__PURE__ */ $constructor2("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime3(def)); + $ZodStringFormat2.init(inst, def); + }); + $ZodISODate2 = /* @__PURE__ */ $constructor2("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date5); + $ZodStringFormat2.init(inst, def); + }); + $ZodISOTime2 = /* @__PURE__ */ $constructor2("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time3(def)); + $ZodStringFormat2.init(inst, def); + }); + $ZodISODuration2 = /* @__PURE__ */ $constructor2("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration3); + $ZodStringFormat2.init(inst, def); + }); + $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv43); + $ZodStringFormat2.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv4`; + }); + }); + $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv63); + $ZodStringFormat2.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort }); } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options + }; + }); + $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv43); + $ZodStringFormat2.init(inst, def); + }); + $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv63); + $ZodStringFormat2.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error; + if (prefixNum < 0 || prefixNum > 128) + throw new Error; + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort }); } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) + }; + }); + $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base643); + $ZodStringFormat2.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase642(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) + }; + }); + $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url3); + $ZodStringFormat2.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL2(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) + }; + }); + $ZodE1642 = /* @__PURE__ */ $constructor2("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e1643); + $ZodStringFormat2.init(inst, def); + }); + $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => { + $ZodStringFormat2.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT2(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) + }; + }); + $ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat2.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) + }; + }); + $ZodNumber2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number4; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) + return payload; + }; + }); + $ZodNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { + $ZodCheckNumberFormat2.init(inst, def); + $ZodNumber2.init(inst, def); + }); + $ZodBoolean2 = /* @__PURE__ */ $constructor2("$ZodBoolean", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = boolean4; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) {} + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) + return payload; + }; + }); + $ZodBigInt2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = bigint4; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) {} + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) + return payload; + }; + }); + $ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { + $ZodCheckBigIntFormat2.init(inst, def); + $ZodBigInt2.init(inst, def); + }); + $ZodSymbol2 = /* @__PURE__ */ $constructor2("$ZodSymbol", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst }); - } - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] + return payload; + }; + }); + $ZodUndefined2 = /* @__PURE__ */ $constructor2("$ZodUndefined", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = _undefined4; + inst._zod.values = new Set([undefined]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst }); - } - toLowerCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] + return payload; + }; + }); + $ZodNull2 = /* @__PURE__ */ $constructor2("$ZodNull", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.pattern = _null4; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst }); - } - toUpperCase() { - return new ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] + return payload; + }; + }); + $ZodAny2 = /* @__PURE__ */ $constructor2("$ZodAny", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodUnknown2 = /* @__PURE__ */ $constructor2("$ZodUnknown", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodNever2 = /* @__PURE__ */ $constructor2("$ZodNever", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + return payload; + }; + }); + $ZodVoid2 = /* @__PURE__ */ $constructor2("$ZodVoid", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodDate2 = /* @__PURE__ */ $constructor2("$ZodDate", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) {} + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; + }); + $ZodArray2 = /* @__PURE__ */ $constructor2("$ZodArray", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0;i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult2(result2, payload, i))); + } else { + handleArrayResult2(result, payload, i); } } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => { + $ZodType2.init(inst, def); + const _normalized = cached2(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType2)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } } - return max; - } - }; - ZodString2.create = (params) => { - return new ZodString2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) + const okeys = optionalKeys2(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; }); - }; - ZodNumber2 = class ZodNumber2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); + defineLazy2(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = new Set); + for (const v of field.values) + propValues[key].add(v); + } } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; + return propValues; + }); + const generateFastpass = (shape) => { + const doc2 = new Doc2(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc2(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc2.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; } - let ctx = undefined; - const status = new ParseStatus; - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder2(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_finite, - message: check2.message - }); - status.dirty(); + doc2.write(`const newResult = {}`); + for (const key of normalized.keys) { + if (normalized.optionalKeys.has(key)) { + const id = ids[key]; + doc2.write(`const ${id} = ${parseStr(key)};`); + const k = esc2(key); + doc2.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; } else { - util.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodNumber2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + newResult[${k}] = ${id}.value; } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + `); + } else { + const id = ids[key]; + doc2.write(`const ${id} = ${parseStr(key)};`); + doc2.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${esc2(key)}, ...iss.path] : [${esc2(key)}] + })));`); + doc2.write(`newResult[${esc2(key)}] = ${id}.value`); } } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + doc2.write(`payload.value = newResult;`); + doc2.write(`return payload;`); + const fn = doc2.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject3 = isObject2; + const jit = !globalConfig2.jitless; + const allowsEval3 = allowsEval2; + const fastEnabled = jit && allowsEval3.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject3(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; } - return Number.isFinite(min) && Number.isFinite(max); - } - }; - ZodNumber2.create = (params) => { - return new ZodNumber2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); - }; - ZodBigInt2 = class ZodBigInt2 extends ZodType2 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); + } else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } else { + handleObjectResult(r, payload, key); + } } } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.bigint) { - return this._getInvalidInput(input); + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; } - let ctx = undefined; - const status = new ParseStatus; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } + const unrecognized = []; + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); } else { - util.assertNever(check2); + handleObjectResult(r, payload, key); } } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt2({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new ZodBigInt2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; + }); + $ZodUnion2 = /* @__PURE__ */ $constructor2("$ZodUnion", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); + defineLazy2(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazy2(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } - return max; - } - }; - ZodBigInt2.create = (params) => { - return new ZodBigInt2({ - checks: [], - typeName: ZodFirstPartyTypeKind2.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) + return; }); - }; - ZodBoolean2 = class ZodBoolean2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; + defineLazy2(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex2(p.source)).join("|")})$`); } - return OK(input.data); - } - }; - ZodBoolean2.create = (params) => { - return new ZodBoolean2({ - typeName: ZodFirstPartyTypeKind2.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) + return; }); - }; - ZodDate2 = class ZodDate2 extends ZodType2 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_date - }); - return INVALID; - } - const status = new ParseStatus; - let ctx = undefined; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" - }); - status.dirty(); - } + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; } else { - util.assertNever(check2); + if (result.issues.length === 0) + return result; + results.push(result); } } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check2) { - return new ZodDate2({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) + if (!async) + return handleUnionResults2(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults2(results2, payload, inst, ctx); }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + }; + }); + $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion2.init(inst, def); + const _super = inst._zod.parse; + defineLazy2(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = new Set; + for (const val of v) { + propValues[k].add(val); + } } } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + return propValues; + }); + const disc = cached2(() => { + const opts = def.options; + const map2 = new Map; + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map2.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map2.set(v, o); } } - return max != null ? new Date(max) : null; - } - }; - ZodDate2.create = (params) => { - return new ZodDate2({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind2.ZodDate, - ...processCreateParams(params) + return map2; }); - }; - ZodSymbol2 = class ZodSymbol2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst }); - return INVALID; + return payload; } - return OK(input.data); - } - }; - ZodSymbol2.create = (params) => { - return new ZodSymbol2({ - typeName: ZodFirstPartyTypeKind2.ZodSymbol, - ...processCreateParams(params) - }); - }; - ZodUndefined2 = class ZodUndefined2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); } - return OK(input.data); - } - }; - ZodUndefined2.create = (params) => { - return new ZodUndefined2({ - typeName: ZodFirstPartyTypeKind2.ZodUndefined, - ...processCreateParams(params) - }); - }; - ZodNull2 = class ZodNull2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; + if (def.unionFallback) { + return _super(payload, ctx); } - return OK(input.data); - } - }; - ZodNull2.create = (params) => { - return new ZodNull2({ - typeName: ZodFirstPartyTypeKind2.ZodNull, - ...processCreateParams(params) - }); - }; - ZodAny2 = class ZodAny2 extends ZodType2 { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } - }; - ZodAny2.create = (params) => { - return new ZodAny2({ - typeName: ZodFirstPartyTypeKind2.ZodAny, - ...processCreateParams(params) - }); - }; - ZodUnknown2 = class ZodUnknown2 extends ZodType2 { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } - }; - ZodUnknown2.create = (params) => { - return new ZodUnknown2({ - typeName: ZodFirstPartyTypeKind2.ZodUnknown, - ...processCreateParams(params) - }); - }; - ZodNever2 = class ZodNever2 extends ZodType2 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst }); - return INVALID; - } - }; - ZodNever2.create = (params) => { - return new ZodNever2({ - typeName: ZodFirstPartyTypeKind2.ZodNever, - ...processCreateParams(params) - }); - }; - ZodVoid2 = class ZodVoid2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType + return payload; + }; + }); + $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults2(payload, left2, right2); }); - return INVALID; } - return OK(input.data); - } - }; - ZodVoid2.create = (params) => { - return new ZodVoid2({ - typeName: ZodFirstPartyTypeKind2.ZodVoid, - ...processCreateParams(params) - }); - }; - ZodArray2 = class ZodArray2 extends ZodType2 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType + return handleIntersectionResults2(payload, left, right); + }; + }); + $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => { + $ZodType2.init(inst, def); + const items = def.items; + const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" }); - return INVALID; + return payload; } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; + payload.value = []; + const proms = []; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message + payload.issues.push({ + input, + inst, + origin: "array", + ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length } }); - status.dirty(); + return payload; } } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) { + if (i >= optStart) + continue; } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); + const result = item._zod.run({ + value: input[i], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult2(result2, payload, i))); + } else { + handleTupleResult2(result, payload, i); } } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray2({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new ZodArray2({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new ZodArray2({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } - }; - ZodArray2.create = (schema, params) => { - return new ZodArray2({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind2.ZodArray, - ...processCreateParams(params) - }); - }; - ZodObject2 = class ZodObject2 extends ZodType2 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult2(result2, payload, i))); + } else { + handleTupleResult2(result, payload, i); } } } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject2(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst }); + return payload; } - if (this._def.catchall instanceof ZodNever2) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues2(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues2(key, result.issues)); + } + payload.value[key] = result.value; + } } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode2.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); + } + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized }); } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject2({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())), + input: key, + path: [key], + inst + }); + payload.value[keyResult.value] = keyResult.value; + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues2(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues2(key, result.issues)); + } + payload.value[keyResult.value] = result.value; } - } : {} - }); - } - strip() { - return new ZodObject2({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject2({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject2({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject2({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind2.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index) { - return new ZodObject2({ - ...this._def, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; } } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } + if (proms.length) { + return Promise.all(proms).then(() => payload); } - return new ZodObject2({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; + return payload; + }; + }); + $ZodMap2 = /* @__PURE__ */ $constructor2("$ZodMap", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = new Map; + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult2(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); } else { - newShape[key] = fieldSchema.optional(); + handleMapResult2(keyResult, valueResult, payload, key, input, inst, ctx); } } - return new ZodObject2({ - ...this._def, - shape: () => newShape + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodSet2 = /* @__PURE__ */ $constructor2("$ZodSet", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = new Set; + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult2(result2, payload))); + } else + handleSetResult2(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodEnum2 = /* @__PURE__ */ $constructor2("$ZodEnum", (inst, def) => { + $ZodType2.init(inst, def); + const values = getEnumValues2(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes2.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional2) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } + return payload; + }; + }); + $ZodLiteral2 = /* @__PURE__ */ $constructor2("$ZodLiteral", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex2(o) : o ? o.toString() : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; } - return new ZodObject2({ - ...this._def, - shape: () => newShape + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } - }; - ZodObject2.create = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); - }; - ZodObject2.strictCreate = (shape, params) => { - return new ZodObject2({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); - }; - ZodObject2.lazycreate = (shape, params) => { - return new ZodObject2({ - shape, - unknownKeys: "strip", - catchall: ZodNever2.create(), - typeName: ZodFirstPartyTypeKind2.ZodObject, - ...processCreateParams(params) - }); - }; - ZodUnion2 = class ZodUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors + return payload; + }; + }); + $ZodFile2 = /* @__PURE__ */ $constructor2("$ZodFile", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodTransform2 = /* @__PURE__ */ $constructor2("$ZodTransform", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + return payload; }); - return INVALID; } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError2(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union, - unionErrors - }); - return INVALID; + if (_out instanceof Promise) { + throw new $ZodAsyncError2; } - } - get options() { - return this._def.options; - } - }; - ZodUnion2.create = (types, params) => { - return new ZodUnion2({ - options: types, - typeName: ZodFirstPartyTypeKind2.ZodUnion, - ...processCreateParams(params) + payload.value = _out; + return payload; + }; + }); + $ZodOptional2 = /* @__PURE__ */ $constructor2("$ZodOptional", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy2(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; }); - }; - ZodDiscriminatedUnion2 = class ZodDiscriminatedUnion2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; + defineLazy2(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; + if (payload.value === undefined) { + return payload; } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNullable2 = /* @__PURE__ */ $constructor2("$ZodNullable", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy2(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)}|null)$`) : undefined; + }); + defineLazy2(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodDefault2 = /* @__PURE__ */ $constructor2("$ZodDefault", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.optin = "optional"; + defineLazy2(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + return payload; } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult2(result2, def)); } - return new ZodDiscriminatedUnion2({ - typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } - }; - ZodIntersection2 = class ZodIntersection2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues2(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); + return handleDefaultResult2(result, def); + }; + }); + $ZodPrefault2 = /* @__PURE__ */ $constructor2("$ZodPrefault", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.optin = "optional"; + defineLazy2(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; } - } - }; - ZodIntersection2.create = (left, right, params) => { - return new ZodIntersection2({ - left, - right, - typeName: ZodFirstPartyTypeKind2.ZodIntersection, - ...processCreateParams(params) + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNonOptional2 = /* @__PURE__ */ $constructor2("$ZodNonOptional", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; }); - }; - ZodTuple2 = class ZodTuple2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult2(result2, inst)); } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" + return handleNonOptionalResult2(result, inst); + }; + }); + $ZodSuccess2 = /* @__PURE__ */ $constructor2("$ZodSuccess", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; }); - return INVALID; } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" + payload.value = result.issues.length === 0; + return payload; + }; + }); + $ZodCatch2 = /* @__PURE__ */ $constructor2("$ZodCatch", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.optin = "optional"; + defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy2(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; }); - status.dirty(); } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) + }, + input: payload.value }); - } else { - return ParseStatus.mergeArray(status, items); + payload.issues = []; } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple2({ - ...this._def, - rest - }); - } - }; - ZodTuple2.create = (schemas3, params) => { - if (!Array.isArray(schemas3)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple2({ - items: schemas3, - typeName: ZodFirstPartyTypeKind2.ZodTuple, - rest: null, - ...processCreateParams(params) - }); - }; - ZodRecord2 = class ZodRecord2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType + return payload; + }; + }); + $ZodNaN2 = /* @__PURE__ */ $constructor2("$ZodNaN", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" }); - return INVALID; + return payload; } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); + return payload; + }; + }); + $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "values", () => def.in._zod.values); + defineLazy2(inst._zod, "optin", () => def.in._zod.optin); + defineLazy2(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult2(left2, def, ctx)); } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); + return handlePipeResult2(left, def, ctx); + }; + }); + $ZodReadonly2 = /* @__PURE__ */ $constructor2("$ZodReadonly", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy2(inst._zod, "values", () => def.innerType._zod.values); + defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult2); + } + return handleReadonlyResult2(result); + }; + }); + $ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("$ZodTemplateLiteral", (inst, def) => { + $ZodType2.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (part instanceof $ZodType2) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes2.has(typeof part)) { + regexParts.push(escapeRegex2(`${part}`)); } else { - return ParseStatus.mergeObjectSync(status, pairs); + throw new Error(`Invalid template literal part: ${part}`); } } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType2) { - return new ZodRecord2({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams(third) + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "template_literal", + code: "invalid_type" }); + return payload; } - return new ZodRecord2({ - keyType: ZodString2.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind2.ZodRecord, - ...processCreateParams(second) - }); - } - }; - ZodMap2 = class ZodMap2 extends ZodType2 { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: "template_literal", + pattern: inst._zod.pattern.source }); - return INVALID; + return payload; } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + return payload; + }; + }); + $ZodPromise2 = /* @__PURE__ */ $constructor2("$ZodPromise", (inst, def) => { + $ZodType2.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; + }); + $ZodLazy2 = /* @__PURE__ */ $constructor2("$ZodLazy", (inst, def) => { + $ZodType2.init(inst, def); + defineLazy2(inst._zod, "innerType", () => def.getter()); + defineLazy2(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); + defineLazy2(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); + defineLazy2(inst._zod, "optin", () => inst._zod.innerType._zod.optin); + defineLazy2(inst._zod, "optout", () => inst._zod.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; + }); + $ZodCustom2 = /* @__PURE__ */ $constructor2("$ZodCustom", (inst, def) => { + $ZodCheck2.init(inst, def); + $ZodType2.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult2(r2, payload, input, inst)); } - } + handleRefineResult2(r, payload, input, inst); + return; + }; + }); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ar.js +function ar_default2() { + return { + localeError: error51() }; - ZodMap2.create = (keyType, valueType, params) => { - return new ZodMap2({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind2.ZodMap, - ...processCreateParams(params) - }); +} +var error51 = () => { + const Sizable = { + string: { unit: "حرف", verb: "أن يحوي" }, + file: { unit: "بايت", verb: "أن يحوي" }, + array: { unit: "عنصر", verb: "أن يحوي" }, + set: { unit: "عنصر", verb: "أن يحوي" } }; - ZodSet2 = class ZodSet2 extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); + case "object": { + if (Array.isArray(data)) { + return "array"; } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode2.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); + if (data === null) { + return "null"; } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); } } - min(minSize, message) { - return new ZodSet2({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new ZodSet2({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } + return t; }; - ZodSet2.create = (valueType, params) => { - return new ZodSet2({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind2.ZodSet, - ...processCreateParams(params) - }); + const Nouns = { + regex: "مدخل", + email: "بريد إلكتروني", + url: "رابط", + emoji: "إيموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاريخ ووقت بمعيار ISO", + date: "تاريخ بمعيار ISO", + time: "وقت بمعيار ISO", + duration: "مدة بمعيار ISO", + ipv4: "عنوان IPv4", + ipv6: "عنوان IPv6", + cidrv4: "مدى عناوين بصيغة IPv4", + cidrv6: "مدى عناوين بصيغة IPv6", + base64: "نَص بترميز base64-encoded", + base64url: "نَص بترميز base64url-encoded", + json_string: "نَص على هيئة JSON", + e164: "رقم هاتف بمعيار E.164", + jwt: "JWT", + template_literal: "مدخل" }; - ZodFunction2 = class ZodFunction2 extends ZodType2 { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error51) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_arguments, - argumentsError: error51 - } - }); + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `مدخلات غير مقبولة: يفترض إدخال ${issue3.expected}، ولكن تم إدخال ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive2(issue3.values[0])}`; + return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return ` أكبر من اللازم: يفترض أن تكون ${issue3.origin ?? "القيمة"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "عنصر"}`; + return `أكبر من اللازم: يفترض أن تكون ${issue3.origin ?? "القيمة"} ${adj} ${issue3.maximum.toString()}`; } - function makeReturnsIssue(returns, error51) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x) => !!x), - issueData: { - code: ZodIssueCode2.invalid_return_type, - returnTypeError: error51 - } - }); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; + } + return `أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()}`; } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise2) { - const me = this; - return OK(async function(...args) { - const error51 = new ZodError2([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error51.addIssue(makeArgsIssue(args, e)); - throw error51; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error51.addIssue(makeReturnsIssue(result, e)); - throw error51; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `نَص غير مقبول: يجب أن يبدأ بـ "${issue3.prefix}"`; + if (_issue.format === "ends_with") + return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; + if (_issue.format === "regex") + return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} غير مقبول`; } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction2({ - ...this._def, - args: ZodTuple2.create(items).rest(ZodUnknown2.create()) - }); - } - returns(returnType) { - return new ZodFunction2({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction2({ - args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), - returns: returns || ZodUnknown2.create(), - typeName: ZodFirstPartyTypeKind2.ZodFunction, - ...processCreateParams(params) - }); + case "not_multiple_of": + return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue3.divisor}`; + case "unrecognized_keys": + return `معرف${issue3.keys.length > 1 ? "ات" : ""} غريب${issue3.keys.length > 1 ? "ة" : ""}: ${joinValues2(issue3.keys, "، ")}`; + case "invalid_key": + return `معرف غير مقبول في ${issue3.origin}`; + case "invalid_union": + return "مدخل غير مقبول"; + case "invalid_element": + return `مدخل غير مقبول في ${issue3.origin}`; + default: + return "مدخل غير مقبول"; } }; - ZodLazy2 = class ZodLazy2 extends ZodType2 { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } +}; +var init_ar2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/az.js +function az_default2() { + return { + localeError: error52() }; - ZodLazy2.create = (getter, params) => { - return new ZodLazy2({ - getter, - typeName: ZodFirstPartyTypeKind2.ZodLazy, - ...processCreateParams(params) - }); +} +var error52 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "element", verb: "olmalıdır" }, + set: { unit: "element", verb: "olmalıdır" } }; - ZodLiteral2 = class ZodLiteral2 extends ZodType2 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_literal, - expected: this._def.value - }); - return INVALID; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; } + return t; }; - ZodLiteral2.create = (value, params) => { - return new ZodLiteral2({ - value, - typeName: ZodFirstPartyTypeKind2.ZodLiteral, - ...processCreateParams(params) - }); + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" }; - ZodEnum2 = class ZodEnum2 extends ZodType2 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Yanlış dəyər: gözlənilən ${issue3.expected}, daxil olan ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Yanlış dəyər: gözlənilən ${stringifyPrimitive2(issue3.values[0])}`; + return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Çox böyük: gözlənilən ${issue3.origin ?? "dəyər"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Çox böyük: gözlənilən ${issue3.origin ?? "dəyər"} ${adj}${issue3.maximum.toString()}`; } - if (!this._cache) { - this._cache = new Set(this._def.values); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + return `Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; + if (_issue.format === "ends_with") + return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; + if (_issue.format === "includes") + return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; + if (_issue.format === "regex") + return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; + return `Yanlış ${Nouns[_issue.format] ?? issue3.format}`; } - return OK(input.data); - } - get options() { - return this._def.values; + case "not_multiple_of": + return `Yanlış ədəd: ${issue3.divisor} ilə bölünə bilən olmalıdır`; + case "unrecognized_keys": + return `Tanınmayan açar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `${issue3.origin} daxilində yanlış açar`; + case "invalid_union": + return "Yanlış dəyər"; + case "invalid_element": + return `${issue3.origin} daxilində yanlış dəyər`; + default: + return `Yanlış dəyər`; } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; + }; +}; +var init_az2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/be.js +function getBelarusianPlural2(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +function be_default2() { + return { + localeError: error53() + }; +} +var error53 = () => { + const Sizable = { + string: { + unit: { + one: "сімвал", + few: "сімвалы", + many: "сімвалаў" + }, + verb: "мець" + }, + array: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў" + }, + verb: "мець" + }, + set: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў" + }, + verb: "мець" + }, + file: { + unit: { + one: "байт", + few: "байты", + many: "байтаў" + }, + verb: "мець" } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "лік"; } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + case "object": { + if (Array.isArray(data)) { + return "масіў"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum2.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); } + return t; }; - ZodEnum2.create = createZodEnum; - ZodNativeEnum = class ZodNativeEnum extends ZodType2 { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode2.invalid_type - }); - return INVALID; + const Nouns = { + regex: "увод", + email: "email адрас", + url: "URL", + emoji: "эмодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата і час", + date: "ISO дата", + time: "ISO час", + duration: "ISO працягласць", + ipv4: "IPv4 адрас", + ipv6: "IPv6 адрас", + cidrv4: "IPv4 дыяпазон", + cidrv6: "IPv6 дыяпазон", + base64: "радок у фармаце base64", + base64url: "радок у фармаце base64url", + json_string: "JSON радок", + e164: "нумар E.164", + jwt: "JWT", + template_literal: "увод" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Няправільны ўвод: чакаўся ${issue3.expected}, атрымана ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Няправільны ўвод: чакалася ${stringifyPrimitive2(issue3.values[0])}`; + return `Няправільны варыянт: чакаўся адзін з ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + const maxValue = Number(issue3.maximum); + const unit = getBelarusianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта вялікі: чакалася, што ${issue3.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue3.maximum.toString()} ${unit}`; + } + return `Занадта вялікі: чакалася, што ${issue3.origin ?? "значэнне"} павінна быць ${adj}${issue3.maximum.toString()}`; } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + const minValue = Number(issue3.minimum); + const unit = getBelarusianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта малы: чакалася, што ${issue3.origin} павінна ${sizing.verb} ${adj}${issue3.minimum.toString()} ${unit}`; + } + return `Занадта малы: чакалася, што ${issue3.origin} павінна быць ${adj}${issue3.minimum.toString()}`; } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode2.invalid_enum_value, - options: expectedValues - }); - return INVALID; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; + if (_issue.format === "regex") + return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; + return `Няправільны ${Nouns[_issue.format] ?? issue3.format}`; } - return OK(input.data); - } - get enum() { - return this._def.values; + case "not_multiple_of": + return `Няправільны лік: павінен быць кратным ${issue3.divisor}`; + case "unrecognized_keys": + return `Нераспазнаны ${issue3.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Няправільны ключ у ${issue3.origin}`; + case "invalid_union": + return "Няправільны ўвод"; + case "invalid_element": + return `Няправільнае значэнне ў ${issue3.origin}`; + default: + return `Няправільны ўвод`; } }; - ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, - ...processCreateParams(params) - }); +}; +var init_be2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ca.js +function ca_default2() { + return { + localeError: error54() }; - ZodPromise2 = class ZodPromise2 extends ZodType2 { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; +} +var error54 = () => { + const Sizable = { + string: { unit: "caràcters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); } + return t; }; - ZodPromise2.create = (schema, params) => { - return new ZodPromise2({ - type: schema, - typeName: ZodFirstPartyTypeKind2.ZodPromise, - ...processCreateParams(params) - }); + const Nouns = { + regex: "entrada", + email: "adreça electrònica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adreça IPv4", + ipv6: "adreça IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada" }; - ZodEffects = class ZodEffects extends ZodType2 { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Tipus invàlid: s'esperava ${issue3.expected}, s'ha rebut ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Valor invàlid: s'esperava ${stringifyPrimitive2(issue3.values[0])}`; + return `Opció invàlida: s'esperava una de ${joinValues2(issue3.values, " o ")}`; + case "too_big": { + const adj = issue3.inclusive ? "com a màxim" : "menys de"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} contingués ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} fos ${adj} ${issue3.maximum.toString()}`; } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); + case "too_small": { + const adj = issue3.inclusive ? "com a mínim" : "més de"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue3.origin} contingués ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } + return `Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`; } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Format invàlid: ha de començar amb "${_issue.prefix}"`; } + if (_issue.format === "ends_with") + return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format invàlid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; + return `Format invàlid per a ${Nouns[_issue.format] ?? issue3.format}`; } - util.assertNever(effect); + case "not_multiple_of": + return `Número invàlid: ha de ser múltiple de ${issue3.divisor}`; + case "unrecognized_keys": + return `Clau${issue3.keys.length > 1 ? "s" : ""} no reconeguda${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Clau invàlida a ${issue3.origin}`; + case "invalid_union": + return "Entrada invàlida"; + case "invalid_element": + return `Element invàlid a ${issue3.origin}`; + default: + return `Entrada invàlida`; } }; - ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - effect, - ...processCreateParams(params) - }); +}; +var init_ca2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/cs.js +function cs_default2() { + return { + localeError: error55() }; - ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind2.ZodEffects, - ...processCreateParams(params) - }); +} +var error55 = () => { + const Sizable = { + string: { unit: "znaků", verb: "mít" }, + file: { unit: "bajtů", verb: "mít" }, + array: { unit: "prvků", verb: "mít" }, + set: { unit: "prvků", verb: "mít" } }; - ZodOptional2 = class ZodOptional2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.undefined) { - return OK(undefined); + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "číslo"; } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - }; - ZodOptional2.create = (type, params) => { - return new ZodOptional2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodOptional, - ...processCreateParams(params) - }); - }; - ZodNullable2 = class ZodNullable2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.null) { - return OK(null); + case "string": { + return "řetězec"; } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } - }; - ZodNullable2.create = (type, params) => { - return new ZodNullable2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodNullable, - ...processCreateParams(params) - }); - }; - ZodDefault2 = class ZodDefault2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); + case "boolean": { + return "boolean"; } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } - }; - ZodDefault2.create = (type, params) => { - return new ZodDefault2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); - }; - ZodCatch2 = class ZodCatch2 extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] + case "bigint": { + return "bigint"; + } + case "function": { + return "funkce"; + } + case "symbol": { + return "symbol"; + } + case "undefined": { + return "undefined"; + } + case "object": { + if (Array.isArray(data)) { + return "pole"; } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError2(newCtx.common.issues); - }, - input: newCtx.data - }) - }; } } - removeCatch() { - return this._def.innerType; - } + return t; }; - ZodCatch2.create = (type, params) => { - return new ZodCatch2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); + const Nouns = { + regex: "regulární výraz", + email: "e-mailová adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a čas ve formátu ISO", + date: "datum ve formátu ISO", + time: "čas ve formátu ISO", + duration: "doba trvání ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "řetězec zakódovaný ve formátu base64", + base64url: "řetězec zakódovaný ve formátu base64url", + json_string: "řetězec ve formátu JSON", + e164: "číslo E.164", + jwt: "JWT", + template_literal: "vstup" }; - ZodNaN2 = class ZodNaN2 extends ZodType2 { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode2.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Neplatný vstup: očekáváno ${issue3.expected}, obdrženo ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Neplatný vstup: očekáváno ${stringifyPrimitive2(issue3.values[0])}`; + return `Neplatná možnost: očekávána jedna z hodnot ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Hodnota je příliš velká: ${issue3.origin ?? "hodnota"} musí mít ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš velká: ${issue3.origin ?? "hodnota"} musí být ${adj}${issue3.maximum.toString()}`; } - return { status: "valid", value: input.data }; + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Hodnota je příliš malá: ${issue3.origin ?? "hodnota"} musí mít ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš malá: ${issue3.origin ?? "hodnota"} musí být ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; + return `Neplatný formát ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Neplatné číslo: musí být násobkem ${issue3.divisor}`; + case "unrecognized_keys": + return `Neznámé klíče: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Neplatný klíč v ${issue3.origin}`; + case "invalid_union": + return "Neplatný vstup"; + case "invalid_element": + return `Neplatná hodnota v ${issue3.origin}`; + default: + return `Neplatný vstup`; } }; - ZodNaN2.create = (params) => { - return new ZodNaN2({ - typeName: ZodFirstPartyTypeKind2.ZodNaN, - ...processCreateParams(params) - }); - }; - BRAND = Symbol("zod_brand"); - ZodBranded = class ZodBranded extends ZodType2 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } +}; +var init_cs2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/de.js +function de_default2() { + return { + localeError: error56() }; - ZodPipeline = class ZodPipeline extends ZodType2 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); +} +var error56 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "Zahl"; + } + case "object": { + if (Array.isArray(data)) { + return "Array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind2.ZodPipeline - }); - } + return t; }; - ZodReadonly2 = class ZodReadonly2 extends ZodType2 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); + const Nouns = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Ungültige Eingabe: erwartet ${issue3.expected}, erhalten ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Ungültige Eingabe: erwartet ${stringifyPrimitive2(issue3.values[0])}`; + return `Ungültige Option: erwartet eine von ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Zu groß: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu groß: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`; } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; + return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ungültiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ungültiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ungültig: ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Ungültige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`; + case "unrecognized_keys": + return `${issue3.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Ungültiger Schlüssel in ${issue3.origin}`; + case "invalid_union": + return "Ungültige Eingabe"; + case "invalid_element": + return `Ungültiger Wert in ${issue3.origin}`; + default: + return `Ungültige Eingabe`; } }; - ZodReadonly2.create = (type, params) => { - return new ZodReadonly2({ - innerType: type, - typeName: ZodFirstPartyTypeKind2.ZodReadonly, - ...processCreateParams(params) - }); - }; - late = { - object: ZodObject2.lazycreate - }; - (function(ZodFirstPartyTypeKind3) { - ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; - })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); - stringType = ZodString2.create; - numberType = ZodNumber2.create; - nanType = ZodNaN2.create; - bigIntType = ZodBigInt2.create; - booleanType = ZodBoolean2.create; - dateType = ZodDate2.create; - symbolType = ZodSymbol2.create; - undefinedType = ZodUndefined2.create; - nullType = ZodNull2.create; - anyType = ZodAny2.create; - unknownType = ZodUnknown2.create; - neverType = ZodNever2.create; - voidType = ZodVoid2.create; - arrayType = ZodArray2.create; - objectType = ZodObject2.create; - strictObjectType = ZodObject2.strictCreate; - unionType = ZodUnion2.create; - discriminatedUnionType = ZodDiscriminatedUnion2.create; - intersectionType = ZodIntersection2.create; - tupleType = ZodTuple2.create; - recordType = ZodRecord2.create; - mapType = ZodMap2.create; - setType = ZodSet2.create; - functionType = ZodFunction2.create; - lazyType = ZodLazy2.create; - literalType = ZodLiteral2.create; - enumType = ZodEnum2.create; - nativeEnumType = ZodNativeEnum.create; - promiseType = ZodPromise2.create; - effectsType = ZodEffects.create; - optionalType = ZodOptional2.create; - nullableType = ZodNullable2.create; - preprocessType = ZodEffects.createWithPreprocess; - pipelineType = ZodPipeline.create; - coerce = { - string: (arg) => ZodString2.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean2.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), - date: (arg) => ZodDate2.create({ ...arg, coerce: true }) - }; - NEVER2 = INVALID; -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/external.js -var exports_external2 = {}; -__export(exports_external2, { - void: () => voidType, - util: () => util, - unknown: () => unknownType, - union: () => unionType, - undefined: () => undefinedType, - tuple: () => tupleType, - transformer: () => effectsType, - symbol: () => symbolType, - string: () => stringType, - strictObject: () => strictObjectType, - setErrorMap: () => setErrorMap2, - set: () => setType, - record: () => recordType, - quotelessJson: () => quotelessJson, - promise: () => promiseType, - preprocess: () => preprocessType, - pipeline: () => pipelineType, - ostring: () => ostring, - optional: () => optionalType, - onumber: () => onumber, - oboolean: () => oboolean, - objectUtil: () => objectUtil, - object: () => objectType, - number: () => numberType, - nullable: () => nullableType, - null: () => nullType, - never: () => neverType, - nativeEnum: () => nativeEnumType, - nan: () => nanType, - map: () => mapType, - makeIssue: () => makeIssue, - literal: () => literalType, - lazy: () => lazyType, - late: () => late, - isValid: () => isValid, - isDirty: () => isDirty, - isAsync: () => isAsync, - isAborted: () => isAborted, - intersection: () => intersectionType, - instanceof: () => instanceOfType, - getParsedType: () => getParsedType2, - getErrorMap: () => getErrorMap2, - function: () => functionType, - enum: () => enumType, - effect: () => effectsType, - discriminatedUnion: () => discriminatedUnionType, - defaultErrorMap: () => en_default2, - datetimeRegex: () => datetimeRegex, - date: () => dateType, - custom: () => custom2, - coerce: () => coerce, - boolean: () => booleanType, - bigint: () => bigIntType, - array: () => arrayType, - any: () => anyType, - addIssueToContext: () => addIssueToContext, - ZodVoid: () => ZodVoid2, - ZodUnknown: () => ZodUnknown2, - ZodUnion: () => ZodUnion2, - ZodUndefined: () => ZodUndefined2, - ZodType: () => ZodType2, - ZodTuple: () => ZodTuple2, - ZodTransformer: () => ZodEffects, - ZodSymbol: () => ZodSymbol2, - ZodString: () => ZodString2, - ZodSet: () => ZodSet2, - ZodSchema: () => ZodType2, - ZodRecord: () => ZodRecord2, - ZodReadonly: () => ZodReadonly2, - ZodPromise: () => ZodPromise2, - ZodPipeline: () => ZodPipeline, - ZodParsedType: () => ZodParsedType, - ZodOptional: () => ZodOptional2, - ZodObject: () => ZodObject2, - ZodNumber: () => ZodNumber2, - ZodNullable: () => ZodNullable2, - ZodNull: () => ZodNull2, - ZodNever: () => ZodNever2, - ZodNativeEnum: () => ZodNativeEnum, - ZodNaN: () => ZodNaN2, - ZodMap: () => ZodMap2, - ZodLiteral: () => ZodLiteral2, - ZodLazy: () => ZodLazy2, - ZodIssueCode: () => ZodIssueCode2, - ZodIntersection: () => ZodIntersection2, - ZodFunction: () => ZodFunction2, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, - ZodError: () => ZodError2, - ZodEnum: () => ZodEnum2, - ZodEffects: () => ZodEffects, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, - ZodDefault: () => ZodDefault2, - ZodDate: () => ZodDate2, - ZodCatch: () => ZodCatch2, - ZodBranded: () => ZodBranded, - ZodBoolean: () => ZodBoolean2, - ZodBigInt: () => ZodBigInt2, - ZodArray: () => ZodArray2, - ZodAny: () => ZodAny2, - Schema: () => ZodType2, - ParseStatus: () => ParseStatus, - OK: () => OK, - NEVER: () => NEVER2, - INVALID: () => INVALID, - EMPTY_PATH: () => EMPTY_PATH, - DIRTY: () => DIRTY, - BRAND: () => BRAND -}); -var init_external2 = __esm(() => { - init_errors4(); - init_parseUtil(); - init_typeAliases(); +}; +var init_de2 = __esm(() => { init_util2(); - init_types(); - init_ZodError(); -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/index.js -var init_v3 = __esm(() => { - init_external2(); - init_external2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js -function parseArrayDef(def, refs) { - const res = { type: "array" }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - if (def.minLength) - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - if (def.maxLength) - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js +function en_default2() { + return { + localeError: error57() + }; } -var init_array = __esm(() => { - init_errorMessages(); - init_parseDef(); - init_v3(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" +var parsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}, error57 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" } }; - if (!def.checks) - return res; - for (const check2 of def.checks) - switch (check2.kind) { - case "min": - if (refs.target === "jsonSchema7") - if (check2.inclusive) - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - else - setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); - else { - if (!check2.inclusive) - res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Invalid input: expected ${issue3.expected}, received ${parsedType2(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; + return `Invalid option: expected one of ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Too big: expected ${issue3.origin ?? "value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue3.origin ?? "value"} to be ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } - break; - case "max": - if (refs.target === "jsonSchema7") - if (check2.inclusive) - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); - else - setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); - else { - if (!check2.inclusive) - res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + return `Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); - break; + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue3.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue3.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue3.origin}`; + default: + return `Invalid input`; } - return res; -} -var init_bigint = __esm(() => { - init_errorMessages(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js -function parseBooleanDef() { - return { type: "boolean" }; -} -var init_boolean = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} -var init_branded = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js -var parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; -var init_catch = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) - return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time" - }; - case "format:date": - return { - type: "string", - format: "date" - }; - case "integer": - return integerDateParser(def, refs); - } -} -var integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" }; - if (refs.target === "openApi3") - return res; - for (const check2 of def.checks) - switch (check2.kind) { - case "min": - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); - break; - } - return res; }; -var init_date = __esm(() => { - init_errorMessages(); +var init_en2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js -function parseDefaultDef(_def, refs) { +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/eo.js +function eo_default2() { return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() + localeError: error58() }; } -var init_default = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); -} -var init_effects = __esm(() => { - init_any(); - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) +var parsedType3 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombro"; + } + case "object": { + if (Array.isArray(data)) { + return "tabelo"; + } + if (data === null) { + return "senvalora"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}, error58 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } }; -} -var init_enum = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js -function parseIntersectionDef(def, refs) { - const allOf = [parseDef(def.left._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }), parseDef(def.right._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "1" - ] - })].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) - unevaluatedProperties = undefined; - } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } else - unevaluatedProperties = undefined; - mergedAllOf.push(nestedSchema); + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emoĝio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-daŭro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Nevalida enigo: atendiĝis ${issue3.expected}, riceviĝis ${parsedType3(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Nevalida enigo: atendiĝis ${stringifyPrimitive2(issue3.values[0])}`; + return `Nevalida opcio: atendiĝis unu el ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Tro granda: atendiĝis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendiĝis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Tro malgranda: atendiĝis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendiĝis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue3.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue3.keys.length > 1 ? "j" : ""} ŝlosilo${issue3.keys.length > 1 ? "j" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Nevalida ŝlosilo en ${issue3.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue3.origin}`; + default: + return `Nevalida enigo`; } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : undefined; -} -var isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; + }; }; -var init_intersection = __esm(() => { - init_parseDef(); +var init_eo2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js -function parseLiteralDef(def, refs) { - const parsedType2 = typeof def.value; - if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") - return { type: Array.isArray(def.value) ? "array" : "object" }; - if (refs.target === "openApi3") - return { - type: parsedType2 === "bigint" ? "integer" : parsedType2, - enum: [def.value] - }; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/es.js +function es_default2() { return { - type: parsedType2 === "bigint" ? "integer" : parsedType2, - const: def.value + localeError: error59() }; } -var init_literal = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js -function parseStringDef(def, refs) { - const res = { type: "string" }; - if (def.checks) - for (const check2 of def.checks) - switch (check2.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check2.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check2.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check2.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check2.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check2.message, refs); - break; - case "regex": - addPattern(res, check2.regex, check2.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check2.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check2.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check2.message, refs); - break; - case "date": - addFormat(res, "date", check2.message, refs); - break; - case "time": - addFormat(res, "time", check2.message, refs); - break; - case "duration": - addFormat(res, "duration", check2.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); - break; - case "includes": - addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); - break; - case "ip": - if (check2.version !== "v6") - addFormat(res, "ipv4", check2.message, refs); - if (check2.version !== "v4") - addFormat(res, "ipv6", check2.message, refs); - break; - case "base64url": - addPattern(res, zodPatterns.base64url, check2.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check2.message, refs); - break; - case "cidr": - if (check2.version !== "v6") - addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); - if (check2.version !== "v4") - addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); - break; - case "emoji": - addPattern(res, zodPatterns.emoji(), check2.message, refs); - break; - case "ulid": - addPattern(res, zodPatterns.ulid, check2.message, refs); - break; - case "base64": - switch (refs.base64Strategy) { - case "format:binary": - addFormat(res, "binary", check2.message, refs); - break; - case "contentEncoding:base64": - setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.base64, check2.message, refs); - break; - } - break; - case "nanoid": - addPattern(res, zodPatterns.nanoid, check2.message, refs); - break; - case "toLowerCase": - case "toUpperCase": - case "trim": - break; - default: - ((_) => {})(check2); - } - return res; -} -function escapeLiteralCheckValue(literal2, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; -} -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0;i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) - result += "\\"; - result += source[i]; +var error59 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) - schema.anyOf = []; - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) - delete schema.errorMessage; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; } - } - schema.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else - setResponseValueAndErrors(schema, "format", value, message, refs); -} -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) - schema.allOf = []; - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) - delete schema.errorMessage; + case "object": { + if (Array.isArray(data)) { + return "arreglo"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype) { + return data.constructor.name; + } } } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else - setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); -} -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) - return regex.source; - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s") + return t; }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0;i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } else - pattern += `${source[i]}${source[i].toUpperCase()}`; - continue; + const Nouns = { + regex: "entrada", + email: "dirección de correo electrónico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duración ISO", + ipv4: "dirección IPv4", + ipv6: "dirección IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Entrada inválida: se esperaba ${issue3.expected}, recibido ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Entrada inválida: se esperaba ${stringifyPrimitive2(issue3.values[0])}`; + return `Opción inválida: se esperaba una de ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} fuera ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Demasiado pequeño: se esperaba que ${issue3.origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } - } else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; + return `Demasiado pequeño: se esperaba que ${issue3.origin} fuera ${adj}${issue3.minimum.toString()}`; } - } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r -]))`; - continue; - } else if (source[i] === "$") { - pattern += `($|(?=[\r -]))`; - continue; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inválida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inválida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; + return `Inválido ${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `Número inválido: debe ser múltiplo de ${issue3.divisor}`; + case "unrecognized_keys": + return `Llave${issue3.keys.length > 1 ? "s" : ""} desconocida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Llave inválida en ${issue3.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido en ${issue3.origin}`; + default: + return `Entrada inválida`; } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r -` : `[${source[i]}\r -]`; - continue; - } - pattern += source[i]; - if (source[i] === "\\") - isEscaped = true; - else if (inCharGroup && source[i] === "]") - inCharGroup = false; - else if (!inCharGroup && source[i] === "[") - inCharGroup = true; - } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} -var emojiRegex2 = undefined, zodPatterns, ALPHA_NUMERIC; -var init_string = __esm(() => { - init_errorMessages(); - zodPatterns = { - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - emoji: () => { - if (emojiRegex2 === undefined) - emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - return emojiRegex2; - }, - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; - ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +}; +var init_es2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js -function parseRecordDef(def, refs) { - if (refs.target === "openAi") - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - key - ] - }) ?? parseAnyDef(refs) - }), {}), - additionalProperties: refs.rejectedAdditionalProperties - }; - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? refs.allowedAdditionalProperties +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fa.js +function fa_default2() { + return { + localeError: error60() }; - if (refs.target === "openApi3") - return schema; - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) { - const { type, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) - return { - ...schema, - propertyNames: { enum: def.keyType._def.values } - }; - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) { - const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } - return schema; } -var init_record = __esm(() => { - init_any(); - init_branded(); - init_string(); - init_parseDef(); - init_v3(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") - return parseRecordDef(def, refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [parseDef(def.keyType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "0" - ] - }) || parseAnyDef(refs), parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "1" - ] - }) || parseAnyDef(refs)], - minItems: 2, - maxItems: 2 +var error60 = () => { + const Sizable = { + string: { unit: "کاراکتر", verb: "داشته باشد" }, + file: { unit: "بایت", verb: "داشته باشد" }, + array: { unit: "آیتم", verb: "داشته باشد" }, + set: { unit: "آیتم", verb: "داشته باشد" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "آرایه"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } + return t; }; -} -var init_map = __esm(() => { - init_any(); - init_record(); - init_parseDef(); + const Nouns = { + regex: "ورودی", + email: "آدرس ایمیل", + url: "URL", + emoji: "ایموجی", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاریخ و زمان ایزو", + date: "تاریخ ایزو", + time: "زمان ایزو", + duration: "مدت زمان ایزو", + ipv4: "IPv4 آدرس", + ipv6: "IPv6 آدرس", + cidrv4: "IPv4 دامنه", + cidrv6: "IPv6 دامنه", + base64: "base64-encoded رشته", + base64url: "base64url-encoded رشته", + json_string: "JSON رشته", + e164: "E.164 عدد", + jwt: "JWT", + template_literal: "ورودی" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `ورودی نامعتبر: می‌بایست ${issue3.expected} می‌بود، ${parsedType4(issue3.input)} دریافت شد`; + case "invalid_value": + if (issue3.values.length === 1) { + return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive2(issue3.values[0])} می‌بود`; + } + return `گزینه نامعتبر: می‌بایست یکی از ${joinValues2(issue3.values, "|")} می‌بود`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `خیلی بزرگ: ${issue3.origin ?? "مقدار"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; + } + return `خیلی بزرگ: ${issue3.origin ?? "مقدار"} باید ${adj}${issue3.maximum.toString()} باشد`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} باشد`; + } + return `خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} باشد`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; + } + if (_issue.format === "ends_with") { + return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; + } + if (_issue.format === "includes") { + return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; + } + if (_issue.format === "regex") { + return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; + } + return `${Nouns[_issue.format] ?? issue3.format} نامعتبر`; + } + case "not_multiple_of": + return `عدد نامعتبر: باید مضرب ${issue3.divisor} باشد`; + case "unrecognized_keys": + return `کلید${issue3.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `کلید ناشناس در ${issue3.origin}`; + case "invalid_union": + return `ورودی نامعتبر`; + case "invalid_element": + return `مقدار نامعتبر در ${issue3.origin}`; + default: + return `ورودی نامعتبر`; + } + }; +}; +var init_fa2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js -function parseNativeEnumDef(def) { - const object2 = def.values; - const actualValues = Object.keys(def.values).filter((key) => { - return typeof object2[object2[key]] !== "number"; - }).map((key) => object2[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fi.js +function fi_default2() { return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues + localeError: error61() }; } -var init_nativeEnum = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js -function parseNeverDef(refs) { - return refs.target === "openAi" ? undefined : { not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"] - }) }; -} -var init_never = __esm(() => { - init_any(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { type: "null" }; -} -var init_null = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => (x._def.typeName in primitiveMappings) && (!x._def.checks || !x._def.checks.length))) { - const types2 = options.reduce((types3, x) => { - const type = primitiveMappings[x._def.typeName]; - return type && !types3.includes(type) ? [...types3, type] : types3; - }, []); - return { type: types2.length > 1 ? types2 : types2[0] }; - } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types2 = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - return acc; - default: - return acc; +var error61 = () => { + const Sizable = { + string: { unit: "merkkiä", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "päivämäärän" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - }, []); - if (types2.length === options.length) { - const uniqueTypes = types2.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []) - }; } - } else if (options.every((x) => x._def.typeName === "ZodEnum")) - return { - type: "string", - enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], []) - }; - return asAnyOf(def, refs); -} -var primitiveMappings, asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - `${i}` - ] - })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); - return anyOf.length ? { anyOf } : undefined; -}; -var init_union = __esm(() => { - init_parseDef(); - primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" + return t; }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js -function parseNullableDef(def, refs) { - if ([ - "ZodString", - "ZodNumber", - "ZodBigInt", - "ZodBoolean", - "ZodNull" - ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; - } - if (refs.target === "openApi3") { - const base2 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base2 && "$ref" in base2) - return { - allOf: [base2], - nullable: true - }; - return base2 && { - ...base2, - nullable: true - }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "0" - ] - }); - return base && { anyOf: [base, { type: "null" }] }; -} -var init_nullable = __esm(() => { - init_union(); - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js -function parseNumberDef(def, refs) { - const res = { type: "number" }; - if (!def.checks) - return res; - for (const check2 of def.checks) - switch (check2.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check2.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") - if (check2.inclusive) - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - else - setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); - else { - if (!check2.inclusive) - res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + const Nouns = { + regex: "säännöllinen lauseke", + email: "sähköpostiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-päivämäärä", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Virheellinen tyyppi: odotettiin ${issue3.expected}, oli ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Virheellinen syöte: täytyy olla ${stringifyPrimitive2(issue3.values[0])}`; + return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim(); } - break; - case "max": - if (refs.target === "jsonSchema7") - if (check2.inclusive) - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); - else - setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); - else { - if (!check2.inclusive) - res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + return `Liian suuri: arvon täytyy olla ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim(); } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); - break; + return `Liian pieni: arvon täytyy olla ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: täytyy olla luvun ${issue3.divisor} monikerta`; + case "unrecognized_keys": + return `${issue3.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen syöte`; } - return res; -} -var init_number = __esm(() => { - init_errorMessages(); + }; +}; +var init_fi2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {} +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr.js +function fr_default2() { + return { + localeError: error62() }; - const required2 = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === undefined || propDef._def === undefined) - continue; - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") - propDef = propDef._def.innerType; - if (!propDef.isNullable()) - propDef = propDef.nullable(); - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - propName - ], - propertyPath: [ - ...refs.currentPath, - "properties", - propName - ] - }); - if (parsedDef === undefined) - continue; - result.properties[propName] = parsedDef; - if (!propOptional) - required2.push(propName); - } - if (required2.length) - result.required = required2; - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== undefined) - result.additionalProperties = additionalProperties; - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") - return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }); - switch (def.unknownKeys) { - case "passthrough": - return refs.allowedAdditionalProperties; - case "strict": - return refs.rejectedAdditionalProperties; - case "strip": - return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; - } } -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } catch { - return true; +var error62 = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } -} -var init_object = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js -var parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) - return parseDef(def.innerType._def, refs); - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "1" - ] - }); - return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); -}; -var init_optional = __esm(() => { - init_any(); - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js -var parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") - return parseDef(def.in._def, refs); - else if (refs.pipeStrategy === "output") - return parseDef(def.out._def, refs); - const a = parseDef(def.in._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }); - return { allOf: [a, parseDef(def.out._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - a ? "1" : "0" - ] - })].filter((x) => x !== undefined) }; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombre"; + } + case "object": { + if (Array.isArray(data)) { + return "tableau"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Entrée invalide : ${issue3.expected} attendu, ${parsedType4(issue3.input)} reçu`; + case "invalid_value": + if (issue3.values.length === 1) + return `Entrée invalide : ${stringifyPrimitive2(issue3.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues2(issue3.values, "|")} attendue`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Trop grand : ${issue3.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; + return `Trop grand : ${issue3.origin ?? "valeur"} doit être ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Trop petit : ${issue3.origin} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue3.origin} doit être ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue3.divisor}`; + case "unrecognized_keys": + return `Clé${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue3.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue3.origin}`; + default: + return `Entrée invalide`; + } + }; }; -var init_pipeline = __esm(() => { - init_parseDef(); +var init_fr2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr-CA.js +function fr_CA_default2() { + return { + localeError: error63() + }; } -var init_promise = __esm(() => { - init_parseDef(); +var error63 = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Entrée invalide : attendu ${issue3.expected}, reçu ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Entrée invalide : attendu ${stringifyPrimitive2(issue3.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "≤" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} soit ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? "≥" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue3.divisor}`; + case "unrecognized_keys": + return `Clé${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue3.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue3.origin}`; + default: + return `Entrée invalide`; + } + }; +}; +var init_fr_CA2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js -function parseSetDef(def, refs) { - const schema = { - type: "array", - uniqueItems: true, - items: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }) +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/he.js +function he_default2() { + return { + localeError: error64() }; - if (def.minSize) - setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - if (def.maxSize) - setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - return schema; } -var init_set = __esm(() => { - init_errorMessages(); - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js -function parseTupleDef(def, refs) { - if (def.rest) - return { - type: "array", - minItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - else - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []) - }; -} -var init_tuple = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js -function parseUndefinedDef(refs) { - return { not: parseAnyDef(refs) }; -} -var init_undefined = __esm(() => { - init_any(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} -var init_unknown = __esm(() => { - init_any(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js -var parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; -var init_readonly = __esm(() => { - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js -var selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind2.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind2.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind2.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind2.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind2.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind2.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind2.ZodUndefined: - return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind2.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind2.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind2.ZodUnion: - case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind2.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind2.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind2.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind2.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind2.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind2.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind2.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind2.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind2.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind2.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind2.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind2.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind2.ZodNaN: - case ZodFirstPartyTypeKind2.ZodNever: - return parseNeverDef(refs); - case ZodFirstPartyTypeKind2.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind2.ZodAny: - return parseAnyDef(refs); - case ZodFirstPartyTypeKind2.ZodUnknown: - return parseUnknownDef(refs); - case ZodFirstPartyTypeKind2.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind2.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind2.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind2.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind2.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind2.ZodFunction: - case ZodFirstPartyTypeKind2.ZodVoid: - case ZodFirstPartyTypeKind2.ZodSymbol: - return; - default: - return ((_) => { - return; - })(typeName); - } -}; -var init_selectParser = __esm(() => { - init_any(); - init_array(); - init_bigint(); - init_boolean(); - init_branded(); - init_catch(); - init_date(); - init_default(); - init_effects(); - init_enum(); - init_intersection(); - init_literal(); - init_string(); - init_record(); - init_map(); - init_nativeEnum(); - init_never(); - init_null(); - init_union(); - init_nullable(); - init_number(); - init_object(); - init_optional(); - init_pipeline(); - init_promise(); - init_set(); - init_tuple(); - init_undefined(); - init_unknown(); - init_readonly(); - init_v3(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) - return overrideResult; - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== undefined) - return seenSchema; - } - const newItem = { - def, - path: refs.currentPath, - jsonSchema: undefined +var error64 = () => { + const Sizable = { + string: { unit: "אותיות", verb: "לכלול" }, + file: { unit: "בייטים", verb: "לכלול" }, + array: { unit: "פריטים", verb: "לכלול" }, + set: { unit: "פריטים", verb: "לכלול" } }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; - if (jsonSchema) - addMeta(def, refs, jsonSchema); - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; + function getSizing(origin) { + return Sizable[origin] ?? null; } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -var get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": - if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; - } -}, addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) - jsonSchema.markdownDescription = def.description; - } - return jsonSchema; -}; -var init_parseDef = __esm(() => { - init_Options(); - init_getRelativePath(); - init_any(); - init_selectParser(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js -var zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ - ...acc, - [name2]: parseDef(schema2._def, { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name2 - ] - }, true) ?? parseAnyDef(refs) - }), {}) : undefined; - const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name; - const main = parseDef(schema._def, name === undefined ? refs : { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name - ] - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined; - if (title !== undefined) - main.title = title; - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) - definitions = {}; - if (!definitions[refs.openAiAnyTypeName]) - definitions[refs.openAiAnyTypeName] = { - type: [ - "string", - "number", - "integer", - "boolean", - "array", - "null" - ], - items: { $ref: refs.$refStrategy === "relative" ? "1" : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ].join("/") } - }; - } - const combined = name === undefined ? definitions ? { - ...main, - [refs.definitionPath]: definitions - } : main : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main + } + return t; + }; + const Nouns = { + regex: "קלט", + email: "כתובת אימייל", + url: "כתובת רשת", + emoji: "אימוג'י", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "תאריך וזמן ISO", + date: "תאריך ISO", + time: "זמן ISO", + duration: "משך זמן ISO", + ipv4: "כתובת IPv4", + ipv6: "כתובת IPv6", + cidrv4: "טווח IPv4", + cidrv6: "טווח IPv6", + base64: "מחרוזת בבסיס 64", + base64url: "מחרוזת בבסיס 64 לכתובות רשת", + json_string: "מחרוזת JSON", + e164: "מספר E.164", + jwt: "JWT", + template_literal: "קלט" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `קלט לא תקין: צריך ${issue3.expected}, התקבל ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `קלט לא תקין: צריך ${stringifyPrimitive2(issue3.values[0])}`; + return `קלט לא תקין: צריך אחת מהאפשרויות ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `גדול מדי: ${issue3.origin ?? "value"} צריך להיות ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `גדול מדי: ${issue3.origin ?? "value"} צריך להיות ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `מחרוזת לא תקינה: חייבת להתחיל ב"${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `מחרוזת לא תקינה: חייבת להסתיים ב "${_issue.suffix}"`; + if (_issue.format === "includes") + return `מחרוזת לא תקינה: חייבת לכלול "${_issue.includes}"`; + if (_issue.format === "regex") + return `מחרוזת לא תקינה: חייבת להתאים לתבנית ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} לא תקין`; + } + case "not_multiple_of": + return `מספר לא תקין: חייב להיות מכפלה של ${issue3.divisor}`; + case "unrecognized_keys": + return `מפתח${issue3.keys.length > 1 ? "ות" : ""} לא מזוה${issue3.keys.length > 1 ? "ים" : "ה"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `מפתח לא תקין ב${issue3.origin}`; + case "invalid_union": + return "קלט לא תקין"; + case "invalid_element": + return `ערך לא תקין ב${issue3.origin}`; + default: + return `קלט לא תקין`; } }; - if (refs.target === "jsonSchema7") - combined.$schema = "http://json-schema.org/draft-07/schema#"; - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - if (refs.target === "openAi" && (("anyOf" in combined) || ("oneOf" in combined) || ("allOf" in combined) || ("type" in combined) && Array.isArray(combined.type))) - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - return combined; }; -var init_zodToJsonSchema = __esm(() => { - init_Refs(); - init_any(); - init_parseDef(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js -var init_zod_to_json_schema = __esm(() => { - init_Options(); - init_Refs(); - init_errorMessages(); - init_getRelativePath(); - init_any(); - init_array(); - init_bigint(); - init_boolean(); - init_branded(); - init_catch(); - init_date(); - init_default(); - init_effects(); - init_enum(); - init_intersection(); - init_literal(); - init_string(); - init_record(); - init_map(); - init_nativeEnum(); - init_never(); - init_null(); - init_union(); - init_nullable(); - init_number(); - init_object(); - init_optional(); - init_pipeline(); - init_promise(); - init_set(); - init_tuple(); - init_undefined(); - init_unknown(); - init_readonly(); - init_selectParser(); - init_parseDef(); - init_zodToJsonSchema(); +var init_he2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deepCompareStrict(a, b) { - const typeofa = typeof a; - if (typeofa !== typeof b) { - return false; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/hu.js +function hu_default2() { + return { + localeError: error65() + }; +} +var error65 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - const length = a.length; - if (length !== b.length) { - return false; - } - for (let i = 0;i < length; i++) { - if (!deepCompareStrict(a[i], b[i])) { - return false; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "szám"; + } + case "object": { + if (Array.isArray(data)) { + return "tömb"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - return true; - } - if (typeofa === "object") { - if (!a || !b) { - return a === b; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; - } - for (const k of aKeys) { - if (!deepCompareStrict(a[k], b[k])) { - return false; + return t; + }; + const Nouns = { + regex: "bemenet", + email: "email cím", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO időbélyeg", + date: "ISO dátum", + time: "ISO idő", + duration: "ISO időintervallum", + ipv4: "IPv4 cím", + ipv6: "IPv6 cím", + cidrv4: "IPv4 tartomány", + cidrv6: "IPv6 tartomány", + base64: "base64-kódolt string", + base64url: "base64url-kódolt string", + json_string: "JSON string", + e164: "E.164 szám", + jwt: "JWT", + template_literal: "bemenet" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Érvénytelen bemenet: a várt érték ${issue3.expected}, a kapott érték ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive2(issue3.values[0])}`; + return `Érvénytelen opció: valamelyik érték várt ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Túl nagy: ${issue3.origin ?? "érték"} mérete túl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `Túl nagy: a bemeneti érték ${issue3.origin ?? "érték"} túl nagy: ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Túl kicsi: a bemeneti érték ${issue3.origin} mérete túl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Túl kicsi: a bemeneti érték ${issue3.origin} túl kicsi ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; + if (_issue.format === "ends_with") + return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; + if (_issue.format === "includes") + return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; + if (_issue.format === "regex") + return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; + return `Érvénytelen ${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `Érvénytelen szám: ${issue3.divisor} többszörösének kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Érvénytelen kulcs ${issue3.origin}`; + case "invalid_union": + return "Érvénytelen bemenet"; + case "invalid_element": + return `Érvénytelen érték: ${issue3.origin}`; + default: + return `Érvénytelen bemenet`; } - return true; - } - return a === b; -} + }; +}; +var init_hu2 = __esm(() => { + init_util2(); +}); -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js -function encodePointer(p) { - return encodeURI(escapePointer(p)); -} -function escapePointer(p) { - return p.replace(/~/g, "~0").replace(/\//g, "~1"); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/id.js +function id_default2() { + return { + localeError: error66() + }; } - -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js -function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = "") { - if (schema && typeof schema === "object" && !Array.isArray(schema)) { - const id = schema.$id || schema.id; - if (id) { - const url2 = new URL(id, baseURI.href); - if (url2.hash.length > 1) { - lookup[url2.href] = schema; - } else { - url2.hash = ""; - if (basePointer === "") { - baseURI = url2; - } else { - dereference(schema, lookup, baseURI); +var error66 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - } else if (schema !== true && schema !== false) { - return lookup; - } - const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : ""); - if (lookup[schemaURI] !== undefined) { - throw new Error(`Duplicate schema URI "${schemaURI}".`); - } - lookup[schemaURI] = schema; - if (schema === true || schema === false) { - return lookup; - } - if (schema.__absolute_uri__ === undefined) { - Object.defineProperty(schema, "__absolute_uri__", { - enumerable: false, - value: schemaURI - }); - } - if (schema.$ref && schema.__absolute_ref__ === undefined) { - const url2 = new URL(schema.$ref, baseURI.href); - url2.hash = url2.hash; - Object.defineProperty(schema, "__absolute_ref__", { - enumerable: false, - value: url2.href - }); - } - if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { - const url2 = new URL(schema.$recursiveRef, baseURI.href); - url2.hash = url2.hash; - Object.defineProperty(schema, "__absolute_recursive_ref__", { - enumerable: false, - value: url2.href - }); - } - if (schema.$anchor) { - const url2 = new URL("#" + schema.$anchor, baseURI.href); - lookup[url2.href] = schema; - } - for (let key in schema) { - if (ignoredKeyword[key]) { - continue; - } - const keyBase = `${basePointer}/${encodePointer(key)}`; - const subSchema = schema[key]; - if (Array.isArray(subSchema)) { - if (schemaArrayKeyword[key]) { - const length = subSchema.length; - for (let i = 0;i < length; i++) { - dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + return t; + }; + const Nouns = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Input tidak valid: diharapkan ${issue3.expected}, diterima ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive2(issue3.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} menjadi ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } + return `Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`; } - } else if (schemaMapKeyword[key]) { - for (let subKey in subSchema) { - dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} tidak valid`; } - } else { - dereference(subSchema, lookup, baseURI, keyBase); + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue3.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue3.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue3.origin}`; + default: + return `Input tidak valid`; } - } - return lookup; -} -var schemaArrayKeyword, schemaMapKeyword, ignoredKeyword, initialBaseURI; -var init_dereference = __esm(() => { - schemaArrayKeyword = { - prefixItems: true, - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - schemaMapKeyword = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependentSchemas: true - }; - ignoredKeyword = { - id: true, - $id: true, - $ref: true, - $schema: true, - $anchor: true, - $vocabulary: true, - $comment: true, - default: true, - enum: true, - const: true, - required: true, - type: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true }; - initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); +}; +var init_id2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js -function bind(r) { - return r.test.bind(r); -} -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function date5(str) { - const matches = str.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); -} -function time3(full, str) { - const matches = str.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second = +matches[3]; - const timeZone = !!matches[5]; - return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); -} -function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date5(dateTime[0]) && time3(true, dateTime[1]); -} -function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); -} -function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str, "u"); - return true; - } catch (e) { - return false; - } -} -var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split("@"); - if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) - return false; - if (name[0] === "." || name.endsWith(".") || name.includes("..")) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); -}, IPV4, IPV6, DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)), format, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR; -var init_format2 = __esm(() => { - DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; - HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; - URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; - URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; - UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; - JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; - JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; - RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; - IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; - IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; - format = { - date: date5, - time: time3.bind(undefined, false), - "date-time": date_time, - duration: DURATION, - uri, - "uri-reference": bind(URIREF), - "uri-template": bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex, - uuid: bind(UUID), - "json-pointer": bind(JSON_POINTER), - "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), - "relative-json-pointer": bind(RELATIVE_JSON_POINTER) +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/it.js +function it_default2() { + return { + localeError: error67() }; - DATE_TIME_SEPARATOR = /t|\s/i; - NOT_URI_FRAGMENT = /\/|:/; - URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - Z_ANCHOR = /[^\\]\\Z/; -}); - -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -var init_types2 = __esm(() => { - (function(OutputFormat2) { - OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag"; - OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic"; - OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed"; - })(OutputFormat || (OutputFormat = {})); -}); - -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js -function ucs2length(s) { - let result = 0; - let length = s.length; - let index = 0; - let charCode; - while (index < length) { - result++; - charCode = s.charCodeAt(index++); - if (charCode >= 55296 && charCode <= 56319 && index < length) { - charCode = s.charCodeAt(index); - if ((charCode & 64512) == 56320) { - index++; - } - } - } - return result; } - -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js -function validate4(instance, schema, draft = "2019-09", lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = Object.create(null)) { - if (schema === true) { - return { valid: true, errors: [] }; - } - if (schema === false) { - return { - valid: false, - errors: [ - { - instanceLocation, - keyword: "false", - keywordLocation: instanceLocation, - error: "False boolean schema." - } - ] - }; +var error67 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - const rawInstanceType = typeof instance; - let instanceType; - switch (rawInstanceType) { - case "boolean": - case "number": - case "string": - instanceType = rawInstanceType; - break; - case "object": - if (instance === null) { - instanceType = "null"; - } else if (Array.isArray(instance)) { - instanceType = "array"; - } else { - instanceType = "object"; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numero"; } - break; - default: - throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); - } - const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; - const errors4 = []; - if ($recursiveAnchor === true && recursiveAnchor === null) { - recursiveAnchor = schema; - } - if ($recursiveRef === "#") { - const refSchema = recursiveAnchor === null ? lookup[__absolute_recursive_ref__] : recursiveAnchor; - const keywordLocation = `${schemaLocation}/$recursiveRef`; - const result = validate4(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "$recursiveRef", - keywordLocation, - error: "A subschema had errors." - }, ...result.errors); - } - } - if ($ref !== undefined) { - const uri2 = __absolute_ref__ || $ref; - const refSchema = lookup[uri2]; - if (refSchema === undefined) { - let message = `Unresolved $ref "${$ref}".`; - if (__absolute_ref__ && __absolute_ref__ !== $ref) { - message += ` Absolute URI "${__absolute_ref__}".`; + case "object": { + if (Array.isArray(data)) { + return "vettore"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - message += ` -Known schemas: -- ${Object.keys(lookup).join(` -- `)}`; - throw new Error(message); - } - const keywordLocation = `${schemaLocation}/$ref`; - const result = validate4(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "$ref", - keywordLocation, - error: "A subschema had errors." - }, ...result.errors); - } - if (draft === "4" || draft === "7") { - return { valid: errors4.length === 0, errors: errors4 }; } - } - if (Array.isArray($type)) { - let length = $type.length; - let valid = false; - for (let i = 0;i < length; i++) { - if (instanceType === $type[i] || $type[i] === "integer" && instanceType === "number" && instance % 1 === 0 && instance === instance) { - valid = true; - break; + return t; + }; + const Nouns = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Input non valido: atteso ${issue3.expected}, ricevuto ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive2(issue3.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Troppo grande: ${issue3.origin ?? "valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue3.origin ?? "valore"} deve essere ${adj}${issue3.maximum.toString()}`; } - } - if (!valid) { - errors4.push({ - instanceLocation, - keyword: "type", - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` - }); - } - } else if ($type === "integer") { - if (instanceType !== "number" || instance % 1 || instance !== instance) { - errors4.push({ - instanceLocation, - keyword: "type", - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - } else if ($type !== undefined && instanceType !== $type) { - errors4.push({ - instanceLocation, - keyword: "type", - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - if ($const !== undefined) { - if (instanceType === "object" || instanceType === "array") { - if (!deepCompareStrict(instance, $const)) { - errors4.push({ - instanceLocation, - keyword: "const", - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`; } - } else if (instance !== $const) { - errors4.push({ - instanceLocation, - keyword: "const", - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - if ($enum !== undefined) { - if (instanceType === "object" || instanceType === "array") { - if (!$enum.some((value) => deepCompareStrict(instance, value))) { - errors4.push({ - instanceLocation, - keyword: "enum", - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; } - } else if (!$enum.some((value) => instance === value)) { - errors4.push({ - instanceLocation, - keyword: "enum", - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - if ($not !== undefined) { - const keywordLocation = `${schemaLocation}/not`; - const result = validate4(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); - if (result.valid) { - errors4.push({ - instanceLocation, - keyword: "not", - keywordLocation, - error: 'Instance matched "not" schema.' - }); + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue3.divisor}`; + case "unrecognized_keys": + return `Chiav${issue3.keys.length > 1 ? "i" : "e"} non riconosciut${issue3.keys.length > 1 ? "e" : "a"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue3.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue3.origin}`; + default: + return `Input non valido`; } + }; +}; +var init_it2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ja.js +function ja_default2() { + return { + localeError: error68() + }; +} +var error68 = () => { + const Sizable = { + string: { unit: "文字", verb: "である" }, + file: { unit: "バイト", verb: "である" }, + array: { unit: "要素", verb: "である" }, + set: { unit: "要素", verb: "である" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - let subEvaluateds = []; - if ($anyOf !== undefined) { - const keywordLocation = `${schemaLocation}/anyOf`; - const errorsLength = errors4.length; - let anyValid = false; - for (let i = 0;i < $anyOf.length; i++) { - const subSchema = $anyOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate4(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors4.push(...result.errors); - anyValid = anyValid || result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "数値"; } - } - if (anyValid) { - errors4.length = errorsLength; - } else { - errors4.splice(errorsLength, 0, { - instanceLocation, - keyword: "anyOf", - keywordLocation, - error: "Instance does not match any subschemas." - }); - } - } - if ($allOf !== undefined) { - const keywordLocation = `${schemaLocation}/allOf`; - const errorsLength = errors4.length; - let allValid = true; - for (let i = 0;i < $allOf.length; i++) { - const subSchema = $allOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate4(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors4.push(...result.errors); - allValid = allValid && result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); + case "object": { + if (Array.isArray(data)) { + return "配列"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - if (allValid) { - errors4.length = errorsLength; - } else { - errors4.splice(errorsLength, 0, { - instanceLocation, - keyword: "allOf", - keywordLocation, - error: `Instance does not match every subschema.` - }); - } - } - if ($oneOf !== undefined) { - const keywordLocation = `${schemaLocation}/oneOf`; - const errorsLength = errors4.length; - const matches = $oneOf.filter((subSchema, i) => { - const subEvaluated = Object.create(evaluated); - const result = validate4(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors4.push(...result.errors); - if (result.valid) { - subEvaluateds.push(subEvaluated); + return t; + }; + const Nouns = { + regex: "入力値", + email: "メールアドレス", + url: "URL", + emoji: "絵文字", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日時", + date: "ISO日付", + time: "ISO時刻", + duration: "ISO期間", + ipv4: "IPv4アドレス", + ipv6: "IPv6アドレス", + cidrv4: "IPv4範囲", + cidrv6: "IPv6範囲", + base64: "base64エンコード文字列", + base64url: "base64urlエンコード文字列", + json_string: "JSON文字列", + e164: "E.164番号", + jwt: "JWT", + template_literal: "入力値" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `無効な入力: ${issue3.expected}が期待されましたが、${parsedType4(issue3.input)}が入力されました`; + case "invalid_value": + if (issue3.values.length === 1) + return `無効な入力: ${stringifyPrimitive2(issue3.values[0])}が期待されました`; + return `無効な選択: ${joinValues2(issue3.values, "、")}のいずれかである必要があります`; + case "too_big": { + const adj = issue3.inclusive ? "以下である" : "より小さい"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `大きすぎる値: ${issue3.origin ?? "値"}は${issue3.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; + return `大きすぎる値: ${issue3.origin ?? "値"}は${issue3.maximum.toString()}${adj}必要があります`; } - return result.valid; - }).length; - if (matches === 1) { - errors4.length = errorsLength; - } else { - errors4.splice(errorsLength, 0, { - instanceLocation, - keyword: "oneOf", - keywordLocation, - error: `Instance does not match exactly one subschema (${matches} matches).` - }); - } - } - if (instanceType === "object" || instanceType === "array") { - Object.assign(evaluated, ...subEvaluateds); - } - if ($if !== undefined) { - const keywordLocation = `${schemaLocation}/if`; - const conditionResult = validate4(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; - if (conditionResult) { - if ($then !== undefined) { - const thenResult = validate4(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); - if (!thenResult.valid) { - errors4.push({ - instanceLocation, - keyword: "if", - keywordLocation, - error: `Instance does not match "then" schema.` - }, ...thenResult.errors); - } + case "too_small": { + const adj = issue3.inclusive ? "以上である" : "より大きい"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${sizing.unit}${adj}必要があります`; + return `小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${adj}必要があります`; } - } else if ($else !== undefined) { - const elseResult = validate4(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); - if (!elseResult.valid) { - errors4.push({ - instanceLocation, - keyword: "if", - keywordLocation, - error: `Instance does not match "else" schema.` - }, ...elseResult.errors); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; + if (_issue.format === "ends_with") + return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; + if (_issue.format === "includes") + return `無効な文字列: "${_issue.includes}"を含む必要があります`; + if (_issue.format === "regex") + return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; + return `無効な${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `無効な数値: ${issue3.divisor}の倍数である必要があります`; + case "unrecognized_keys": + return `認識されていないキー${issue3.keys.length > 1 ? "群" : ""}: ${joinValues2(issue3.keys, "、")}`; + case "invalid_key": + return `${issue3.origin}内の無効なキー`; + case "invalid_union": + return "無効な入力"; + case "invalid_element": + return `${issue3.origin}内の無効な値`; + default: + return `無効な入力`; } + }; +}; +var init_ja2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/kh.js +function kh_default2() { + return { + localeError: error69() + }; +} +var error69 = () => { + const Sizable = { + string: { unit: "តួអក្សរ", verb: "គួរមាន" }, + file: { unit: "បៃ", verb: "គួរមាន" }, + array: { unit: "ធាតុ", verb: "គួរមាន" }, + set: { unit: "ធាតុ", verb: "គួរមាន" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - if (instanceType === "object") { - if ($required !== undefined) { - for (const key of $required) { - if (!(key in instance)) { - errors4.push({ - instanceLocation, - keyword: "required", - keywordLocation: `${schemaLocation}/required`, - error: `Instance does not have required property "${key}".` - }); - } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; } - } - const keys = Object.keys(instance); - if ($minProperties !== undefined && keys.length < $minProperties) { - errors4.push({ - instanceLocation, - keyword: "minProperties", - keywordLocation: `${schemaLocation}/minProperties`, - error: `Instance does not have at least ${$minProperties} properties.` - }); - } - if ($maxProperties !== undefined && keys.length > $maxProperties) { - errors4.push({ - instanceLocation, - keyword: "maxProperties", - keywordLocation: `${schemaLocation}/maxProperties`, - error: `Instance does not have at least ${$maxProperties} properties.` - }); - } - if ($propertyNames !== undefined) { - const keywordLocation = `${schemaLocation}/propertyNames`; - for (const key in instance) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate4(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "propertyNames", - keywordLocation, - error: `Property name "${key}" does not match schema.` - }, ...result.errors); + case "object": { + if (Array.isArray(data)) { + return "អារេ (Array)"; } - } - } - if ($dependentRequired !== undefined) { - const keywordLocation = `${schemaLocation}/dependantRequired`; - for (const key in $dependentRequired) { - if (key in instance) { - const required2 = $dependentRequired[key]; - for (const dependantKey of required2) { - if (!(dependantKey in instance)) { - errors4.push({ - instanceLocation, - keyword: "dependentRequired", - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } + if (data === null) { + return "គ្មានតម្លៃ (null)"; } - } - } - if ($dependentSchemas !== undefined) { - for (const key in $dependentSchemas) { - const keywordLocation = `${schemaLocation}/dependentSchemas`; - if (key in instance) { - const result = validate4(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "dependentSchemas", - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - if ($dependencies !== undefined) { - const keywordLocation = `${schemaLocation}/dependencies`; - for (const key in $dependencies) { - if (key in instance) { - const propsOrSchema = $dependencies[key]; - if (Array.isArray(propsOrSchema)) { - for (const dependantKey of propsOrSchema) { - if (!(dependantKey in instance)) { - errors4.push({ - instanceLocation, - keyword: "dependencies", - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } else { - const result = validate4(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "dependencies", - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } + return t; + }; + const Nouns = { + regex: "ទិន្នន័យបញ្ចូល", + email: "អាសយដ្ឋានអ៊ីមែល", + url: "URL", + emoji: "សញ្ញាអារម្មណ៍", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", + date: "កាលបរិច្ឆេទ ISO", + time: "ម៉ោង ISO", + duration: "រយៈពេល ISO", + ipv4: "អាសយដ្ឋាន IPv4", + ipv6: "អាសយដ្ឋាន IPv6", + cidrv4: "ដែនអាសយដ្ឋាន IPv4", + cidrv6: "ដែនអាសយដ្ឋាន IPv6", + base64: "ខ្សែអក្សរអ៊ិកូដ base64", + base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", + json_string: "ខ្សែអក្សរ JSON", + e164: "លេខ E.164", + jwt: "JWT", + template_literal: "ទិន្នន័យបញ្ចូល" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue3.expected} ប៉ុន្តែទទួលបាន ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive2(issue3.values[0])}`; + return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `ធំពេក៖ ត្រូវការ ${issue3.origin ?? "តម្លៃ"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; + return `ធំពេក៖ ត្រូវការ ${issue3.origin ?? "តម្លៃ"} ${adj} ${issue3.maximum.toString()}`; } - } - const thisEvaluated = Object.create(null); - let stop = false; - if ($properties !== undefined) { - const keywordLocation = `${schemaLocation}/properties`; - for (const key in $properties) { - if (!(key in instance)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate4(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } else { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "properties", - keywordLocation, - error: `Property "${key}" does not match schema.` - }, ...result.errors); - if (stop) - break; + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; } + return `តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()}`; } - } - if (!stop && $patternProperties !== undefined) { - const keywordLocation = `${schemaLocation}/patternProperties`; - for (const pattern in $patternProperties) { - const regex2 = new RegExp(pattern, "u"); - const subSchema = $patternProperties[pattern]; - for (const key in instance) { - if (!regex2.test(key)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate4(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } else { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "patternProperties", - keywordLocation, - error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` - }, ...result.errors); - } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; } + if (_issue.format === "ends_with") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; + if (_issue.format === "regex") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; + return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue3.divisor}`; + case "unrecognized_keys": + return `រកឃើញសោមិនស្គាល់៖ ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`; + case "invalid_union": + return `ទិន្នន័យមិនត្រឹមត្រូវ`; + case "invalid_element": + return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`; + default: + return `ទិន្នន័យមិនត្រឹមត្រូវ`; } - if (!stop && $additionalProperties !== undefined) { - const keywordLocation = `${schemaLocation}/additionalProperties`; - for (const key in instance) { - if (thisEvaluated[key]) { - continue; + }; +}; +var init_kh2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ko.js +function ko_default2() { + return { + localeError: error70() + }; +} +var error70 = () => { + const Sizable = { + string: { unit: "문자", verb: "to have" }, + file: { unit: "바이트", verb: "to have" }, + array: { unit: "개", verb: "to have" }, + set: { unit: "개", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate4(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } else { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "additionalProperties", - keywordLocation, - error: `Property "${key}" does not match additional properties schema.` - }, ...result.errors); + if (data === null) { + return "null"; } - } - } else if (!stop && $unevaluatedProperties !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedProperties`; - for (const key in instance) { - if (!evaluated[key]) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate4(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } else { - errors4.push({ - instanceLocation, - keyword: "unevaluatedProperties", - keywordLocation, - error: `Property "${key}" does not match unevaluated properties schema.` - }, ...result.errors); - } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - } else if (instanceType === "array") { - if ($maxItems !== undefined && instance.length > $maxItems) { - errors4.push({ - instanceLocation, - keyword: "maxItems", - keywordLocation: `${schemaLocation}/maxItems`, - error: `Array has too many items (${instance.length} > ${$maxItems}).` - }); - } - if ($minItems !== undefined && instance.length < $minItems) { - errors4.push({ - instanceLocation, - keyword: "minItems", - keywordLocation: `${schemaLocation}/minItems`, - error: `Array has too few items (${instance.length} < ${$minItems}).` - }); - } - const length = instance.length; - let i = 0; - let stop = false; - if ($prefixItems !== undefined) { - const keywordLocation = `${schemaLocation}/prefixItems`; - const length2 = Math.min($prefixItems.length, length); - for (;i < length2; i++) { - const result = validate4(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "prefixItems", - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } + return t; + }; + const Nouns = { + regex: "입력", + email: "이메일 주소", + url: "URL", + emoji: "이모지", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 날짜시간", + date: "ISO 날짜", + time: "ISO 시간", + duration: "ISO 기간", + ipv4: "IPv4 주소", + ipv6: "IPv6 주소", + cidrv4: "IPv4 범위", + cidrv6: "IPv6 범위", + base64: "base64 인코딩 문자열", + base64url: "base64url 인코딩 문자열", + json_string: "JSON 문자열", + e164: "E.164 번호", + jwt: "JWT", + template_literal: "입력" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `잘못된 입력: 예상 타입은 ${issue3.expected}, 받은 타입은 ${parsedType4(issue3.input)}입니다`; + case "invalid_value": + if (issue3.values.length === 1) + return `잘못된 입력: 값은 ${stringifyPrimitive2(issue3.values[0])} 이어야 합니다`; + return `잘못된 옵션: ${joinValues2(issue3.values, "또는 ")} 중 하나여야 합니다`; + case "too_big": { + const adj = issue3.inclusive ? "이하" : "미만"; + const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue3.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) + return `${issue3.origin ?? "값"}이 너무 큽니다: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue3.origin ?? "값"}이 너무 큽니다: ${issue3.maximum.toString()} ${adj}${suffix}`; } - } - if ($items !== undefined) { - const keywordLocation = `${schemaLocation}/items`; - if (Array.isArray($items)) { - const length2 = Math.min($items.length, length); - for (;i < length2; i++) { - const result = validate4(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "items", - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } else { - for (;i < length; i++) { - const result = validate4(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "items", - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } + case "too_small": { + const adj = issue3.inclusive ? "이상" : "초과"; + const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue3.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) { + return `${issue3.origin ?? "값"}이 너무 작습니다: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`; } + return `${issue3.origin ?? "값"}이 너무 작습니다: ${issue3.minimum.toString()} ${adj}${suffix}`; } - if (!stop && $additionalItems !== undefined) { - const keywordLocation2 = `${schemaLocation}/additionalItems`; - for (;i < length; i++) { - const result = validate4(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation2); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors4.push({ - instanceLocation, - keyword: "additionalItems", - keywordLocation: keywordLocation2, - error: `Items did not match additional items schema.` - }, ...result.errors); - } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; } + if (_issue.format === "ends_with") + return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; + if (_issue.format === "includes") + return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; + if (_issue.format === "regex") + return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; + return `잘못된 ${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `잘못된 숫자: ${issue3.divisor}의 배수여야 합니다`; + case "unrecognized_keys": + return `인식할 수 없는 키: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `잘못된 키: ${issue3.origin}`; + case "invalid_union": + return `잘못된 입력`; + case "invalid_element": + return `잘못된 값: ${issue3.origin}`; + default: + return `잘못된 입력`; } - if ($contains !== undefined) { - if (length === 0 && $minContains === undefined) { - errors4.push({ - instanceLocation, - keyword: "contains", - keywordLocation: `${schemaLocation}/contains`, - error: `Array is empty. It must contain at least one item matching the schema.` - }); - } else if ($minContains !== undefined && length < $minContains) { - errors4.push({ - instanceLocation, - keyword: "minContains", - keywordLocation: `${schemaLocation}/minContains`, - error: `Array has less items (${length}) than minContains (${$minContains}).` - }); - } else { - const keywordLocation = `${schemaLocation}/contains`; - const errorsLength = errors4.length; - let contained = 0; - for (let j = 0;j < length; j++) { - const result = validate4(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); - if (result.valid) { - evaluated[j] = true; - contained++; - } else { - errors4.push(...result.errors); - } + }; +}; +var init_ko2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/mk.js +function mk_default2() { + return { + localeError: error71() + }; +} +var error71 = () => { + const Sizable = { + string: { unit: "знаци", verb: "да имаат" }, + file: { unit: "бајти", verb: "да имаат" }, + array: { unit: "ставки", verb: "да имаат" }, + set: { unit: "ставки", verb: "да имаат" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "број"; + } + case "object": { + if (Array.isArray(data)) { + return "низа"; } - if (contained >= ($minContains || 0)) { - errors4.length = errorsLength; + if (data === null) { + return "null"; } - if ($minContains === undefined && $maxContains === undefined && contained === 0) { - errors4.splice(errorsLength, 0, { - instanceLocation, - keyword: "contains", - keywordLocation, - error: `Array does not contain item matching schema.` - }); - } else if ($minContains !== undefined && contained < $minContains) { - errors4.push({ - instanceLocation, - keyword: "minContains", - keywordLocation: `${schemaLocation}/minContains`, - error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` - }); - } else if ($maxContains !== undefined && contained > $maxContains) { - errors4.push({ - instanceLocation, - keyword: "maxContains", - keywordLocation: `${schemaLocation}/maxContains`, - error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` - }); + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - if (!stop && $unevaluatedItems !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedItems`; - for (i;i < length; i++) { - if (evaluated[i]) { - continue; + return t; + }; + const Nouns = { + regex: "внес", + email: "адреса на е-пошта", + url: "URL", + emoji: "емоџи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO датум и време", + date: "ISO датум", + time: "ISO време", + duration: "ISO времетраење", + ipv4: "IPv4 адреса", + ipv6: "IPv6 адреса", + cidrv4: "IPv4 опсег", + cidrv6: "IPv6 опсег", + base64: "base64-енкодирана низа", + base64url: "base64url-енкодирана низа", + json_string: "JSON низа", + e164: "E.164 број", + jwt: "JWT", + template_literal: "внес" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Грешен внес: се очекува ${issue3.expected}, примено ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; + return `Грешана опција: се очекува една ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Премногу голем: се очекува ${issue3.origin ?? "вредноста"} да има ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "елементи"}`; + return `Премногу голем: се очекува ${issue3.origin ?? "вредноста"} да биде ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Премногу мал: се очекува ${issue3.origin} да има ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } - const result = validate4(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - errors4.push({ - instanceLocation, - keyword: "unevaluatedItems", - keywordLocation, - error: `Items did not match unevaluated items schema.` - }, ...result.errors); + return `Премногу мал: се очекува ${issue3.origin} да биде ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; } + if (_issue.format === "ends_with") + return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неважечка низа: мора да вклучува "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; } + case "not_multiple_of": + return `Грешен број: мора да биде делив со ${issue3.divisor}`; + case "unrecognized_keys": + return `${issue3.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Грешен клуч во ${issue3.origin}`; + case "invalid_union": + return "Грешен внес"; + case "invalid_element": + return `Грешна вредност во ${issue3.origin}`; + default: + return `Грешен внес`; } - if ($uniqueItems) { - for (let j = 0;j < length; j++) { - const a = instance[j]; - const ao = typeof a === "object" && a !== null; - for (let k = 0;k < length; k++) { - if (j === k) { - continue; - } - const b = instance[k]; - const bo = typeof b === "object" && b !== null; - if (a === b || ao && bo && deepCompareStrict(a, b)) { - errors4.push({ - instanceLocation, - keyword: "uniqueItems", - keywordLocation: `${schemaLocation}/uniqueItems`, - error: `Duplicate items at indexes ${j} and ${k}.` - }); - j = Number.MAX_SAFE_INTEGER; - k = Number.MAX_SAFE_INTEGER; - } + }; +}; +var init_mk2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ms.js +function ms_default2() { + return { + localeError: error72() + }; +} +var error72 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombor"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } } - } else if (instanceType === "number") { - if (draft === "4") { - if ($minimum !== undefined && ($exclusiveMinimum === true && instance <= $minimum || instance < $minimum)) { - errors4.push({ - instanceLocation, - keyword: "minimum", - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$exclusiveMinimum ? "or equal to " : ""} ${$minimum}.` - }); - } - if ($maximum !== undefined && ($exclusiveMaximum === true && instance >= $maximum || instance > $maximum)) { - errors4.push({ - instanceLocation, - keyword: "maximum", - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$exclusiveMaximum ? "or equal to " : ""} ${$maximum}.` - }); + return t; + }; + const Nouns = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Input tidak sah: dijangka ${issue3.expected}, diterima ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive2(issue3.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} adalah ${adj}${issue3.maximum.toString()}`; } - } else { - if ($minimum !== undefined && instance < $minimum) { - errors4.push({ - instanceLocation, - keyword: "minimum", - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$minimum}.` - }); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`; } - if ($maximum !== undefined && instance > $maximum) { - errors4.push({ - instanceLocation, - keyword: "maximum", - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$maximum}.` - }); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} tidak sah`; } - if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { - errors4.push({ - instanceLocation, - keyword: "exclusiveMinimum", - keywordLocation: `${schemaLocation}/exclusiveMinimum`, - error: `${instance} is less than ${$exclusiveMinimum}.` - }); + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue3.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue3.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue3.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +var init_ms2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/nl.js +function nl_default2() { + return { + localeError: error73() + }; +} +var error73 = () => { + const Sizable = { + string: { unit: "tekens" }, + file: { unit: "bytes" }, + array: { unit: "elementen" }, + set: { unit: "elementen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "getal"; } - if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { - errors4.push({ - instanceLocation, - keyword: "exclusiveMaximum", - keywordLocation: `${schemaLocation}/exclusiveMaximum`, - error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` - }); + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - if ($multipleOf !== undefined) { - const remainder = instance % $multipleOf; - if (Math.abs(0 - remainder) >= 0.00000011920929 && Math.abs($multipleOf - remainder) >= 0.00000011920929) { - errors4.push({ - instanceLocation, - keyword: "multipleOf", - keywordLocation: `${schemaLocation}/multipleOf`, - error: `${instance} is not a multiple of ${$multipleOf}.` - }); + return t; + }; + const Nouns = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Ongeldige invoer: verwacht ${issue3.expected}, ontving ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive2(issue3.values[0])}`; + return `Ongeldige optie: verwacht één van ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; + return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} is`; } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} bevat`; + } + return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue3.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue3.origin}`; + default: + return `Ongeldige invoer`; } - } else if (instanceType === "string") { - const length = $minLength === undefined && $maxLength === undefined ? 0 : ucs2length(instance); - if ($minLength !== undefined && length < $minLength) { - errors4.push({ - instanceLocation, - keyword: "minLength", - keywordLocation: `${schemaLocation}/minLength`, - error: `String is too short (${length} < ${$minLength}).` - }); - } - if ($maxLength !== undefined && length > $maxLength) { - errors4.push({ - instanceLocation, - keyword: "maxLength", - keywordLocation: `${schemaLocation}/maxLength`, - error: `String is too long (${length} > ${$maxLength}).` - }); - } - if ($pattern !== undefined && !new RegExp($pattern, "u").test(instance)) { - errors4.push({ - instanceLocation, - keyword: "pattern", - keywordLocation: `${schemaLocation}/pattern`, - error: `String does not match pattern.` - }); - } - if ($format !== undefined && format[$format] && !format[$format](instance)) { - errors4.push({ - instanceLocation, - keyword: "format", - keywordLocation: `${schemaLocation}/format`, - error: `String does not match format "${$format}".` - }); - } - } - return { valid: errors4.length === 0, errors: errors4 }; -} -var init_validate3 = __esm(() => { - init_dereference(); - init_format2(); + }; +}; +var init_nl2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validator.js -class Validator { - schema; - draft; - shortCircuit; - lookup; - constructor(schema, draft = "2019-09", shortCircuit = true) { - this.schema = schema; - this.draft = draft; - this.shortCircuit = shortCircuit; - this.lookup = dereference(schema); - } - validate(instance) { - return validate4(instance, this.schema, this.draft, this.lookup, this.shortCircuit); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/no.js +function no_default2() { + return { + localeError: error74() + }; +} +var error74 = () => { + const Sizable = { + string: { unit: "tegn", verb: "å ha" }, + file: { unit: "bytes", verb: "å ha" }, + array: { unit: "elementer", verb: "å inneholde" }, + set: { unit: "elementer", verb: "å inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - addSchema(schema, id) { - if (id) { - schema = { ...schema, $id: id }; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tall"; + } + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - dereference(schema, this.lookup); - } -} -var init_validator = __esm(() => { - init_dereference(); - init_validate3(); -}); - -// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/index.js -var init_esm = __esm(() => { - init_dereference(); - init_format2(); - init_types2(); - init_validate3(); - init_validator(); + return t; + }; + const Nouns = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-område", + ipv6: "IPv6-område", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Ugyldig input: forventet ${issue3.expected}, fikk ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive2(issue3.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `For stor(t): forventet ${issue3.origin ?? "value"} til å ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue3.origin ?? "value"} til å ha ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Ugyldig streng: må starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: må ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: må inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: må være et multiplum av ${issue3.divisor}`; + case "unrecognized_keys": + return `${issue3.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Ugyldig nøkkel i ${issue3.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue3.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +var init_no2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/json_schema.js -function toJsonSchema(schema, params) { - const canCache = !params && schema != null && typeof schema === "object"; - if (canCache) { - const cached2 = _jsonSchemaCache.get(schema); - if (cached2) - return cached2; - } - let result; - if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) - result = schema["~standard"].jsonSchema.input({ target: "draft-07" }); - else if (isZodSchemaV4(schema)) { - const inputSchema = interopZodTransformInputSchema(schema, true); - if (isZodObjectV4(inputSchema)) - result = toJSONSchema(interopZodObjectStrict(inputSchema, true), params); - else - result = toJSONSchema(schema, params); - } else if (isZodSchemaV3(schema)) - result = zodToJsonSchema(schema); - else - result = schema; - if (canCache && result != null && typeof result === "object") - _jsonSchemaCache.set(schema, result); - return result; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ota.js +function ota_default2() { + return { + localeError: error75() + }; } -function validatesOnlyStrings(schema) { - if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) - return false; - if ("type" in schema) { - if (typeof schema.type === "string") - return schema.type === "string"; - if (Array.isArray(schema.type)) - return schema.type.every((t) => t === "string"); - return false; - } - if ("enum" in schema) - return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); - if ("const" in schema) - return typeof schema.const === "string"; - if ("allOf" in schema && Array.isArray(schema.allOf)) - return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); - if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { - const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; - return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); - } - if ("not" in schema) - return false; - if ("$ref" in schema && typeof schema.$ref === "string") { - const ref = schema.$ref; - const resolved = dereference(schema); - if (resolved[ref]) - return validatesOnlyStrings(resolved[ref]); - return false; +var error75 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "unsur", verb: "olmalıdır" }, + set: { unit: "unsur", verb: "olmalıdır" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return false; -} -var json_schema_exports, _jsonSchemaCache; -var init_json_schema2 = __esm(() => { - init_runtime2(); - init_zod2(); - init_zodToJsonSchema(); - init_zod_to_json_schema(); - init_standard_schema(); - init_core2(); - init_esm(); - json_schema_exports = /* @__PURE__ */ __exportAll({ - Validator: () => Validator, - deepCompareStrict: () => deepCompareStrict, - toJsonSchema: () => toJsonSchema, - validatesOnlyStrings: () => validatesOnlyStrings - }); - _jsonSchemaCache = /* @__PURE__ */ new WeakMap; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numara"; + } + case "object": { + if (Array.isArray(data)) { + return "saf"; + } + if (data === null) { + return "gayb"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "giren", + email: "epostagâh", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO hengâmı", + date: "ISO tarihi", + time: "ISO zamanı", + duration: "ISO müddeti", + ipv4: "IPv4 nişânı", + ipv6: "IPv6 nişânı", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-şifreli metin", + base64url: "base64url-şifreli metin", + json_string: "JSON metin", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "giren" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Fâsit giren: umulan ${issue3.expected}, alınan ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Fâsit giren: umulan ${stringifyPrimitive2(issue3.values[0])}`; + return `Fâsit tercih: mûteberler ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Fazla büyük: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; + return `Fazla büyük: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} olmalıydı.`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; + } + return `Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmalıydı.`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; + if (_issue.format === "ends_with") + return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; + if (_issue.format === "regex") + return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; + return `Fâsit ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Fâsit sayı: ${issue3.divisor} katı olmalıydı.`; + case "unrecognized_keys": + return `Tanınmayan anahtar ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `${issue3.origin} için tanınmayan anahtar var.`; + case "invalid_union": + return "Giren tanınamadı."; + case "invalid_element": + return `${issue3.origin} için tanınmayan kıymet var.`; + default: + return `Kıymet tanınamadı.`; + } + }; +}; +var init_ota2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -function hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys2 = new Array(obj.length); - for (let k = 0;k < keys2.length; k++) - keys2[k] = "" + k; - return keys2; - } - if (Object.keys) - return Object.keys(obj); - let keys = []; - for (let i in obj) - if (hasOwnProperty(obj, i)) - keys.push(i); - return keys; -} -function _deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); - case "undefined": - return null; - default: - return obj; - } +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ps.js +function ps_default2() { + return { + localeError: error76() + }; } -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; +var error76 = () => { + const Sizable = { + string: { unit: "توکي", verb: "ولري" }, + file: { unit: "بایټس", verb: "ولري" }, + array: { unit: "توکي", verb: "ولري" }, + set: { unit: "توکي", verb: "ولري" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return true; -} -function escapePathComponent(path2) { - if (path2.indexOf("/") === -1 && path2.indexOf("~") === -1) - return path2; - return path2.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function unescapePathComponent(path2) { - return path2.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function hasUndefined(obj) { - if (obj === undefined) - return true; - if (obj) { - if (Array.isArray(obj)) { - for (let i2 = 0, len = obj.length;i2 < len; i2++) - if (hasUndefined(obj[i2])) - return true; - } else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0;i < objKeysLength; i++) - if (hasUndefined(obj[objKeys[i]])) - return true; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "ارې"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; - if (typeof value !== "undefined") - messageParts.push(`${key}: ${value}`); - } - return messageParts.join(` -`); -} -var _hasOwnProperty, PatchError; -var init_helpers = __esm(() => { - /*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */ - _hasOwnProperty = Object.prototype.hasOwnProperty; - PatchError = class extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - })); - this.name = name; - this.index = index; - this.operation = operation; - this.tree = tree; - Object.setPrototypeOf(this, new.target.prototype); - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - }); + return t; + }; + const Nouns = { + regex: "ورودي", + email: "بریښنالیک", + url: "یو آر ال", + emoji: "ایموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "نیټه او وخت", + date: "نېټه", + time: "وخت", + duration: "موده", + ipv4: "د IPv4 پته", + ipv6: "د IPv6 پته", + cidrv4: "د IPv4 ساحه", + cidrv6: "د IPv6 ساحه", + base64: "base64-encoded متن", + base64url: "base64url-encoded متن", + json_string: "JSON متن", + e164: "د E.164 شمېره", + jwt: "JWT", + template_literal: "ورودي" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `ناسم ورودي: باید ${issue3.expected} وای, مګر ${parsedType4(issue3.input)} ترلاسه شو`; + case "invalid_value": + if (issue3.values.length === 1) { + return `ناسم ورودي: باید ${stringifyPrimitive2(issue3.values[0])} وای`; + } + return `ناسم انتخاب: باید یو له ${joinValues2(issue3.values, "|")} څخه وای`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `ډیر لوی: ${issue3.origin ?? "ارزښت"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; + } + return `ډیر لوی: ${issue3.origin ?? "ارزښت"} باید ${adj}${issue3.maximum.toString()} وي`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} ولري`; + } + return `ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} وي`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; + } + if (_issue.format === "ends_with") { + return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; + } + if (_issue.format === "includes") { + return `ناسم متن: باید "${_issue.includes}" ولري`; + } + if (_issue.format === "regex") { + return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; + } + return `${Nouns[_issue.format] ?? issue3.format} ناسم دی`; + } + case "not_multiple_of": + return `ناسم عدد: باید د ${issue3.divisor} مضرب وي`; + case "unrecognized_keys": + return `ناسم ${issue3.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `ناسم کلیډ په ${issue3.origin} کې`; + case "invalid_union": + return `ناسمه ورودي`; + case "invalid_element": + return `ناسم عنصر په ${issue3.origin} کې`; + default: + return `ناسمه ورودي`; } }; +}; +var init_ps2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -function getValueByPointer(document2, pointer2) { - if (pointer2 == "") - return document2; - var getOriginalDestination = { - op: "_get", - path: pointer2 +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pl.js +function pl_default2() { + return { + localeError: error77() }; - applyOperation(document2, getOriginalDestination); - return getOriginalDestination.value; } -function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) - if (typeof validateOperation == "function") - validateOperation(operation, 0, document2, operation.path); - else - validator2(operation, 0); - if (operation.path === "") { - let returnValue = { newDocument: document2 }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document2; - return returnValue; - } else if (operation.op === "move" || operation.op === "copy") { - returnValue.newDocument = getValueByPointer(document2, operation.from); - if (operation.op === "move") - returnValue.removed = document2; - return returnValue; - } else if (operation.op === "test") { - returnValue.test = _areEquals(document2, operation.value); - if (returnValue.test === false) - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); - returnValue.newDocument = document2; - return returnValue; - } else if (operation.op === "remove") { - returnValue.removed = document2; - returnValue.newDocument = null; - return returnValue; - } else if (operation.op === "_get") { - operation.value = document2; - return returnValue; - } else if (validateOperation) - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document2); - else - return returnValue; - } else { - if (!mutateDocument) - document2 = _deepClone(document2); - const keys = (operation.path || "").split("/"); - let obj = document2; - let t = 1; - let len = keys.length; - let existingPathFragment = undefined; - let key; - let validateFunction; - if (typeof validateOperation == "function") - validateFunction = validateOperation; - else - validateFunction = validator2; - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) - key = unescapePathComponent(key); - if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) - existingPathFragment = keys.slice(0, t).join("/"); - else if (t == len - 1) - existingPathFragment = operation.path; - if (existingPathFragment !== undefined) - validateFunction(operation, 0, document2, existingPathFragment); +var error77 = () => { + const Sizable = { + string: { unit: "znaków", verb: "mieć" }, + file: { unit: "bajtów", verb: "mieć" }, + array: { unit: "elementów", verb: "mieć" }, + set: { unit: "elementów", verb: "mieć" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "liczba"; + } + case "object": { + if (Array.isArray(data)) { + return "tablica"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } } - t++; - if (Array.isArray(obj)) { - if (key === "-") - key = obj.length; - else if (validateOperation && !isInteger(key)) - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document2); - else if (isInteger(key)) - key = ~~key; - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document2); - const returnValue = arrOps[operation.op].call(operation, obj, key, document2); - if (returnValue.test === false) - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); - return returnValue; + } + return t; + }; + const Nouns = { + regex: "wyrażenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ciąg znaków zakodowany w formacie base64", + base64url: "ciąg znaków zakodowany w formacie base64url", + json_string: "ciąg znaków w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wejście" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Nieprawidłowe dane wejściowe: oczekiwano ${issue3.expected}, otrzymano ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive2(issue3.values[0])}`; + return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Za duża wartość: oczekiwano, że ${issue3.origin ?? "wartość"} będzie mieć ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementów"}`; } - } else if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document2); - if (returnValue.test === false) - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); - return returnValue; + return `Zbyt duż(y/a/e): oczekiwano, że ${issue3.origin ?? "wartość"} będzie wynosić ${adj}${issue3.maximum.toString()}`; } - obj = obj[key]; - if (validateOperation && t < len && (!obj || typeof obj !== "object")) - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document2); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Za mała wartość: oczekiwano, że ${issue3.origin ?? "wartość"} będzie mieć ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt mał(y/a/e): oczekiwano, że ${issue3.origin ?? "wartość"} będzie wynosić ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; + return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Nieprawidłowa liczba: musi być wielokrotnością ${issue3.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Nieprawidłowy klucz w ${issue3.origin}`; + case "invalid_union": + return "Nieprawidłowe dane wejściowe"; + case "invalid_element": + return `Nieprawidłowa wartość w ${issue3.origin}`; + default: + return `Nieprawidłowe dane wejściowe`; } - } -} -function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (!mutateDocument) - document2 = _deepClone(document2); - const results = new Array(patch.length); - for (let i = 0, length = patch.length;i < length; i++) { - results[i] = applyOperation(document2, patch[i], validateOperation, true, banPrototypeModifications, i); - document2 = results[i].newDocument; - } - results.newDocument = document2; - return results; -} -function applyReducer(document2, operation, index) { - const operationResult = applyOperation(document2, operation); - if (operationResult.test === false) - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); - return operationResult.newDocument; -} -function validator2(operation, index, document2, existingPathFragment) { - if (typeof operation !== "object" || operation === null || Array.isArray(operation)) - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document2); - else if (!objOps[operation.op]) - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document2); - else if (typeof operation.path !== "string") - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document2); - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document2); - else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document2); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === undefined) - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document2); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document2); - else if (document2) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document2); - } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { - if (operation.path !== existingPathFragment) - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document2); - } else if (operation.op === "move" || operation.op === "copy") { - var error51 = validate6([{ - op: "_get", - path: operation.from, - value: undefined - }], document2); - if (error51 && error51.name === "OPERATION_PATH_UNRESOLVABLE") - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document2); - } - } + }; +}; +var init_pl2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pt.js +function pt_default2() { + return { + localeError: error78() + }; } -function validate6(sequence, document2, externalValidator) { - try { - if (!Array.isArray(sequence)) - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - if (document2) - applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); - else { - externalValidator = externalValidator || validator2; - for (var i = 0;i < sequence.length; i++) - externalValidator(sequence[i], i, document2, undefined); - } - } catch (e) { - if (e instanceof JsonPatchError) - return e; - else - throw e; +var error78 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } -} -function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length;i-- !== 0; ) - if (!_areEquals(a[i], b[i])) - return false; - return true; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length;i-- !== 0; ) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length;i-- !== 0; ) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; + return t; + }; + const Nouns = { + regex: "padrão", + email: "endereço de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "duração ISO", + ipv4: "endereço IPv4", + ipv6: "endereço IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Tipo inválido: esperado ${issue3.expected}, recebido ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Entrada inválida: esperado ${stringifyPrimitive2(issue3.values[0])}`; + return `Opção inválida: esperada uma das ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Muito grande: esperado que ${issue3.origin ?? "valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue3.origin ?? "valor"} fosse ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Texto inválido: deve começar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inválido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inválido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} inválido`; + } + case "not_multiple_of": + return `Número inválido: deve ser múltiplo de ${issue3.divisor}`; + case "unrecognized_keys": + return `Chave${issue3.keys.length > 1 ? "s" : ""} desconhecida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Chave inválida em ${issue3.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido em ${issue3.origin}`; + default: + return `Campo inválido`; } - return true; + }; +}; +var init_pt2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ru.js +function getRussianPlural2(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; } - return a !== a && b !== b; + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; } -var core_exports, JsonPatchError, deepClone, objOps, arrOps; -var init_core3 = __esm(() => { - init_runtime2(); - init_helpers(); - core_exports = /* @__PURE__ */ __exportAll({ - JsonPatchError: () => JsonPatchError, - _areEquals: () => _areEquals, - applyOperation: () => applyOperation, - applyPatch: () => applyPatch, - applyReducer: () => applyReducer, - deepClone: () => deepClone, - getValueByPointer: () => getValueByPointer, - validate: () => validate6, - validator: () => validator2 - }); - JsonPatchError = PatchError; - deepClone = _deepClone; - objOps = { - add: function(obj, key, document2) { - if (key === "__proto__" || key === "constructor") - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); - obj[key] = this.value; - return { newDocument: document2 }; - }, - remove: function(obj, key, document2) { - if (key === "__proto__" || key === "constructor") - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); - var removed = obj[key]; - delete obj[key]; - return { - newDocument: document2, - removed - }; - }, - replace: function(obj, key, document2) { - if (key === "__proto__" || key === "constructor") - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); - var removed = obj[key]; - obj[key] = this.value; - return { - newDocument: document2, - removed - }; - }, - move: function(obj, key, document2) { - let removed = getValueByPointer(document2, this.path); - if (removed) - removed = _deepClone(removed); - const originalValue = applyOperation(document2, { - op: "remove", - path: this.from - }).removed; - applyOperation(document2, { - op: "add", - path: this.path, - value: originalValue - }); - return { - newDocument: document2, - removed - }; +function ru_default2() { + return { + localeError: error79() + }; +} +var error79 = () => { + const Sizable = { + string: { + unit: { + one: "символ", + few: "символа", + many: "символов" + }, + verb: "иметь" }, - copy: function(obj, key, document2) { - const valueToCopy = getValueByPointer(document2, this.from); - applyOperation(document2, { - op: "add", - path: this.path, - value: _deepClone(valueToCopy) - }); - return { newDocument: document2 }; + file: { + unit: { + one: "байт", + few: "байта", + many: "байт" + }, + verb: "иметь" }, - test: function(obj, key, document2) { - return { - newDocument: document2, - test: _areEquals(obj[key], this.value) - }; + array: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов" + }, + verb: "иметь" }, - _get: function(obj, key, document2) { - this.value = obj[key]; - return { newDocument: document2 }; + set: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов" + }, + verb: "иметь" } }; - arrOps = { - add: function(arr2, i, document2) { - if (isInteger(i)) - arr2.splice(i, 0, this.value); - else - arr2[i] = this.value; - return { - newDocument: document2, - index: i - }; - }, - remove: function(arr2, i, document2) { - return { - newDocument: document2, - removed: arr2.splice(i, 1)[0] - }; - }, - replace: function(arr2, i, document2) { - var removed = arr2[i]; - arr2[i] = this.value; - return { - newDocument: document2, - removed - }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "массив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js -function _generate(mirror, obj, patches, path2, invertible) { - if (obj === mirror) - return; - if (typeof obj.toJSON === "function") - obj = obj.toJSON(); - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var deleted = false; - for (var t = oldKeys.length - 1;t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) - _generate(oldVal, newVal, patches, path2 + "/" + escapePathComponent(key), invertible); - else if (oldVal !== newVal) { - if (invertible) - patches.push({ - op: "test", - path: path2 + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "replace", - path: path2 + "/" + escapePathComponent(key), - value: _deepClone(newVal) - }); + const Nouns = { + regex: "ввод", + email: "email адрес", + url: "URL", + emoji: "эмодзи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата и время", + date: "ISO дата", + time: "ISO время", + duration: "ISO длительность", + ipv4: "IPv4 адрес", + ipv6: "IPv6 адрес", + cidrv4: "IPv4 диапазон", + cidrv6: "IPv6 диапазон", + base64: "строка в формате base64", + base64url: "строка в формате base64url", + json_string: "JSON строка", + e164: "номер E.164", + jwt: "JWT", + template_literal: "ввод" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Неверный ввод: ожидалось ${issue3.expected}, получено ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Неверный ввод: ожидалось ${stringifyPrimitive2(issue3.values[0])}`; + return `Неверный вариант: ожидалось одно из ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + const maxValue = Number(issue3.maximum); + const unit = getRussianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком большое значение: ожидалось, что ${issue3.origin ?? "значение"} будет иметь ${adj}${issue3.maximum.toString()} ${unit}`; + } + return `Слишком большое значение: ожидалось, что ${issue3.origin ?? "значение"} будет ${adj}${issue3.maximum.toString()}`; } - } else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) - patches.push({ - op: "test", - path: path2 + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "remove", - path: path2 + "/" + escapePathComponent(key) - }); - deleted = true; - } else { - if (invertible) - patches.push({ - op: "test", - path: path2, - value: mirror - }); - patches.push({ - op: "replace", - path: path2, - value: obj - }); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + const minValue = Number(issue3.minimum); + const unit = getRussianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком маленькое значение: ожидалось, что ${issue3.origin} будет иметь ${adj}${issue3.minimum.toString()} ${unit}`; + } + return `Слишком маленькое значение: ожидалось, что ${issue3.origin} будет ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Неверная строка: должна начинаться с "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неверная строка: должна содержать "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; + return `Неверный ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Неверное число: должно быть кратным ${issue3.divisor}`; + case "unrecognized_keys": + return `Нераспознанн${issue3.keys.length > 1 ? "ые" : "ый"} ключ${issue3.keys.length > 1 ? "и" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Неверный ключ в ${issue3.origin}`; + case "invalid_union": + return "Неверные входные данные"; + case "invalid_element": + return `Неверное значение в ${issue3.origin}`; + default: + return `Неверные входные данные`; } - } - if (!deleted && newKeys.length == oldKeys.length) - return; - for (var t = 0;t < newKeys.length; t++) { - var key = newKeys[t]; - if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) - patches.push({ - op: "add", - path: path2 + "/" + escapePathComponent(key), - value: _deepClone(obj[key]) - }); - } -} -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; -} -var init_duplex = __esm(() => { - init_helpers(); - init_core3(); - /*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2013-2021 Joachim Wester - * MIT license - */ -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/fast-json-patch/index.js -var init_fast_json_patch = __esm(() => { - init_helpers(); - init_core3(); - init_duplex(); - ({ ...core_exports }); + }; +}; +var init_ru2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/log_stream.js -async function _getStandardizedInputs(run2, schemaFormat) { - if (schemaFormat === "original") - throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); - const { inputs } = run2; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run2.run_type)) - return inputs; - if (Object.keys(inputs).length === 1 && inputs?.input === "") - return; - return inputs.input; -} -async function _getStandardizedOutputs(run2, schemaFormat) { - const { outputs } = run2; - if (schemaFormat === "original") - return outputs; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run2.run_type)) - return outputs; - if (outputs !== undefined && Object.keys(outputs).length === 1 && outputs?.output !== undefined) - return outputs.output; - return outputs; -} -function isChatGenerationChunk(x) { - return x !== undefined && x.message !== undefined; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sl.js +function sl_default2() { + return { + localeError: error80() + }; } -var log_stream_exports, RunLogPatch = class { - ops; - constructor(fields) { - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch({}, ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } -}, RunLog, isLogStreamHandler = (handler) => handler.name === "log_stream_tracer", LogStreamCallbackHandler; -var init_log_stream = __esm(() => { - init_runtime2(); - init_ai(); - init_base3(); - init_core3(); - init_fast_json_patch(); - init_stream(); - log_stream_exports = /* @__PURE__ */ __exportAll({ - LogStreamCallbackHandler: () => LogStreamCallbackHandler, - RunLog: () => RunLog, - RunLogPatch: () => RunLogPatch, - isLogStreamHandler: () => isLogStreamHandler - }); - RunLog = class RunLog2 extends RunLogPatch { - state; - constructor(fields) { - super(fields); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch(this.state, other.ops); - return new RunLog2({ - ops, - state: states[states.length - 1].newDocument - }); - } - static fromRunLogPatch(patch) { - const states = applyPatch({}, patch.ops); - return new RunLog2({ - ops: patch.ops, - state: states[states.length - 1].newDocument - }); - } +var error80 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } }; - LogStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - _schemaFormat = "original"; - rootId; - keyMapByRunId = {}; - counterMapByRunName = {}; - transformStream; - writer; - receiveStream; - name = "log_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream; - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run2) { - if (run2.id === this.rootId) - return false; - const runTags = run2.tags ?? []; - let include = this.includeNames === undefined && this.includeTags === undefined && this.includeTypes === undefined; - if (this.includeNames !== undefined) - include = include || this.includeNames.includes(run2.name); - if (this.includeTypes !== undefined) - include = include || this.includeTypes.includes(run2.run_type); - if (this.includeTags !== undefined) - include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; - if (this.excludeNames !== undefined) - include = include && !this.excludeNames.includes(run2.name); - if (this.excludeTypes !== undefined) - include = include && !this.excludeTypes.includes(run2.run_type); - if (this.excludeTags !== undefined) - include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async* tapOutputIterable(runId, output) { - for await (const chunk of output) { - if (runId !== this.rootId) { - const key = this.keyMapByRunId[runId]; - if (key) - await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk - }] })); + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "število"; + } + case "object": { + if (Array.isArray(data)) { + return "tabela"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - yield chunk; } } - async onRunCreate(run2) { - if (this.rootId === undefined) { - this.rootId = run2.id; - await this.writer.write(new RunLogPatch({ ops: [{ - op: "replace", - path: "", - value: { - id: run2.id, - name: run2.name, - type: run2.run_type, - streamed_output: [], - final_output: undefined, - logs: {} - } - }] })); + return t; + }; + const Nouns = { + regex: "vnos", + email: "e-poštni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in čas", + date: "ISO datum", + time: "ISO čas", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 številka", + jwt: "JWT", + template_literal: "vnos" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Neveljaven vnos: pričakovano ${issue3.expected}, prejeto ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Neveljaven vnos: pričakovano ${stringifyPrimitive2(issue3.values[0])}`; + return `Neveljavna možnost: pričakovano eno izmed ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Preveliko: pričakovano, da bo ${issue3.origin ?? "vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pričakovano, da bo ${issue3.origin ?? "vrednost"} ${adj}${issue3.maximum.toString()}`; } - if (!this._includeRun(run2)) - return; - if (this.counterMapByRunName[run2.name] === undefined) - this.counterMapByRunName[run2.name] = 0; - this.counterMapByRunName[run2.name] += 1; - const count = this.counterMapByRunName[run2.name]; - this.keyMapByRunId[run2.id] = count === 1 ? run2.name : `${run2.name}:${count}`; - const logEntry = { - id: run2.id, - name: run2.name, - type: run2.run_type, - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {}, - start_time: new Date(run2.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: undefined, - end_time: undefined - }; - if (this._schemaFormat === "streaming_events") - logEntry.inputs = await _getStandardizedInputs(run2, this._schemaFormat); - await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${this.keyMapByRunId[run2.id]}`, - value: logEntry - }] })); - } - async onRunUpdate(run2) { - try { - const runName = this.keyMapByRunId[run2.id]; - if (runName === undefined) - return; - const ops = []; - if (this._schemaFormat === "streaming_events") - ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run2, this._schemaFormat) - }); - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run2, this._schemaFormat) - }); - if (run2.end_time !== undefined) - ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run2.end_time).toISOString() - }); - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); - } finally { - if (run2.id === this.rootId) { - const patch = new RunLogPatch({ ops: [{ - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run2, this._schemaFormat) - }] }); - await this.writer.write(patch); - if (this.autoClose) - await this.writer.close(); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Premajhno: pričakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } + return `Premajhno: pričakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } - } - async onLLMNewToken(run2, token, kwargs) { - const runName = this.keyMapByRunId[run2.id]; - if (runName === undefined) - return; - const isChatModel = run2.inputs.messages !== undefined; - let streamedOutputValue; - if (isChatModel) - if (isChatGenerationChunk(kwargs?.chunk)) - streamedOutputValue = kwargs?.chunk; - else - streamedOutputValue = new AIMessageChunk({ - id: `run-${run2.id}`, - content: token - }); - else - streamedOutputValue = token; - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token - }, { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue - }] }); - await this.writer.write(patch); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Neveljavno število: mora biti večkratnik ${issue3.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue3.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Neveljaven ključ v ${issue3.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue3.origin}`; + default: + return "Neveljaven vnos"; } }; +}; +var init_sl2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/event_stream.js -function assignName({ name, serialized }) { - if (name !== undefined) - return name; - if (serialized?.name !== undefined) - return serialized.name; - else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) - return serialized.id[serialized.id.length - 1]; - return "Unnamed"; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sv.js +function sv_default2() { + return { + localeError: error81() + }; } -var isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer", EventStreamCallbackHandler; -var init_event_stream = __esm(() => { - init_ai(); - init_base3(); - init_stream(); - init_outputs(); - EventStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - runInfoMap = /* @__PURE__ */ new Map; - tappedPromises = /* @__PURE__ */ new Map; - transformStream; - writer; - receiveStream; - readableStreamClosed = false; - name = "event_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream({ flush: () => { - this.readableStreamClosed = true; - } }); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run2) { - const runTags = run2.tags ?? []; - let include = this.includeNames === undefined && this.includeTags === undefined && this.includeTypes === undefined; - if (this.includeNames !== undefined) - include = include || this.includeNames.includes(run2.name); - if (this.includeTypes !== undefined) - include = include || this.includeTypes.includes(run2.runType); - if (this.includeTags !== undefined) - include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; - if (this.excludeNames !== undefined) - include = include && !this.excludeNames.includes(run2.name); - if (this.excludeTypes !== undefined) - include = include && !this.excludeTypes.includes(run2.runType); - if (this.excludeTags !== undefined) - include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async* tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) - return; - const runInfo = this.runInfoMap.get(runId); - if (runInfo === undefined) { - yield firstChunk.value; - return; - } - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") - return new GenerationChunk({ text: data }); - return data; +var error81 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att innehålla" }, + set: { unit: "objekt", verb: "att innehålla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "antal"; } - let tappedPromise = this.tappedPromises.get(runId); - if (tappedPromise === undefined) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve2) => { - tappedPromiseResolver = resolve2; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {} - }; - await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") - await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } - }, runInfo); - yield chunk; - } - } finally { - tappedPromiseResolver?.(); + case "object": { + if (Array.isArray(data)) { + return "lista"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - } else { - yield firstChunk.value; - for await (const chunk of outputStream) - yield chunk; } } - async send(payload, run2) { - if (this.readableStreamClosed) - return; - if (this._includeRun(run2)) - await this.writer.write(payload); - } - async sendEndEvent(payload, run2) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== undefined) - tappedPromise.then(() => { - this.send(payload, run2); - }); - else - await this.send(payload, run2); - } - async onLLMStart(run2) { - const runName = assignName(run2); - const runType = run2.inputs.messages !== undefined ? "chat_model" : "llm"; - const runInfo = { - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run2.inputs - }; - this.runInfoMap.set(run2.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { input: run2.inputs }, - name: runName, - tags: run2.tags ?? [], - run_id: run2.id, - metadata: run2.extra?.metadata ?? {} - }, runInfo); - } - async onLLMNewToken(run2, token, kwargs) { - const runInfo = this.runInfoMap.get(run2.id); - let chunk; - let eventName; - if (runInfo === undefined) - throw new Error(`onLLMNewToken: Run ID ${run2.id} not found in run map.`); - if (this.runInfoMap.size === 1) - return; - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === undefined) - chunk = new AIMessageChunk({ - content: token, - id: `run-${run2.id}` - }); - else - chunk = kwargs.chunk.message; - } else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === undefined) - chunk = new GenerationChunk({ text: token }); - else - chunk = kwargs.chunk; - } else - throw new Error(`Unexpected run type ${runInfo.runType}`); - await this.send({ - event: eventName, - data: { chunk }, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onLLMEnd(run2) { - const runInfo = this.runInfoMap.get(run2.id); - this.runInfoMap.delete(run2.id); - let eventName; - if (runInfo === undefined) - throw new Error(`onLLMEnd: Run ID ${run2.id} not found in run map.`); - const generations = run2.outputs?.generations; - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== undefined) - break; - output = generation[0]?.message; + return t; + }; + const Nouns = { + regex: "reguljärt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad sträng", + base64url: "base64url-kodad sträng", + json_string: "JSON-sträng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Ogiltig inmatning: förväntat ${issue3.expected}, fick ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Ogiltig inmatning: förväntat ${stringifyPrimitive2(issue3.values[0])}`; + return `Ogiltigt val: förväntade en av ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `För stor(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; } - eventName = "on_chat_model_end"; - } else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo - }; - }); - }), - llmOutput: run2.outputs?.llmOutput ?? {} - }; - eventName = "on_llm_end"; - } else - throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs - }, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onChainStart(run2) { - const runName = assignName(run2); - const runType = run2.run_type ?? "chain"; - const runInfo = { - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {}, - name: runName, - runType: run2.run_type - }; - let eventData = {}; - if (run2.inputs.input === "" && Object.keys(run2.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; - } else if (run2.inputs.input !== undefined) { - eventData.input = run2.inputs.input; - runInfo.inputs = run2.inputs.input; - } else { - eventData.input = run2.inputs; - runInfo.inputs = run2.inputs; + return `För stor(t): förväntat ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.maximum.toString()}`; } - this.runInfoMap.set(run2.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run2.tags ?? [], - run_id: run2.id, - metadata: run2.extra?.metadata ?? {} - }, runInfo); - } - async onChainEnd(run2) { - const runInfo = this.runInfoMap.get(run2.id); - this.runInfoMap.delete(run2.id); - if (runInfo === undefined) - throw new Error(`onChainEnd: Run ID ${run2.id} not found in run map.`); - const eventName = `on_${run2.run_type}_end`; - const inputs = run2.inputs ?? runInfo.inputs ?? {}; - const data = { - output: run2.outputs?.output ?? run2.outputs, - input: inputs - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `För lite(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `För lite(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.minimum.toString()}`; } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {} - }, runInfo); - } - async onToolStart(run2) { - const runName = assignName(run2); - const runInfo = { - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run2.inputs ?? {} - }; - this.runInfoMap.set(run2.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { input: run2.inputs ?? {} }, - name: runName, - run_id: run2.id, - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {} - }, runInfo); - } - async onToolEnd(run2) { - const runInfo = this.runInfoMap.get(run2.id); - this.runInfoMap.delete(run2.id); - if (runInfo === undefined) - throw new Error(`onToolEnd: Run ID ${run2.id} not found in run map.`); - if (runInfo.inputs === undefined) - throw new Error(`onToolEnd: Run ID ${run2.id} is a tool call, and is expected to have traced inputs.`); - const output = run2.outputs?.output === undefined ? run2.outputs : run2.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs - }, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onToolError(run2) { - const runInfo = this.runInfoMap.get(run2.id); - this.runInfoMap.delete(run2.id); - if (runInfo === undefined) - throw new Error(`onToolEnd: Run ID ${run2.id} not found in run map.`); - if (runInfo.inputs === undefined) - throw new Error(`onToolEnd: Run ID ${run2.id} is a tool call, and is expected to have traced inputs.`); - await this.sendEndEvent({ - event: "on_tool_error", - data: { - input: runInfo.inputs, - error: run2.error - }, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onRetrieverStart(run2) { - const runName = assignName(run2); - const runInfo = { - tags: run2.tags ?? [], - metadata: run2.extra?.metadata ?? {}, - name: runName, - runType: "retriever", - inputs: { query: run2.inputs.query } - }; - this.runInfoMap.set(run2.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { input: { query: run2.inputs.query } }, - name: runName, - tags: run2.tags ?? [], - run_id: run2.id, - metadata: run2.extra?.metadata ?? {} - }, runInfo); - } - async onRetrieverEnd(run2) { - const runInfo = this.runInfoMap.get(run2.id); - this.runInfoMap.delete(run2.id); - if (runInfo === undefined) - throw new Error(`onRetrieverEnd: Run ID ${run2.id} not found in run map.`); - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run2.outputs?.documents ?? run2.outputs, - input: runInfo.inputs - }, - run_id: run2.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === undefined) - throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data - }, runInfo); - } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - Promise.all(pendingPromises).finally(() => { - this.writer.close(); - }); + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; + return `Ogiltig(t) ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: måste vara en multipel av ${issue3.divisor}`; + case "unrecognized_keys": + return `${issue3.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue3.origin ?? "värdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt värde i ${issue3.origin ?? "värdet"}`; + default: + return `Ogiltig input`; } }; +}; +var init_sv2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/is-network-error/index.js -function isNetworkError2(error51) { - if (!(error51 && isError2(error51) && error51.name === "TypeError" && typeof error51.message === "string")) - return false; - const { message, stack } = error51; - if (message === "Load failed") - return stack === undefined || "__sentry_captured__" in error51; - if (message.startsWith("error sending request for url")) - return true; - return errorMessages2.has(message); -} -var objectToString2, isError2 = (value) => objectToString2.call(value) === "[object Error]", errorMessages2; -var init_is_network_error2 = __esm(() => { - objectToString2 = Object.prototype.toString; - errorMessages2 = new Set([ - "network error", - "Failed to fetch", - "NetworkError when attempting to fetch resource.", - "The Internet connection appears to be offline.", - "Network request failed", - "fetch failed", - "terminated", - " A network error occurred.", - "Network connection lost" - ]); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/p-retry/index.js -function validateRetries2(retries) { - if (typeof retries === "number") { - if (retries < 0) - throw new TypeError("Expected `retries` to be a non-negative number."); - if (Number.isNaN(retries)) - throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); - } else if (retries !== undefined) - throw new TypeError("Expected `retries` to be a number or Infinity."); -} -function validateNumberOption2(name, value, { min = 0, allowInfinity = false } = {}) { - if (value === undefined) - return; - if (typeof value !== "number" || Number.isNaN(value)) - throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); - if (!allowInfinity && !Number.isFinite(value)) - throw new TypeError(`Expected \`${name}\` to be a finite number.`); - if (value < min) - throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`); -} -function calculateDelay2(retriesConsumed, options) { - const attempt = Math.max(1, retriesConsumed + 1); - const random = options.randomize ? Math.random() + 1 : 1; - let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); - timeout = Math.min(timeout, options.maxTimeout); - return timeout; -} -function calculateRemainingTime2(start, max) { - if (!Number.isFinite(max)) - return max; - return max - (performance.now() - start); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ta.js +function ta_default2() { + return { + localeError: error82() + }; } -async function onAttemptFailure2({ error: error51, attemptNumber, retriesConsumed, startTime, options }) { - const normalizedError = error51 instanceof Error ? error51 : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error51}". You should only throw errors.`); - if (normalizedError instanceof AbortError2) - throw normalizedError.originalError; - const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; - const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; - const context = Object.freeze({ - error: normalizedError, - attemptNumber, - retriesLeft, - retriesConsumed - }); - await options.onFailedAttempt(context); - if (calculateRemainingTime2(startTime, maxRetryTime) <= 0) - throw normalizedError; - const consumeRetry = await options.shouldConsumeRetry(context); - const remainingTime = calculateRemainingTime2(startTime, maxRetryTime); - if (remainingTime <= 0 || retriesLeft <= 0) - throw normalizedError; - if (normalizedError instanceof TypeError && !isNetworkError2(normalizedError)) { - if (consumeRetry) - throw normalizedError; - options.signal?.throwIfAborted(); - return false; - } - if (!await options.shouldRetry(context)) - throw normalizedError; - if (!consumeRetry) { - options.signal?.throwIfAborted(); - return false; +var error82 = () => { + const Sizable = { + string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, + file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, + array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - const delayTime = calculateDelay2(retriesConsumed, options); - const finalDelay = Math.min(delayTime, remainingTime); - if (finalDelay > 0) - await new Promise((resolve2, reject) => { - const onAbort = () => { - clearTimeout(timeoutToken); - options.signal?.removeEventListener("abort", onAbort); - reject(options.signal.reason); - }; - const timeoutToken = setTimeout(() => { - options.signal?.removeEventListener("abort", onAbort); - resolve2(); - }, finalDelay); - if (options.unref) - timeoutToken.unref?.(); - options.signal?.addEventListener("abort", onAbort, { once: true }); - }); - options.signal?.throwIfAborted(); - return true; -} -async function pRetry2(input, options = {}) { - options = { ...options }; - validateRetries2(options.retries); - if (Object.hasOwn(options, "forever")) - throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); - options.retries ??= 10; - options.factor ??= 2; - options.minTimeout ??= 1000; - options.maxTimeout ??= Number.POSITIVE_INFINITY; - options.maxRetryTime ??= Number.POSITIVE_INFINITY; - options.randomize ??= false; - options.onFailedAttempt ??= () => {}; - options.shouldRetry ??= () => true; - options.shouldConsumeRetry ??= () => true; - validateNumberOption2("factor", options.factor, { - min: 0, - allowInfinity: false - }); - validateNumberOption2("minTimeout", options.minTimeout, { - min: 0, - allowInfinity: false - }); - validateNumberOption2("maxTimeout", options.maxTimeout, { - min: 0, - allowInfinity: true - }); - validateNumberOption2("maxRetryTime", options.maxRetryTime, { - min: 0, - allowInfinity: true - }); - if (!(options.factor > 0)) - options.factor = 1; - options.signal?.throwIfAborted(); - let attemptNumber = 0; - let retriesConsumed = 0; - const startTime = performance.now(); - while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { - attemptNumber++; - try { - options.signal?.throwIfAborted(); - const result = await input(attemptNumber); - options.signal?.throwIfAborted(); - return result; - } catch (error51) { - if (await onAttemptFailure2({ - error: error51, - attemptNumber, - retriesConsumed, - startTime, - options - })) - retriesConsumed++; + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; + } + case "object": { + if (Array.isArray(data)) { + return "அணி"; + } + if (data === null) { + return "வெறுமை"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - } - throw new Error("Retry attempts exhausted without throwing an error."); -} -var AbortError2; -var init_p_retry2 = __esm(() => { - init_is_network_error2(); - AbortError2 = class extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({ message } = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; + return t; + }; + const Nouns = { + regex: "உள்ளீடு", + email: "மின்னஞ்சல் முகவரி", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO தேதி நேரம்", + date: "ISO தேதி", + time: "ISO நேரம்", + duration: "ISO கால அளவு", + ipv4: "IPv4 முகவரி", + ipv6: "IPv6 முகவரி", + cidrv4: "IPv4 வரம்பு", + cidrv6: "IPv6 வரம்பு", + base64: "base64-encoded சரம்", + base64url: "base64url-encoded சரம்", + json_string: "JSON சரம்", + e164: "E.164 எண்", + jwt: "JWT", + template_literal: "input" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue3.expected}, பெறப்பட்டது ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive2(issue3.values[0])}`; + return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues2(issue3.values, "|")} இல் ஒன்று`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin ?? "மதிப்பு"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; + } + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin ?? "மதிப்பு"} ${adj}${issue3.maximum.toString()} ஆக இருக்க வேண்டும்`; } - this.name = "AbortError"; - this.message = message; + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; + } + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ஆக இருக்க வேண்டும்`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; + if (_issue.format === "ends_with") + return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; + if (_issue.format === "includes") + return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; + if (_issue.format === "regex") + return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; + return `தவறான ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `தவறான எண்: ${issue3.divisor} இன் பலமாக இருக்க வேண்டும்`; + case "unrecognized_keys": + return `அடையாளம் தெரியாத விசை${issue3.keys.length > 1 ? "கள்" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `${issue3.origin} இல் தவறான விசை`; + case "invalid_union": + return "தவறான உள்ளீடு"; + case "invalid_element": + return `${issue3.origin} இல் தவறான மதிப்பு`; + default: + return `தவறான உள்ளீடு`; } }; +}; +var init_ta2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/async_caller.js -var import_p_queue4, async_caller_exports, STATUS_NO_RETRY, defaultFailedAttemptHandler = (error51) => { - if (typeof error51 !== "object" || error51 === null) - return; - if ("message" in error51 && typeof error51.message === "string" && (error51.message.startsWith("Cancel") || error51.message.startsWith("AbortError")) || "name" in error51 && typeof error51.name === "string" && error51.name === "AbortError") - throw error51; - if ("code" in error51 && typeof error51.code === "string" && error51.code === "ECONNABORTED") - throw error51; - const responseStatus = "response" in error51 && typeof error51.response === "object" && error51.response !== null && "status" in error51.response && typeof error51.response.status === "number" ? error51.response.status : undefined; - const directStatus = "status" in error51 && typeof error51.status === "number" ? error51.status : undefined; - const status = responseStatus ?? directStatus; - if (status && STATUS_NO_RETRY.includes(+status)) - throw error51; - if (("error" in error51 && typeof error51.error === "object" && error51.error !== null && "code" in error51.error && typeof error51.error.code === "string" ? error51.error.code : undefined) === "insufficient_quota") { - const err = new Error("message" in error51 && typeof error51.message === "string" ? error51.message : "Insufficient quota"); - err.name = "InsufficientQuotaError"; - throw err; - } -}, AsyncCaller2 = class { - maxConcurrency; - maxRetries; - onFailedAttempt; - queue; - constructor(params) { - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue2 = "default" in import_p_queue4.default ? import_p_queue4.default.default : import_p_queue4.default; - this.queue = new PQueue2({ concurrency: this.maxConcurrency }); - } - async call(callable, ...args) { - return this.queue.add(() => pRetry2(() => callable(...args).catch((error51) => { - if (error51 instanceof Error) - throw error51; - else - throw new Error(error51); - }), { - onFailedAttempt: ({ error: error51 }) => this.onFailedAttempt?.(error51), - retries: this.maxRetries, - randomize: true - }), { throwOnTimeout: true }); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/th.js +function th_default2() { + return { + localeError: error83() + }; +} +var error83 = () => { + const Sizable = { + string: { unit: "ตัวอักษร", verb: "ควรมี" }, + file: { unit: "ไบต์", verb: "ควรมี" }, + array: { unit: "รายการ", verb: "ควรมี" }, + set: { unit: "รายการ", verb: "ควรมี" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - callWithOptions(options, callable, ...args) { - if (options.signal) { - let listener; - return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { - listener = () => { - reject(getAbortSignalError(options.signal)); - }; - options.signal?.addEventListener("abort", listener, { once: true }); - })]).finally(() => { - if (options.signal && listener) - options.signal.removeEventListener("abort", listener); - }); + const parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; + } + case "object": { + if (Array.isArray(data)) { + return "อาร์เรย์ (Array)"; + } + if (data === null) { + return "ไม่มีค่า (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); - } + return t; + }; + const Nouns = { + regex: "ข้อมูลที่ป้อน", + email: "ที่อยู่อีเมล", + url: "URL", + emoji: "อิโมจิ", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "วันที่เวลาแบบ ISO", + date: "วันที่แบบ ISO", + time: "เวลาแบบ ISO", + duration: "ช่วงเวลาแบบ ISO", + ipv4: "ที่อยู่ IPv4", + ipv6: "ที่อยู่ IPv6", + cidrv4: "ช่วง IP แบบ IPv4", + cidrv6: "ช่วง IP แบบ IPv6", + base64: "ข้อความแบบ Base64", + base64url: "ข้อความแบบ Base64 สำหรับ URL", + json_string: "ข้อความแบบ JSON", + e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", + jwt: "โทเคน JWT", + template_literal: "ข้อมูลที่ป้อน" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue3.expected} แต่ได้รับ ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive2(issue3.values[0])}`; + return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "ไม่เกิน" : "น้อยกว่า"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `เกินกำหนด: ${issue3.origin ?? "ค่า"} ควรมี${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "รายการ"}`; + return `เกินกำหนด: ${issue3.origin ?? "ค่า"} ควรมี${adj} ${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? "อย่างน้อย" : "มากกว่า"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()} ${sizing.unit}`; + } + return `น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; + if (_issue.format === "includes") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; + if (_issue.format === "regex") + return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; + return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue3.divisor} ได้ลงตัว`; + case "unrecognized_keys": + return `พบคีย์ที่ไม่รู้จัก: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `คีย์ไม่ถูกต้องใน ${issue3.origin}`; + case "invalid_union": + return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; + case "invalid_element": + return `ข้อมูลไม่ถูกต้องใน ${issue3.origin}`; + default: + return `ข้อมูลไม่ถูกต้อง`; + } + }; }; -var init_async_caller2 = __esm(() => { - init_runtime2(); - init_signal(); - init_p_retry2(); - import_p_queue4 = __toESM(require_dist(), 1); - async_caller_exports = /* @__PURE__ */ __exportAll({ AsyncCaller: () => AsyncCaller2 }); - STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 - ]; +var init_th2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/root_listener.js -var RootListenersTracer; -var init_root_listener = __esm(() => { - init_base3(); - RootListenersTracer = class extends BaseTracer { - name = "RootListenersTracer"; - rootId; - config; - argOnStart; - argOnEnd; - argOnError; - constructor({ config: config2, onStart, onEnd, onError: onError2 }) { - super({ _awaitHandler: true }); - this.config = config2; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError2; - } - persistRun(_) { - return Promise.resolve(); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/tr.js +function tr_default2() { + return { + localeError: error84() + }; +} +var parsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - async onRunCreate(run2) { - if (this.rootId) - return; - this.rootId = run2.id; - if (this.argOnStart) - await this.argOnStart(run2, this.config); + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - async onRunUpdate(run2) { - if (run2.id !== this.rootId) - return; - if (!run2.error) { - if (this.argOnEnd) - await this.argOnEnd(run2, this.config); - } else if (this.argOnError) - await this.argOnError(run2, this.config); + } + return t; +}, error84 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmalı" }, + file: { unit: "bayt", verb: "olmalı" }, + array: { unit: "öğe", verb: "olmalı" }, + set: { unit: "öğe", verb: "olmalı" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO süre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aralığı", + cidrv6: "IPv6 aralığı", + base64: "base64 ile şifrelenmiş metin", + base64url: "base64url ile şifrelenmiş metin", + json_string: "JSON dizesi", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "Şablon dizesi" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Geçersiz değer: beklenen ${issue3.expected}, alınan ${parsedType4(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Geçersiz değer: beklenen ${stringifyPrimitive2(issue3.values[0])}`; + return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Çok büyük: beklenen ${issue3.origin ?? "değer"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "öğe"}`; + return `Çok büyük: beklenen ${issue3.origin ?? "değer"} ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + return `Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; + if (_issue.format === "ends_with") + return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Geçersiz metin: "${_issue.includes}" içermeli`; + if (_issue.format === "regex") + return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; + return `Geçersiz ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Geçersiz sayı: ${issue3.divisor} ile tam bölünebilmeli`; + case "unrecognized_keys": + return `Tanınmayan anahtar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `${issue3.origin} içinde geçersiz anahtar`; + case "invalid_union": + return "Geçersiz değer"; + case "invalid_element": + return `${issue3.origin} içinde geçersiz değer`; + default: + return `Geçersiz değer`; } }; +}; +var init_tr2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/utils.js -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ua.js +function ua_default2() { + return { + localeError: error85() + }; } -var _RootEventFilter = class { - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - constructor(fields) { - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; - } - includeEvent(event, rootType) { - let include = this.includeNames === undefined && this.includeTypes === undefined && this.includeTags === undefined; - const eventTags = event.tags ?? []; - if (this.includeNames !== undefined) - include = include || this.includeNames.includes(event.name); - if (this.includeTypes !== undefined) - include = include || this.includeTypes.includes(rootType); - if (this.includeTags !== undefined) - include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); - if (this.excludeNames !== undefined) - include = include && !this.excludeNames.includes(event.name); - if (this.excludeTypes !== undefined) - include = include && !this.excludeTypes.includes(rootType); - if (this.excludeTags !== undefined) - include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } -}, toBase64Url = (str) => { - return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -}; -var init_utils4 = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/graph_mermaid.js -function _escapeNodeLabel(nodeLabel) { - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); -} -function _generateMermaidGraphStyles(nodeColors) { - let styles2 = ""; - for (const [className, color2] of Object.entries(nodeColors)) - styles2 += ` classDef ${className} ${color2}; -`; - return styles2; -} -function drawMermaid(nodes, edges, config2) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config2 ?? {}; - let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%% -graph TD; -` : `graph TD; -`; - if (withStyles) { - const defaultClassLabel = "default"; - const formatDict = { [defaultClassLabel]: "{0}({1})" }; - if (firstNode !== undefined) - formatDict[firstNode] = "{0}([{1}]):::first"; - if (lastNode !== undefined) - formatDict[lastNode] = "{0}([{1}]):::last"; - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - let finalLabel = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; - if (Object.keys(node.metadata ?? {}).length) - finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join(` -`)}`; - const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); - mermaidGraph += ` ${nodeLabel} -`; - } - } - const edgeGroups = {}; - for (const edge of edges) { - const srcParts = edge.source.split(":"); - const tgtParts = edge.target.split(":"); - const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); - if (!edgeGroups[commonPrefix]) - edgeGroups[commonPrefix] = []; - edgeGroups[commonPrefix].push(edge); - } - const seenSubgraphs = /* @__PURE__ */ new Set; - function sortPrefixesByDepth(prefixes) { - return [...prefixes].sort((a, b) => { - return a.split(":").length - b.split(":").length; - }); - } - function addSubgraph(edges2, prefix) { - const selfLoop = edges2.length === 1 && edges2[0].source === edges2[0].target; - if (prefix && !selfLoop) { - const subgraph = prefix.split(":").pop(); - if (seenSubgraphs.has(prefix)) - throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); - seenSubgraphs.add(prefix); - mermaidGraph += ` subgraph ${subgraph} -`; - } - const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1)); - for (const nestedPrefix of nestedPrefixes) - addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); - for (const edge of edges2) { - const { source, target, data, conditional } = edge; - let edgeLabel = ""; - if (data !== undefined) { - let edgeData = data; - const words = edgeData.split(" "); - if (words.length > wrapLabelNWords) - edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); - edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; - } else - edgeLabel = conditional ? " -.-> " : " --> "; - mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)}; -`; - } - if (prefix && !selfLoop) - mermaidGraph += ` end -`; - } - addSubgraph(edgeGroups[""] ?? [], ""); - for (const prefix in edgeGroups) - if (!prefix.includes(":") && prefix !== "") - addSubgraph(edgeGroups[prefix], prefix); - if (withStyles) - mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); - return mermaidGraph; -} -async function drawMermaidImage(mermaidSyntax, config2) { - let backgroundColor = config2?.backgroundColor ?? "white"; - const imageType = config2?.imageType ?? "png"; - const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax); - if (backgroundColor !== undefined) { - if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(backgroundColor)) - backgroundColor = `!${backgroundColor}`; +var error85 = () => { + const Sizable = { + string: { unit: "символів", verb: "матиме" }, + file: { unit: "байтів", verb: "матиме" }, + array: { unit: "елементів", verb: "матиме" }, + set: { unit: "елементів", verb: "матиме" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; - const res = await fetch(imageUrl); - if (!res.ok) - throw new Error([ - `Failed to render the graph using the Mermaid.INK API.`, - `Status code: ${res.status}`, - `Status text: ${res.statusText}` - ].join(` -`)); - return await res.blob(); -} -var MARKDOWN_SPECIAL_CHARS; -var init_graph_mermaid = __esm(() => { - init_utils4(); - MARKDOWN_SPECIAL_CHARS = [ - "*", - "_", - "`" - ]; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/graph.js -function nodeDataStr(id, data) { - if (id !== undefined && !validate2(id)) - return id; - else if (isRunnableInterface(data)) - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); + const parsedType5 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "масив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - else - return data.name ?? "UnknownSchema"; -} -function nodeDataJson(node) { - if (isRunnableInterface(node.data)) - return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName() + return t; + }; + const Nouns = { + regex: "вхідні дані", + email: "адреса електронної пошти", + url: "URL", + emoji: "емодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "дата та час ISO", + date: "дата ISO", + time: "час ISO", + duration: "тривалість ISO", + ipv4: "адреса IPv4", + ipv6: "адреса IPv6", + cidrv4: "діапазон IPv4", + cidrv6: "діапазон IPv6", + base64: "рядок у кодуванні base64", + base64url: "рядок у кодуванні base64url", + json_string: "рядок JSON", + e164: "номер E.164", + jwt: "JWT", + template_literal: "вхідні дані" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Неправильні вхідні дані: очікується ${issue3.expected}, отримано ${parsedType5(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Неправильні вхідні дані: очікується ${stringifyPrimitive2(issue3.values[0])}`; + return `Неправильна опція: очікується одне з ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Занадто велике: очікується, що ${issue3.origin ?? "значення"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "елементів"}`; + return `Занадто велике: очікується, що ${issue3.origin ?? "значення"} буде ${adj}${issue3.maximum.toString()}`; } - }; - else - return { - type: "schema", - data: { - ...toJsonSchema(node.data.schema), - title: node.data.name + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Занадто мале: очікується, що ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + } + return `Занадто мале: очікується, що ${issue3.origin} буде ${adj}${issue3.minimum.toString()}`; } - }; -} -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) - if (!exclude.includes(node.id) && !targets.has(node.id)) - found.push(node); - return found.length === 1 ? found[0] : undefined; -} -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) - if (!exclude.includes(node.id) && !sources.has(node.id)) - found.push(node); - return found.length === 1 ? found[0] : undefined; -} -var graph_exports, Graph = class Graph2 { - nodes = {}; - edges = []; - constructor(params) { - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; - } - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i) => { - stableNodeIds[node.id] = validate2(node.id) ? i : node.id; - }); - return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node) - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target] - }; - if (typeof edge.data !== "undefined") - item.data = edge.data; - if (typeof edge.conditional !== "undefined") - item.conditional = edge.conditional; - return item; - }) - }; - } - addNode(data, id, metadata) { - if (id !== undefined && this.nodes[id] !== undefined) - throw new Error(`Node with id ${id} already exists`); - const nodeId = id ?? v4(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - delete this.nodes[node.id]; - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); - } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === undefined) - throw new Error(`Source node ${source.id} not in graph`); - if (this.nodes[target.id] === undefined) - throw new Error(`Target node ${target.id} not in graph`); - const edge = { - source: source.id, - target: target.id, - data, - conditional - }; - this.edges.push(edge); - return edge; - } - firstNode() { - return _firstNode(this); - } - lastNode() { - return _lastNode(this); - } - extend(graph, prefix = "") { - let finalPrefix = prefix; - if (Object.values(graph.nodes).map((node) => node.id).every(validate2)) - finalPrefix = ""; - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { - ...value, - id: prefixed(key) - }; - }); - const newEdges = graph.edges.map((edge) => { - return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target) - }; - }); - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [first ? { - id: prefixed(first.id), - data: first.data - } : undefined, last ? { - id: prefixed(last.id), - data: last.data - } : undefined]; - } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) - this.removeNode(firstNode); - } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) - this.removeNode(lastNode); - } - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = /* @__PURE__ */ new Map; - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (validate2(nodeId) && nodeLabelCounts.get(label) === 1) - return label; - else - return nodeId; - }; - return new Graph2({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { - ...node, - id: getNodeId(id) - }])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target) - })) - }); - } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc" - }, wrapLabelNWords } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords - }); - } - async drawMermaidPng(params) { - return drawMermaidImage(this.drawMermaid(params), { backgroundColor: params?.backgroundColor }); - } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неправильний рядок: повинен містити "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; + return `Неправильний ${Nouns[_issue.format] ?? issue3.format}`; + } + case "not_multiple_of": + return `Неправильне число: повинно бути кратним ${issue3.divisor}`; + case "unrecognized_keys": + return `Нерозпізнаний ключ${issue3.keys.length > 1 ? "і" : ""}: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Неправильний ключ у ${issue3.origin}`; + case "invalid_union": + return "Неправильні вхідні дані"; + case "invalid_element": + return `Неправильне значення у ${issue3.origin}`; + default: + return `Неправильні вхідні дані`; + } + }; }; -var init_graph = __esm(() => { - init_runtime2(); - init_validate(); - init_v4(); - init_uuid(); - init_utils4(); - init_graph_mermaid(); - init_json_schema2(); - graph_exports = /* @__PURE__ */ __exportAll({ Graph: () => Graph }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/wrappers.js -function convertToHttpEventStream(stream2) { - const encoder2 = new TextEncoder; - const finalStream = new ReadableStream({ async start(controller) { - for await (const chunk of stream2) - controller.enqueue(encoder2.encode(`event: data -data: ${JSON.stringify(chunk)} - -`)); - controller.enqueue(encoder2.encode(`event: end - -`)); - controller.close(); - } }); - return IterableReadableStream.fromReadableStream(finalStream); -} -var init_wrappers = __esm(() => { - init_stream(); +var init_ua2 = __esm(() => { + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/iter.js -function isIterableIterator(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; -} -function isAsyncIterable(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; -} -function isAsyncGenerator(x) { - return x != null && typeof x === "object" && typeof x.next === "function"; -} -async function consumeAsyncGenerator(generator, onYield) { - try { - let iterResult = await generator.next(); - while (!iterResult.done) { - await onYield?.(iterResult.value); - iterResult = await generator.next(); - } - return iterResult.value; - } finally { - await generator.return?.(undefined); - } -} -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) - break; - else - yield value; - } +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ur.js +function ur_default2() { + return { + localeError: error86() + }; } -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) - break; - else - yield value; +var error86 = () => { + const Sizable = { + string: { unit: "حروف", verb: "ہونا" }, + file: { unit: "بائٹس", verb: "ہونا" }, + array: { unit: "آئٹمز", verb: "ہونا" }, + set: { unit: "آئٹمز", verb: "ہونا" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } -} -var isIterator = (x) => x != null && typeof x === "object" && ("next" in x) && typeof x.next === "function"; -var init_iter = __esm(() => { - init_async_local_storage(); - init_singletons(); - init_config(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/base.js -function _coerceToDict2(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) - throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); -} -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") - return new RunnableLambda({ func: coerceable }); - else if (Runnable.isRunnable(coerceable)) - return coerceable; - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) - runnables[key] = _coerceToRunnable(value); - return new RunnableMap({ steps: runnables }); - } else - throw new Error(`Expected a Runnable, function or object. -Instead got an unsupported type.`); -} -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? getSchemaDescription(fields.schema); - if (isSimpleStringZodSchema(fields.schema)) - return new RunnableToolLike({ - name, - description, - schema: exports_external2.object({ input: exports_external2.string() }).transform((input) => input.input), - bound: runnable - }); - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable - }); -} -var Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableTraceable, RunnableLambda, RunnableParallel, RunnableWithFallbacks, RunnableAssign, RunnablePick, RunnableToolLike; -var init_base4 = __esm(() => { - init_utils2(); - init_serializable(); - init_v7(); - init_uuid(); - init_async_local_storage(); - init_singletons(); - init_config(); - init_signal(); - init_stream(); - init_log_stream(); - init_event_stream(); - init_p_retry2(); - init_async_caller2(); - init_root_listener(); - init_utils4(); - init_zod2(); - init_graph(); - init_wrappers(); - init_iter(); - init_traceable2(); - init_v3(); - Runnable = class extends Serializable { - lc_runnable = true; - name; - getName(suffix) { - const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; - return suffix ? `${name}${suffix}` : name; - } - withRetry(fields) { - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - withConfig(config2) { - return new RunnableBinding({ - bound: this, - config: config2, - kwargs: {} - }); - } - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - return new RunnableWithFallbacks({ - runnable: this, - fallbacks - }); - } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) - throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - if (Array.isArray(options)) - return options.map(ensureConfig); - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + const parsedType5 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "نمبر"; } - return Array.from({ length }, () => ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const caller = new AsyncCaller2({ - maxConcurrency: configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency, - onFailedAttempt: (e) => { - throw e; + case "object": { + if (Array.isArray(data)) { + return "آرے"; } - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - return await this.invoke(input, configList[i]); - } catch (e) { - if (batchOptions?.returnExceptions) - return e; - throw e; + if (data === null) { + return "نل"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - })); - return Promise.all(batchCalls); - } - async* _streamIterator(input, options) { - yield this.invoke(input, options); - } - async stream(input, options) { - const config2 = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config2), - config: config2 - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === undefined) - runnableConfig = ensureConfig(options); - else - runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal - }); - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; - } - async _callWithConfig(func, input, options) { - const config2 = ensureConfig(options); - const runManager = await (await getCallbackManagerForConfig(config2))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config2.runId, config2?.runType, undefined, undefined, config2?.runName ?? this.getName()); - delete config2.runId; - let output; - try { - output = await raceWithSignal(func.call(this, input, config2, runManager), config2.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; } - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - return output; } - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); - delete optionsList[i].runId; - return handleStartRes; - })); - let outputs; - try { - outputs = await raceWithSignal(func.call(this, inputs, optionsList, runManagers, batchOptions), optionsList?.[0]?.signal); - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; + return t; + }; + const Nouns = { + regex: "ان پٹ", + email: "ای میل ایڈریس", + url: "یو آر ایل", + emoji: "ایموجی", + uuid: "یو یو آئی ڈی", + uuidv4: "یو یو آئی ڈی وی 4", + uuidv6: "یو یو آئی ڈی وی 6", + nanoid: "نینو آئی ڈی", + guid: "جی یو آئی ڈی", + cuid: "سی یو آئی ڈی", + cuid2: "سی یو آئی ڈی 2", + ulid: "یو ایل آئی ڈی", + xid: "ایکس آئی ڈی", + ksuid: "کے ایس یو آئی ڈی", + datetime: "آئی ایس او ڈیٹ ٹائم", + date: "آئی ایس او تاریخ", + time: "آئی ایس او وقت", + duration: "آئی ایس او مدت", + ipv4: "آئی پی وی 4 ایڈریس", + ipv6: "آئی پی وی 6 ایڈریس", + cidrv4: "آئی پی وی 4 رینج", + cidrv6: "آئی پی وی 6 رینج", + base64: "بیس 64 ان کوڈڈ سٹرنگ", + base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", + json_string: "جے ایس او این سٹرنگ", + e164: "ای 164 نمبر", + jwt: "جے ڈبلیو ٹی", + template_literal: "ان پٹ" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `غلط ان پٹ: ${issue3.expected} متوقع تھا، ${parsedType5(issue3.input)} موصول ہوا`; + case "invalid_value": + if (issue3.values.length === 1) + return `غلط ان پٹ: ${stringifyPrimitive2(issue3.values[0])} متوقع تھا`; + return `غلط آپشن: ${joinValues2(issue3.values, "|")} میں سے ایک متوقع تھا`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `بہت بڑا: ${issue3.origin ?? "ویلیو"} کے ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; + return `بہت بڑا: ${issue3.origin ?? "ویلیو"} کا ${adj}${issue3.maximum.toString()} ہونا متوقع تھا`; } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(outputs, "output")))); - return outputs; - } - _concatOutputChunks(first, second) { - return concat(first, second); - } - async* _transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config2 = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config2); - const outerThis = this; - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) - if (finalInput === undefined) - finalInput = chunk; - else - try { - finalInput = outerThis._concatOutputChunks(finalInput, chunk); - } catch { - finalInput = undefined; - finalInputSupported = false; - } - yield chunk; + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `بہت چھوٹا: ${issue3.origin} کے ${adj}${issue3.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; } + return `بہت چھوٹا: ${issue3.origin} کا ${adj}${issue3.minimum.toString()} ہونا متوقع تھا`; } - let runManager; - try { - const pipe2 = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config2.runId, config2.runType, undefined, undefined, config2.runName ?? this.getName(), undefined, { lc_defers_inputs: true }), config2.signal, config2); - delete config2.runId; - runManager = pipe2.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe2.output; - if (streamEventsHandler !== undefined && runManager !== undefined) - iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== undefined && runManager !== undefined) - iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = undefined; - finalOutputSupported = false; - } + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; } - } catch (e) { - await runManager?.handleChainError(e, undefined, undefined, undefined, { inputs: _coerceToDict2(finalInput, "input") }); - throw e; + if (_issue.format === "ends_with") + return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; + if (_issue.format === "includes") + return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; + if (_issue.format === "regex") + return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; + return `غلط ${Nouns[_issue.format] ?? issue3.format}`; } - await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict2(finalInput, "input") }); - } - getGraph(_) { - const graph = new Graph; - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: exports_external2.any() - }); - const runnableNode = graph.addNode(this); - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: exports_external2.any() - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; - } - pipe(coerceable) { - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable) - }); - } - pick(keys) { - return this.pipe(new RunnablePick(keys)); - } - assign(mapping) { - return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); - } - async* transform(generator, options) { - let finalChunk; - for await (const chunk of generator) - if (finalChunk === undefined) - finalChunk = chunk; - else - finalChunk = this._concatOutputChunks(finalChunk, chunk); - yield* this._streamIterator(finalChunk, ensureConfig(options)); - } - async* streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original" - }); - const config2 = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config2); + case "not_multiple_of": + return `غلط نمبر: ${issue3.divisor} کا مضاعف ہونا چاہیے`; + case "unrecognized_keys": + return `غیر تسلیم شدہ کی${issue3.keys.length > 1 ? "ز" : ""}: ${joinValues2(issue3.keys, "، ")}`; + case "invalid_key": + return `${issue3.origin} میں غلط کی`; + case "invalid_union": + return "غلط ان پٹ"; + case "invalid_element": + return `${issue3.origin} میں غلط ویلیو`; + default: + return `غلط ان پٹ`; } - async* _streamLog(input, logStreamCallbackHandler, config2) { - const { callbacks } = config2; - if (callbacks === undefined) - config2.callbacks = [logStreamCallbackHandler]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat([logStreamCallbackHandler]); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - config2.callbacks = copiedCallbacks; + }; +}; +var init_ur2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/vi.js +function vi_default2() { + return { + localeError: error87() + }; +} +var error87 = () => { + const Sizable = { + string: { unit: "ký tự", verb: "có" }, + file: { unit: "byte", verb: "có" }, + array: { unit: "phần tử", verb: "có" }, + set: { unit: "phần tử", verb: "có" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType5 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "số"; } - const runnableStreamPromise = this.stream(input, config2); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: "/streamed_output/-", - value: chunk - }] }); - await logStreamCallbackHandler.writer.write(patch); - } - } finally { - await logStreamCallbackHandler.writer.close(); + case "object": { + if (Array.isArray(data)) { + return "mảng"; } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) - yield log; - } finally { - await runnableStreamConsumePromise; - } - } - streamEvents(input, options, streamOptions) { - let stream2; - if (options.version === "v1") - stream2 = this._streamEventsV1(input, options, streamOptions); - else if (options.version === "v2") - stream2 = this._streamEventsV2(input, options, streamOptions); - else - throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); - if (options.encoding === "text/event-stream") - return convertToHttpEventStream(stream2); - else - return IterableReadableStream.fromAsyncGenerator(stream2); - } - async* _streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false - }); - const config2 = ensureConfig(options); - const runId = config2.runId ?? v7(); - config2.runId = runId; - const callbacks = config2.callbacks; - if (callbacks === undefined) - config2.callbacks = [eventStreamer]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat(eventStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - config2.callbacks = copiedCallbacks; - } - const abortController = new AbortController; - const outerThis = this; - async function consumeRunnableStream() { - let signal; - try { - if (config2.signal) - if ("any" in AbortSignal) - signal = AbortSignal.any([abortController.signal, config2.signal]); - else { - const composed = new AbortController; - config2.signal.addEventListener("abort", () => composed.abort(), { once: true }); - abortController.signal.addEventListener("abort", () => composed.abort(), { once: true }); - signal = composed.signal; - } - else - signal = abortController.signal; - const runnableStream = await outerThis.stream(input, { - ...config2, - signal - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - for await (const _ of tappedStream) - if (abortController.signal.aborted) - break; - } finally { - await eventStreamer.finish(); + if (data === null) { + return "null"; } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; - continue; - } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - if (event.data?.input) - delete event.data.input; - } - yield event; + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - } finally { - abortController.abort(); - await runnableStreamConsumePromise; } } - async* _streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config2 = ensureConfig(options); - const rootTags = config2.tags ?? []; - const rootMetadata = config2.metadata ?? {}; - const rootName = config2.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events" - }); - const rootEventFilter = new _RootEventFilter({ ...streamOptions }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config2); - for await (const log of logStream) { - if (!runLog) - runLog = RunLog.fromRunLogPatch(log); - else - runLog = runLog.concat(log); - if (runLog.state === undefined) - throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state3 = { ...runLog.state }; - const event = { - run_id: state3.id, - event: `on_${state3.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { input } - }; - if (rootEventFilter.includeEvent(event, state3.type)) - yield event; - } - const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path2 of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path2]; - if (logEntry.end_time === undefined) - if (logEntry.streamed_output.length > 0) - eventType = "stream"; - else - eventType = "start"; - else - eventType = "end"; - if (eventType === "start") { - if (logEntry.inputs !== undefined) - data.input = logEntry.inputs; - } else if (eventType === "end") { - if (logEntry.inputs !== undefined) - data.input = logEntry.inputs; - data.output = logEntry.final_output; - } else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); - data = { chunk: logEntry.streamed_output[0] }; - logEntry.streamed_output = []; - } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data - }; - } - const { state: state2 } = runLog; - if (state2.streamed_output.length > 0) { - const chunkCount = state2.streamed_output.length; - if (chunkCount !== 1) - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`); - const data = { chunk: state2.streamed_output[0] }; - state2.streamed_output = []; - const event = { - event: `on_${state2.type}_stream`, - run_id: state2.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data - }; - if (rootEventFilter.includeEvent(event, state2.type)) - yield event; + return t; + }; + const Nouns = { + regex: "đầu vào", + email: "địa chỉ email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ngày giờ ISO", + date: "ngày ISO", + time: "giờ ISO", + duration: "khoảng thời gian ISO", + ipv4: "địa chỉ IPv4", + ipv6: "địa chỉ IPv6", + cidrv4: "dải IPv4", + cidrv6: "dải IPv6", + base64: "chuỗi mã hóa base64", + base64url: "chuỗi mã hóa base64url", + json_string: "chuỗi JSON", + e164: "số E.164", + jwt: "JWT", + template_literal: "đầu vào" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `Đầu vào không hợp lệ: mong đợi ${issue3.expected}, nhận được ${parsedType5(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive2(issue3.values[0])}`; + return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `Quá lớn: mong đợi ${issue3.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "phần tử"}`; + return `Quá lớn: mong đợi ${issue3.origin ?? "giá trị"} ${adj}${issue3.maximum.toString()}`; + } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `Quá nhỏ: mong đợi ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } + return `Quá nhỏ: mong đợi ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } - const state = runLog?.state; - if (state !== undefined) { - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { output: state.final_output } - }; - if (rootEventFilter.includeEvent(event, state.type)) - yield event; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue3.format} không hợp lệ`; } - } - static isRunnable(thing) { - return isRunnableInterface(thing); - } - withListeners({ onStart, onEnd, onError: onError2 }) { - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [(config2) => ({ callbacks: [new RootListenersTracer({ - config: config2, - onStart, - onEnd, - onError: onError2 - })] })] - }); - } - asTool(fields) { - return convertRunnableToTool(this, fields); - } - }; - RunnableBinding = class RunnableBinding2 extends Runnable { - static lc_name() { - return "RunnableBinding"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - bound; - config; - kwargs; - configFactories; - constructor(fields) { - super(fields); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; - } - getName(suffix) { - return this.bound.getName(suffix); - } - async _mergeConfig(...options) { - const config2 = mergeConfigs(this.config, ...options); - return mergeConfigs(config2, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config2))) : []); - } - withConfig(config2) { - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { - ...this.config, - ...config2 - } - }); - } - withRetry(fields) { - return new RunnableRetry({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - _concatOutputChunks(first, second) { - return this.bound._concatOutputChunks(first, second); - } - async* _streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async* transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - streamEvents(input, options, streamOptions) { - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), - version: options.version - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); - } - static isRunnableBinding(thing) { - return thing.bound && Runnable.isRunnable(thing.bound); - } - withListeners({ onStart, onEnd, onError: onError2 }) { - return new RunnableBinding2({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [(config2) => ({ callbacks: [new RootListenersTracer({ - config: config2, - onStart, - onEnd, - onError: onError2 - })] })] - }); + case "not_multiple_of": + return `Số không hợp lệ: phải là bội số của ${issue3.divisor}`; + case "unrecognized_keys": + return `Khóa không được nhận dạng: ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `Khóa không hợp lệ trong ${issue3.origin}`; + case "invalid_union": + return "Đầu vào không hợp lệ"; + case "invalid_element": + return `Giá trị không hợp lệ trong ${issue3.origin}`; + default: + return `Đầu vào không hợp lệ`; } }; - RunnableEach = class RunnableEach2 extends Runnable { - static lc_name() { - return "RunnableEach"; - } - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - bound; - constructor(fields) { - super(fields); - this.bound = fields.bound; - } - async invoke(inputs, config2) { - return this._callWithConfig(this._invoke.bind(this), inputs, config2); - } - async _invoke(inputs, config2, runManager) { - return this.bound.batch(inputs, patchConfig(config2, { callbacks: runManager?.getChild() })); - } - withListeners({ onStart, onEnd, onError: onError2 }) { - return new RunnableEach2({ bound: this.bound.withListeners({ - onStart, - onEnd, - onError: onError2 - }) }); - } +}; +var init_vi2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-CN.js +function zh_CN_default2() { + return { + localeError: error88() }; - RunnableRetry = class extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - lc_namespace = ["langchain_core", "runnables"]; - maxAttemptNumber = 3; - onFailedAttempt = () => {}; - constructor(fields) { - super(fields); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config2, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; - return patchConfig(config2, { callbacks: runManager?.getChild(tag) }); - } - async _invoke(input, config2, runManager) { - return pRetry2((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config2, runManager)), { - onFailedAttempt: ({ error: error51 }) => this.onFailedAttempt(error51, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } - async invoke(input, config2) { - return this._callWithConfig(this._invoke.bind(this), input, config2); - } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await pRetry2(async (attemptNumber) => { - const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === undefined || resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true - }); - let firstException; - for (let i = 0;i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - if (result instanceof Error) { - if (firstException === undefined) { - firstException = result; - firstException.input = remainingInputs[i]; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) - throw firstException; - return results; - }, { - onFailedAttempt: ({ error: error51 }) => this.onFailedAttempt(error51, error51.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } catch (e) { - if (batchOptions?.returnExceptions !== true) - throw e; - } - return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); - } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); - } +} +var error88 = () => { + const Sizable = { + string: { unit: "字符", verb: "包含" }, + file: { unit: "字节", verb: "包含" }, + array: { unit: "项", verb: "包含" }, + set: { unit: "项", verb: "包含" } }; - RunnableSequence = class RunnableSequence2 extends Runnable { - static lc_name() { - return "RunnableSequence"; - } - first; - middle = []; - last; - omitSequenceTags = false; - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - constructor(fields) { - super(fields); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; - } - get steps() { - return [ - this.first, - ...this.middle, - this.last - ]; - } - async invoke(input, options) { - const config2 = ensureConfig(options); - const runManager = await (await getCallbackManagerForConfig(config2))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config2.runId, undefined, undefined, undefined, config2?.runName); - delete config2.runId; - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0;i < initialSteps.length; i += 1) - nextStepInput = await raceWithSignal(initialSteps[i].invoke(nextStepInput, patchConfig(config2, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`) })), config2.signal); - if (config2.signal?.aborted) - throw getAbortSignalError(config2.signal); - finalOutput = await this.last.invoke(nextStepInput, patchConfig(config2, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`) })); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); - return finalOutput; - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let nextStepInputs = inputs; - try { - for (let i = 0;i < this.steps.length; i += 1) - nextStepInputs = await raceWithSignal(this.steps[i].batch(nextStepInputs, runManagers.map((runManager, j) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); - return patchConfig(configList[j], { callbacks: childRunManager }); - }), batchOptions), configList[0]?.signal); - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(nextStepInputs, "output")))); - return nextStepInputs; - } - _concatOutputChunks(first, second) { - return this.last._concatOutputChunks(first, second); - } - async* _streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId, ...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); - const steps = [ - this.first, - ...this.middle, - this.last - ]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType5 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "非数字(NaN)" : "数字"; } - try { - let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`) })); - for (let i = 1;i < steps.length; i += 1) - finalGenerator = await steps[i].transform(finalGenerator, patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`) })); - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = undefined; - concatSupported = false; - } + case "object": { + if (Array.isArray(data)) { + return "数组"; + } + if (data === null) { + return "空值(null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - } catch (e) { - await runManager?.handleChainError(e); - throw e; } - await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); - } - getGraph(config2) { - const graph = new Graph; - let currentLastNode = null; - this.steps.forEach((step, index) => { - const stepGraph = step.getGraph(config2); - if (index !== 0) - stepGraph.trimFirstNode(); - if (index !== this.steps.length - 1) - stepGraph.trimLastNode(); - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) - throw new Error(`Runnable ${step} has no first node`); - if (currentLastNode) - graph.addEdge(currentLastNode, stepFirstNode); - currentLastNode = stepGraph.lastNode(); - }); - return graph; - } - pipe(coerceable) { - if (RunnableSequence2.isRunnableSequence(coerceable)) - return new RunnableSequence2({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle - ]), - last: coerceable.last, - name: this.name ?? coerceable.name - }); - else - return new RunnableSequence2({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name - }); - } - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); - } - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") - extra.name = nameOrFields; - else if (nameOrFields !== undefined) - extra = nameOrFields; - return new RunnableSequence2({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]) - }); } + return t; }; - RunnableMap = class RunnableMap2 extends Runnable { - static lc_name() { - return "RunnableMap"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - steps; - getStepsKeys() { - return Object.keys(this.steps); - } - constructor(fields) { - super(fields); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) - this.steps[key] = _coerceToRunnable(value); - } - static from(steps) { - return new RunnableMap2({ steps }); - } - async invoke(input, options) { - const config2 = ensureConfig(options); - const runManager = await (await getCallbackManagerForConfig(config2))?.handleChainStart(this.toJSON(), { input }, config2.runId, undefined, undefined, undefined, config2?.runName); - delete config2.runId; - const output = {}; - try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, patchConfig(config2, { callbacks: runManager?.getChild(`map:key:${key}`) })); - }); - await raceWithSignal(Promise.all(promises), config2.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; + const Nouns = { + regex: "输入", + email: "电子邮件", + url: "URL", + emoji: "表情符号", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日期时间", + date: "ISO日期", + time: "ISO时间", + duration: "ISO时长", + ipv4: "IPv4地址", + ipv6: "IPv6地址", + cidrv4: "IPv4网段", + cidrv6: "IPv6网段", + base64: "base64编码字符串", + base64url: "base64url编码字符串", + json_string: "JSON字符串", + e164: "E.164号码", + jwt: "JWT", + template_literal: "输入" + }; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `无效输入:期望 ${issue3.expected},实际接收 ${parsedType5(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `无效输入:期望 ${stringifyPrimitive2(issue3.values[0])}`; + return `无效选项:期望以下之一 ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `数值过大:期望 ${issue3.origin ?? "值"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "个元素"}`; + return `数值过大:期望 ${issue3.origin ?? "值"} ${adj}${issue3.maximum.toString()}`; } - await runManager?.handleChainEnd(output); - return output; - } - async* _transform(generator, runManager, options) { - const steps = { ...this.steps }; - const inputCopies = atee(generator, Object.keys(steps).length); - const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { - const gen = runnable.transform(inputCopies[i], patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); - return [key, gen.next().then((result) => ({ - key, - gen, - result - }))]; - })); - while (tasks.size) { - const { key, result, gen } = await raceWithSignal(Promise.race(tasks.values()), options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result2) => ({ - key, - gen, - result: result2 - }))); + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } + return `数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()}`; } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") + return `无效字符串:必须以 "${_issue.prefix}" 开头`; + if (_issue.format === "ends_with") + return `无效字符串:必须以 "${_issue.suffix}" 结尾`; + if (_issue.format === "includes") + return `无效字符串:必须包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; + return `无效${Nouns[_issue.format] ?? issue3.format}`; } - const config2 = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config2), - config: config2 - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + case "not_multiple_of": + return `无效数字:必须是 ${issue3.divisor} 的倍数`; + case "unrecognized_keys": + return `出现未知的键(key): ${joinValues2(issue3.keys, ", ")}`; + case "invalid_key": + return `${issue3.origin} 中的键(key)无效`; + case "invalid_union": + return "无效输入"; + case "invalid_element": + return `${issue3.origin} 中包含无效值(value)`; + default: + return `无效输入`; } }; - RunnableTraceable = class RunnableTraceable2 extends Runnable { - lc_serializable = false; - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - super(fields); - if (!isTraceableFunction(fields.func)) - throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); - this.func = fields.func; - } - async invoke(input, options) { - const [config2] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config2); - return raceWithSignal(this.func(patchConfig(config2, { callbacks }), input), config2?.signal); - } - async* _streamIterator(input, options) { - const [config2] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (isAsyncIterable(result)) { - for await (const item of result) { - config2?.signal?.throwIfAborted(); - yield item; - } - return; +}; +var init_zh_CN2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-TW.js +function zh_TW_default2() { + return { + localeError: error89() + }; +} +var error89 = () => { + const Sizable = { + string: { unit: "字元", verb: "擁有" }, + file: { unit: "位元組", verb: "擁有" }, + array: { unit: "項目", verb: "擁有" }, + set: { unit: "項目", verb: "擁有" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType5 = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - if (isIterator(result)) { - while (true) { - config2?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) - break; - yield state.value; + case "object": { + if (Array.isArray(data)) { + return "array"; } - return; - } - yield result; - } - static from(func) { - return new RunnableTraceable2({ func }); - } - }; - RunnableLambda = class RunnableLambda2 extends Runnable { - static lc_name() { - return "RunnableLambda"; - } - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - if (isTraceableFunction(fields.func)) - return RunnableTraceable.from(fields.func); - super(fields); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new RunnableLambda2({ func }); - } - async _invoke(input, config2, runManager) { - return new Promise((resolve2, reject) => { - const childConfig = patchConfig(config2, { - callbacks: runManager?.getChild(), - recursionLimit: (config2?.recursionLimit ?? 25) - 1 - }); - AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { ...childConfig }); - if (output && Runnable.isRunnable(output)) { - if (config2?.recursionLimit === 0) - throw new Error("Recursion limit reached."); - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? 25) - 1 - }); - } else if (isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config2?.signal?.throwIfAborted(); - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config2?.signal?.throwIfAborted(); - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } - resolve2(output); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); - } - async* _transform(generator, runManager, config2) { - let finalChunk; - for await (const chunk of generator) - if (finalChunk === undefined) - finalChunk = chunk; - else - try { - finalChunk = this._concatOutputChunks(finalChunk, chunk); - } catch { - finalChunk = chunk; - } - const childConfig = patchConfig(config2, { - callbacks: runManager?.getChild(), - recursionLimit: (config2?.recursionLimit ?? 25) - 1 - }); - const output = await new Promise((resolve2, reject) => { - AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - resolve2(await this.func(finalChunk, { - ...childConfig, - config: childConfig - })); - } catch (e) { - reject(e); - } - }); - }); - if (output && Runnable.isRunnable(output)) { - if (config2?.recursionLimit === 0) - throw new Error("Recursion limit reached."); - const stream2 = await output.stream(finalChunk, childConfig); - for await (const chunk of stream2) - yield chunk; - } else if (isAsyncIterable(output)) - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config2?.signal?.throwIfAborted(); - yield chunk; + if (data === null) { + return "null"; } - else if (isIterableIterator(output)) - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config2?.signal?.throwIfAborted(); - yield chunk; + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - else - yield output; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; } - const config2 = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config2), - config: config2 - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } + return t; }; - RunnableParallel = class extends RunnableMap { + const Nouns = { + regex: "輸入", + email: "郵件地址", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 日期時間", + date: "ISO 日期", + time: "ISO 時間", + duration: "ISO 期間", + ipv4: "IPv4 位址", + ipv6: "IPv6 位址", + cidrv4: "IPv4 範圍", + cidrv6: "IPv6 範圍", + base64: "base64 編碼字串", + base64url: "base64url 編碼字串", + json_string: "JSON 字串", + e164: "E.164 數值", + jwt: "JWT", + template_literal: "輸入" }; - RunnableWithFallbacks = class extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnable; - fallbacks; - constructor(fields) { - super(fields); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; - } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) - yield fallback; - } - async invoke(input, options) { - const config2 = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config2); - const { runId, ...otherConfigFields } = config2; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - return await AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config2?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - return output; - } catch (e) { - if (firstError === undefined) - firstError = e; - } - } - if (firstError === undefined) - throw new Error("No error stored at end of fallback."); - await runManager?.handleChainError(firstError); - throw firstError; - }); - } - async* _streamIterator(input, options) { - const config2 = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config2); - const { runId, ...otherConfigFields } = config2; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - let firstError; - let stream2; - for (const runnable of this.runnables()) { - config2?.signal?.throwIfAborted(); - const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - try { - stream2 = consumeAsyncIterableInContext(childConfig, await runnable.stream(input, childConfig)); - break; - } catch (e) { - if (firstError === undefined) - firstError = e; - } - } - if (stream2 === undefined) { - const error51 = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error51); - throw error51; + return (issue3) => { + switch (issue3.code) { + case "invalid_type": + return `無效的輸入值:預期為 ${issue3.expected},但收到 ${parsedType5(issue3.input)}`; + case "invalid_value": + if (issue3.values.length === 1) + return `無效的輸入值:預期為 ${stringifyPrimitive2(issue3.values[0])}`; + return `無效的選項:預期為以下其中之一 ${joinValues2(issue3.values, "|")}`; + case "too_big": { + const adj = issue3.inclusive ? "<=" : "<"; + const sizing = getSizing(issue3.origin); + if (sizing) + return `數值過大:預期 ${issue3.origin ?? "值"} 應為 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "個元素"}`; + return `數值過大:預期 ${issue3.origin ?? "值"} 應為 ${adj}${issue3.maximum.toString()}`; } - let output; - try { - for await (const chunk of stream2) { - yield chunk; - try { - output = output === undefined ? output : this._concatOutputChunks(output, chunk); - } catch { - output = undefined; - } + case "too_small": { + const adj = issue3.inclusive ? ">=" : ">"; + const sizing = getSizing(issue3.origin); + if (sizing) { + return `數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; } - } catch (e) { - await runManager?.handleChainError(e); - throw e; + return `數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()}`; } - await runManager?.handleChainEnd(_coerceToDict2(output, "output")); - } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) - throw new Error("Not implemented."); - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config2) => getCallbackManagerForConfig(config2))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict2(outputs[i], "output")))); - return outputs; - } catch (e) { - if (firstError === undefined) - firstError = e; + case "invalid_format": { + const _issue = issue3; + if (_issue.format === "starts_with") { + return `無效的字串:必須以 "${_issue.prefix}" 開頭`; } + if (_issue.format === "ends_with") + return `無效的字串:必須以 "${_issue.suffix}" 結尾`; + if (_issue.format === "includes") + return `無效的字串:必須包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `無效的字串:必須符合格式 ${_issue.pattern}`; + return `無效的 ${Nouns[_issue.format] ?? issue3.format}`; } - if (!firstError) - throw new Error("No error stored at end of fallbacks."); - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; + case "not_multiple_of": + return `無效的數字:必須為 ${issue3.divisor} 的倍數`; + case "unrecognized_keys": + return `無法識別的鍵值${issue3.keys.length > 1 ? "們" : ""}:${joinValues2(issue3.keys, "、")}`; + case "invalid_key": + return `${issue3.origin} 中有無效的鍵值`; + case "invalid_union": + return "無效的輸入值"; + case "invalid_element": + return `${issue3.origin} 中有無效的值`; + default: + return `無效的輸入值`; } }; - RunnableAssign = class extends Runnable { - static lc_name() { - return "RunnableAssign"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - mapper; - constructor(fields) { - if (fields instanceof RunnableMap) - fields = { mapper: fields }; - super(fields); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult - }; - } - async* _transform(generator, runManager, options) { - const mapperKeys = this.mapper.getStepsKeys(); - const [forPassthrough, forMapper] = atee(generator); - const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); - const firstMapperChunkPromise = mapperOutput.next(); - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) - throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) - yield filtered; - } - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) - yield chunk; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config2 = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config2), - config: config2 - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - }; - RunnablePick = class extends Runnable { - static lc_name() { - return "RunnablePick"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - keys; - constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) - fields = { keys: fields }; - super(fields); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") - return input[this.keys]; - else { - const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== undefined); - return picked.length === 0 ? undefined : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async* _transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== undefined) - yield picked; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; +}; +var init_zh_TW2 = __esm(() => { + init_util2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/index.js +var exports_locales2 = {}; +__export(exports_locales2, { + zhTW: () => zh_TW_default2, + zhCN: () => zh_CN_default2, + vi: () => vi_default2, + ur: () => ur_default2, + ua: () => ua_default2, + tr: () => tr_default2, + th: () => th_default2, + ta: () => ta_default2, + sv: () => sv_default2, + sl: () => sl_default2, + ru: () => ru_default2, + pt: () => pt_default2, + ps: () => ps_default2, + pl: () => pl_default2, + ota: () => ota_default2, + no: () => no_default2, + nl: () => nl_default2, + ms: () => ms_default2, + mk: () => mk_default2, + ko: () => ko_default2, + kh: () => kh_default2, + ja: () => ja_default2, + it: () => it_default2, + id: () => id_default2, + hu: () => hu_default2, + he: () => he_default2, + frCA: () => fr_CA_default2, + fr: () => fr_default2, + fi: () => fi_default2, + fa: () => fa_default2, + es: () => es_default2, + eo: () => eo_default2, + en: () => en_default2, + de: () => de_default2, + cs: () => cs_default2, + ca: () => ca_default2, + be: () => be_default2, + az: () => az_default2, + ar: () => ar_default2 +}); +var init_locales2 = __esm(() => { + init_ar2(); + init_az2(); + init_be2(); + init_ca2(); + init_cs2(); + init_de2(); + init_en2(); + init_eo2(); + init_es2(); + init_fa2(); + init_fi2(); + init_fr2(); + init_fr_CA2(); + init_he2(); + init_hu2(); + init_id2(); + init_it2(); + init_ja2(); + init_kh2(); + init_ko2(); + init_mk2(); + init_ms2(); + init_nl2(); + init_no2(); + init_ota2(); + init_ps2(); + init_pl2(); + init_pt2(); + init_ru2(); + init_sl2(); + init_sv2(); + init_ta2(); + init_th2(); + init_tr2(); + init_ua2(); + init_ur2(); + init_vi2(); + init_zh_CN2(); + init_zh_TW2(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js +class $ZodRegistry2 { + constructor() { + this._map = new Map; + this._idmap = new Map; + } + add(schema, ..._meta) { + const meta3 = _meta[0]; + this._map.set(schema, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + if (this._idmap.has(meta3.id)) { + throw new Error(`ID ${meta3.id} already exists in the registry`); } - const config2 = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config2), - config: config2 - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + this._idmap.set(meta3.id, schema); } - }; - RunnableToolLike = class extends RunnableBinding { - name; - description; - schema; - constructor(fields) { - const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) - try { - toolInput = await interopParseAsync(this.schema, input.args); - } catch { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - else - toolInput = input; - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {} - }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; + return this; + } + clear() { + this._map = new Map; + this._idmap = new Map; + return this; + } + remove(schema) { + const meta3 = this._map.get(schema); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); } - static lc_name() { - return "RunnableToolLike"; + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + return { ...pm, ...this._map.get(schema) }; } - }; + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +function registry2() { + return new $ZodRegistry2; +} +var $output2, $input2, globalRegistry2; +var init_registries2 = __esm(() => { + $output2 = Symbol("ZodOutput"); + $input2 = Symbol("ZodInput"); + globalRegistry2 = /* @__PURE__ */ registry2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/transformers.js -function filterMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) - return _filterMessages(messagesOrOptions, options); - return RunnableLambda.from((input) => { - return _filterMessages(input, messagesOrOptions); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js +function _string2(Class3, params) { + return new Class3({ + type: "string", + ...normalizeParams2(params) }); } -function _filterMessages(messages, options = {}) { - const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; - const filtered = []; - for (const msg of messages) { - if (excludeNames && msg.name && excludeNames.includes(msg.name)) - continue; - else if (excludeTypes && _isMessageType(msg, excludeTypes)) - continue; - else if (excludeIds && msg.id && excludeIds.includes(msg.id)) - continue; - if (!(includeTypes || includeIds || includeNames)) - filtered.push(msg); - else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) - filtered.push(msg); - else if (includeTypes && _isMessageType(msg, includeTypes)) - filtered.push(msg); - else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) - filtered.push(msg); - } - return filtered; +function _coercedString2(Class3, params) { + return new Class3({ + type: "string", + coerce: true, + ...normalizeParams2(params) + }); } -function mergeMessageRuns(messages) { - if (Array.isArray(messages)) - return _mergeMessageRuns(messages); - return RunnableLambda.from(_mergeMessageRuns); +function _email2(Class3, params) { + return new Class3({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function _mergeMessageRuns(messages) { - if (!messages.length) - return []; - const merged = []; - for (const msg of messages) { - const curr = msg; - const last = merged.pop(); - if (!last) - merged.push(curr); - else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) - merged.push(last, curr); - else { - const lastChunk = convertToChunk(last); - const currChunk = convertToChunk(curr); - const mergedChunks = lastChunk.concat(currChunk); - if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") - mergedChunks.content = `${lastChunk.content} -${currChunk.content}`; - merged.push(_chunkToMsg(mergedChunks)); - } - } - return merged; +function _guid2(Class3, params) { + return new Class3({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function trimMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - const messages = messagesOrOptions; - if (!options) - throw new Error("Options parameter is required when providing messages."); - return _trimMessagesHelper(messages, options); - } else { - const trimmerOptions = messagesOrOptions; - return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); - } +function _uuid2(Class3, params) { + return new Class3({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -async function _trimMessagesHelper(messages, options) { - const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; - if (startOn && strategy === "first") - throw new Error("`startOn` should only be specified if `strategy` is 'last'."); - if (includeSystem && strategy === "first") - throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); - let listTokenCounter; - if ("getNumTokens" in tokenCounter) - listTokenCounter = async (msgs) => { - return (await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)))).reduce((sum, count) => sum + count, 0); - }; - else - listTokenCounter = async (msgs) => tokenCounter(msgs); - let textSplitterFunc = defaultTextSplitter; - if (textSplitter) - if ("splitText" in textSplitter) - textSplitterFunc = textSplitter.splitText; - else - textSplitterFunc = async (text) => textSplitter(text); - if (strategy === "first") - return _firstMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - partialStrategy: allowPartial ? "first" : undefined, - endOn - }); - else if (strategy === "last") - return _lastMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - allowPartial, - includeSystem, - startOn, - endOn - }); - else - throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); +function _uuidv42(Class3, params) { + return new Class3({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams2(params) + }); } -async function _firstMaxTokens(messages, options) { - const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; - let messagesCopy = [...messages]; - let idx = 0; - for (let i = 0;i < messagesCopy.length; i += 1) - if (await tokenCounter(i > 0 ? messagesCopy.slice(0, -i) : messagesCopy) <= maxTokens) { - idx = messagesCopy.length - i; - break; - } - if (idx < messagesCopy.length && partialStrategy) { - let includedPartial = false; - if (Array.isArray(messagesCopy[idx].content)) { - const excluded = messagesCopy[idx]; - if (typeof excluded.content === "string") - throw new Error("Expected content to be an array."); - const numBlock = excluded.content.length; - const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; - for (let i = 1;i <= numBlock; i += 1) { - const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); - const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - const updatedMessage = _switchTypeToMessage(excluded.getType(), { - ...fields, - content: partialContent - }); - const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; - if (await tokenCounter(slicedMessages) <= maxTokens) { - messagesCopy = slicedMessages; - idx += 1; - includedPartial = true; - } else - break; - } - if (includedPartial && partialStrategy === "last") - excluded.content = [...reversedContent].reverse(); - } - if (!includedPartial) { - const excluded = messagesCopy[idx]; - let text; - if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) - text = excluded.content.find((block) => block.type === "text" && block.text)?.text; - else if (typeof excluded.content === "string") - text = excluded.content; - if (text) { - const splitTexts = await textSplitter(text); - const numSplits = splitTexts.length; - if (partialStrategy === "last") - splitTexts.reverse(); - for (let _ = 0;_ < numSplits - 1; _ += 1) { - splitTexts.pop(); - excluded.content = splitTexts.join(""); - if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { - if (partialStrategy === "last") - excluded.content = [...splitTexts].reverse().join(""); - messagesCopy = [...messagesCopy.slice(0, idx), excluded]; - idx += 1; - break; - } - } - } - } - } - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) - idx -= 1; - } - return messagesCopy.slice(0, idx); +function _uuidv62(Class3, params) { + return new Class3({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams2(params) + }); } -async function _lastMaxTokens(messages, options) { - const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; - let messagesCopy = messages.map((message) => { - const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); +function _uuidv72(Class3, params) { + return new Class3({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams2(params) }); - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) - messagesCopy = messagesCopy.slice(0, -1); - } - const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; - let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); - reversed_ = await _firstMaxTokens(reversed_, { - ...rest, - partialStrategy: allowPartial ? "last" : undefined, - endOn: startOn +} +function _url2(Class3, params) { + return new Class3({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); - if (swappedSystem) - return [reversed_[0], ...reversed_.slice(1).reverse()]; - else - return reversed_.reverse(); } -function _switchTypeToMessage(messageType, fields, returnChunk) { - let chunk; - let msg; - switch (messageType) { - case "human": - if (returnChunk) - chunk = new HumanMessageChunk(fields); - else - msg = new HumanMessage(fields); - break; - case "ai": - if (returnChunk) { - let aiChunkFields = { ...fields }; - if ("tool_calls" in aiChunkFields) - aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: undefined, - args: JSON.stringify(tc.args) - })) - }; - chunk = new AIMessageChunk(aiChunkFields); - } else - msg = new AIMessage(fields); - break; - case "system": - if (returnChunk) - chunk = new SystemMessageChunk(fields); - else - msg = new SystemMessage(fields); - break; - case "developer": - if (returnChunk) - chunk = new SystemMessageChunk({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - else - msg = new SystemMessage({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - break; - case "tool": - if ("tool_call_id" in fields) - if (returnChunk) - chunk = new ToolMessageChunk(fields); - else - msg = new ToolMessage(fields); - else - throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); - break; - case "function": - if (returnChunk) - chunk = new FunctionMessageChunk(fields); - else { - if (!fields.name) - throw new Error("FunctionMessage must have a 'name' field"); - msg = new FunctionMessage(fields); - } - break; - case "generic": - if ("role" in fields) - if (returnChunk) - chunk = new ChatMessageChunk(fields); - else - msg = new ChatMessage(fields); - else - throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); - break; - default: - throw new Error(`Unrecognized message type ${messageType}`); - } - if (returnChunk && chunk) - return chunk; - if (msg) - return msg; - throw new Error(`Unrecognized message type ${messageType}`); +function _emoji4(Class3, params) { + return new Class3({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function _chunkToMsg(chunk) { - const chunkType = chunk.getType(); - let msg; - const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); - if (chunkType in _MSG_CHUNK_MAP) - msg = _switchTypeToMessage(chunkType, fields); - if (!msg) - throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); - return msg; +function _nanoid2(Class3, params) { + return new Class3({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function defaultTextSplitter(text) { - const splits = text.split(` -`); - return Promise.resolve([...splits.slice(0, -1).map((s) => `${s} -`), splits[splits.length - 1]]); +function _cuid3(Class3, params) { + return new Class3({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -var _isMessageType = (msg, types3) => { - const typesAsStrings = [...new Set(types3?.map((t) => { - if (typeof t === "string") - return t; - const instantiatedMsgClass = new t({}); - if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") - throw new Error("Invalid type provided."); - return instantiatedMsgClass.getType(); - }))]; - const msgType = msg.getType(); - return typesAsStrings.some((t) => t === msgType); -}, _MSG_CHUNK_MAP; -var init_transformers = __esm(() => { - init_base(); - init_tool(); - init_ai(); - init_chat(); - init_function(); - init_human(); - init_modifier(); - init_system(); - init_utils3(); - init_base4(); - _MSG_CHUNK_MAP = { - human: { - message: HumanMessage, - messageChunk: HumanMessageChunk - }, - ai: { - message: AIMessage, - messageChunk: AIMessageChunk - }, - system: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - developer: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - tool: { - message: ToolMessage, - messageChunk: ToolMessageChunk - }, - function: { - message: FunctionMessage, - messageChunk: FunctionMessageChunk - }, - generic: { - message: ChatMessage, - messageChunk: ChatMessageChunk - }, - remove: { - message: RemoveMessage, - messageChunk: RemoveMessage - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/content/tools.js -var KNOWN_BLOCK_TYPES; -var init_tools = __esm(() => { - KNOWN_BLOCK_TYPES = [ - "tool_call", - "tool_call_chunk", - "invalid_tool_call", - "server_tool_call", - "server_tool_call_chunk", - "server_tool_call_result" - ]; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/content/multimodal.js -var KNOWN_BLOCK_TYPES2; -var init_multimodal = __esm(() => { - KNOWN_BLOCK_TYPES2 = [ - "image", - "video", - "audio", - "text-plain", - "file" - ]; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/content/index.js -var KNOWN_BLOCK_TYPES3; -var init_content = __esm(() => { - init_tools(); - init_multimodal(); - KNOWN_BLOCK_TYPES3 = [ - "text", - "reasoning", - ...KNOWN_BLOCK_TYPES, - ...KNOWN_BLOCK_TYPES2 - ]; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/messages/index.js -var messages_exports; -var init_messages = __esm(() => { - init_runtime2(); - init_data(); - init_message(); - init_base(); - init_metadata(); - init_tool(); - init_ai(); - init_chat(); - init_function(); - init_human(); - init_modifier(); - init_system(); - init_utils3(); - init_transformers(); - init_content(); - messages_exports = /* @__PURE__ */ __exportAll({ - AIMessage: () => AIMessage, - AIMessageChunk: () => AIMessageChunk, - BaseMessage: () => BaseMessage, - BaseMessageChunk: () => BaseMessageChunk, - ChatMessage: () => ChatMessage, - ChatMessageChunk: () => ChatMessageChunk, - DEFAULT_MERGE_IGNORE_KEYS: () => DEFAULT_MERGE_IGNORE_KEYS, - FunctionMessage: () => FunctionMessage, - FunctionMessageChunk: () => FunctionMessageChunk, - HumanMessage: () => HumanMessage, - HumanMessageChunk: () => HumanMessageChunk, - KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES3, - RemoveMessage: () => RemoveMessage, - SystemMessage: () => SystemMessage, - SystemMessageChunk: () => SystemMessageChunk, - ToolMessage: () => ToolMessage, - ToolMessageChunk: () => ToolMessageChunk, - _isMessageFieldWithRole: () => _isMessageFieldWithRole, - _mergeDicts: () => _mergeDicts, - _mergeLists: () => _mergeLists, - _mergeObj: () => _mergeObj, - _mergeStatus: () => _mergeStatus, - coerceMessageLikeToMessage: () => coerceMessageLikeToMessage, - collapseToolCallChunks: () => collapseToolCallChunks, - convertToChunk: () => convertToChunk, - convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, - convertToProviderContentBlock: () => convertToProviderContentBlock, - defaultTextSplitter: () => defaultTextSplitter, - defaultToolCallParser: () => defaultToolCallParser, - filterMessages: () => filterMessages, - getBufferString: () => getBufferString, - iife: () => iife2, - isAIMessage: () => isAIMessage, - isAIMessageChunk: () => isAIMessageChunk, - isBase64ContentBlock: () => isBase64ContentBlock, - isBaseMessage: () => isBaseMessage, - isBaseMessageChunk: () => isBaseMessageChunk, - isChatMessage: () => isChatMessage, - isChatMessageChunk: () => isChatMessageChunk, - isDataContentBlock: () => isDataContentBlock, - isDirectToolOutput: () => isDirectToolOutput, - isFunctionMessage: () => isFunctionMessage, - isFunctionMessageChunk: () => isFunctionMessageChunk, - isHumanMessage: () => isHumanMessage, - isHumanMessageChunk: () => isHumanMessageChunk, - isIDContentBlock: () => isIDContentBlock, - isMessage: () => isMessage, - isOpenAIToolCallArray: () => isOpenAIToolCallArray, - isPlainTextContentBlock: () => isPlainTextContentBlock, - isSystemMessage: () => isSystemMessage, - isSystemMessageChunk: () => isSystemMessageChunk, - isToolMessage: () => isToolMessage, - isToolMessageChunk: () => isToolMessageChunk, - isURLContentBlock: () => isURLContentBlock, - mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, - mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, - mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, - mergeContent: () => mergeContent, - mergeMessageRuns: () => mergeMessageRuns, - mergeResponseMetadata: () => mergeResponseMetadata, - mergeUsageMetadata: () => mergeUsageMetadata, - parseBase64DataUrl: () => parseBase64DataUrl, - parseMimeType: () => parseMimeType, - trimMessages: () => trimMessages +function _cuid22(Class3, params) { + return new Class3({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/js-sha256/hash.js -function Sha256(is224, sharedMemory) { - if (sharedMemory) { - blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - this.blocks = blocks; - } else - this.blocks = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - if (is224) { - this.h0 = 3238371032; - this.h1 = 914150663; - this.h2 = 812702999; - this.h3 = 4144912697; - this.h4 = 4290775857; - this.h5 = 1750603025; - this.h6 = 1694076839; - this.h7 = 3204075428; - } else { - this.h0 = 1779033703; - this.h1 = 3144134277; - this.h2 = 1013904242; - this.h3 = 2773480762; - this.h4 = 1359893119; - this.h5 = 2600822924; - this.h6 = 528734635; - this.h7 = 1541459225; - } - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; - this.is224 = is224; } -var HEX_CHARS, EXTRA, SHIFT, K, blocks, sha256 = (...strings) => { - return new Sha256(false, true).update(strings.join("")).hex(); -}; -var init_hash = __esm(() => { - HEX_CHARS = "0123456789abcdef".split(""); - EXTRA = [ - -2147483648, - 8388608, - 32768, - 128 - ]; - SHIFT = [ - 24, - 16, - 8, - 0 - ]; - K = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]; - blocks = []; - Sha256.prototype.update = function(message) { - if (this.finalized) - return; - var notString, type = typeof message; - if (type !== "string") { - if (type === "object") { - if (message === null) - throw new Error(ERROR); - else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) - message = new Uint8Array(message); - else if (!Array.isArray(message)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) - throw new Error(ERROR); - } - } else - throw new Error(ERROR); - notString = true; - } - var code, index = 0, i, length = message.length, blocks2 = this.blocks; - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks2[0] = this.block; - this.block = blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; - } - if (notString) - for (i = this.start;index < length && i < 64; ++index) - blocks2[i >>> 2] |= message[index] << SHIFT[i++ & 3]; - else - for (i = this.start;index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 128) - blocks2[i >>> 2] |= code << SHIFT[i++ & 3]; - else if (code < 2048) { - blocks2[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else if (code < 55296 || code >= 57344) { - blocks2[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else { - code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); - blocks2[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } - } - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks2[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; - } else - this.start = i; - } - if (this.bytes > 4294967295) { - this.hBytes += this.bytes / 4294967296 << 0; - this.bytes = this.bytes % 4294967296; - } - return this; - }; - Sha256.prototype.finalize = function() { - if (this.finalized) - return; - this.finalized = true; - var blocks2 = this.blocks, i = this.lastByteIndex; - blocks2[16] = this.block; - blocks2[i >>> 2] |= EXTRA[i & 3]; - this.block = blocks2[16]; - if (i >= 56) { - if (!this.hashed) - this.hash(); - blocks2[0] = this.block; - blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; - } - blocks2[14] = this.hBytes << 3 | this.bytes >>> 29; - blocks2[15] = this.bytes << 3; - this.hash(); - }; - Sha256.prototype.hash = function() { - var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f3 = this.h5, g = this.h6, h = this.h7, blocks2 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; - for (j = 16;j < 64; ++j) { - t1 = blocks2[j - 15]; - s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; - t1 = blocks2[j - 2]; - s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - blocks2[j] = blocks2[j - 16] + s0 + blocks2[j - 7] + s1 << 0; - } - bc = b & c; - for (j = 0;j < 64; j += 4) { - if (this.first) { - if (this.is224) { - ab = 300032; - t1 = blocks2[0] - 1413257819; - h = t1 - 150054599 << 0; - d = t1 + 24177077 << 0; - } else { - ab = 704751109; - t1 = blocks2[0] - 210244248; - h = t1 - 1521486534 << 0; - d = t1 + 143694565 << 0; - } - this.first = false; - } else { - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ab = a & b; - maj = ab ^ a & c ^ bc; - ch = e & f3 ^ ~e & g; - t1 = h + s1 + ch + K[j] + blocks2[j]; - t2 = s0 + maj; - h = d + t1 << 0; - d = t1 + t2 << 0; - } - s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); - s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); - da = d & a; - maj = da ^ d & b ^ ab; - ch = g & h ^ ~g & e; - t1 = f3 + s1 + ch + K[j + 1] + blocks2[j + 1]; - t2 = s0 + maj; - g = c + t1 << 0; - c = t1 + t2 << 0; - s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); - s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); - cd = c & d; - maj = cd ^ c & a ^ da; - ch = f3 & g ^ ~f3 & h; - t1 = e + s1 + ch + K[j + 2] + blocks2[j + 2]; - t2 = s0 + maj; - f3 = b + t1 << 0; - b = t1 + t2 << 0; - s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); - s1 = (f3 >>> 6 | f3 << 26) ^ (f3 >>> 11 | f3 << 21) ^ (f3 >>> 25 | f3 << 7); - bc = b & c; - maj = bc ^ b & d ^ cd; - ch = f3 & g ^ ~f3 & h; - t1 = e + s1 + ch + K[j + 3] + blocks2[j + 3]; - t2 = s0 + maj; - e = a + t1 << 0; - a = t1 + t2 << 0; - this.chromeBugWorkAround = true; - } - this.h0 = this.h0 + a << 0; - this.h1 = this.h1 + b << 0; - this.h2 = this.h2 + c << 0; - this.h3 = this.h3 + d << 0; - this.h4 = this.h4 + e << 0; - this.h5 = this.h5 + f3 << 0; - this.h6 = this.h6 + g << 0; - this.h7 = this.h7 + h << 0; - }; - Sha256.prototype.hex = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var hex3 = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; - if (!this.is224) - hex3 += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; - return hex3; - }; - Sha256.prototype.toString = Sha256.prototype.hex; - Sha256.prototype.digest = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var arr2 = [ - h0 >>> 24 & 255, - h0 >>> 16 & 255, - h0 >>> 8 & 255, - h0 & 255, - h1 >>> 24 & 255, - h1 >>> 16 & 255, - h1 >>> 8 & 255, - h1 & 255, - h2 >>> 24 & 255, - h2 >>> 16 & 255, - h2 >>> 8 & 255, - h2 & 255, - h3 >>> 24 & 255, - h3 >>> 16 & 255, - h3 >>> 8 & 255, - h3 & 255, - h4 >>> 24 & 255, - h4 >>> 16 & 255, - h4 >>> 8 & 255, - h4 & 255, - h5 >>> 24 & 255, - h5 >>> 16 & 255, - h5 >>> 8 & 255, - h5 & 255, - h6 >>> 24 & 255, - h6 >>> 16 & 255, - h6 >>> 8 & 255, - h6 & 255 - ]; - if (!this.is224) - arr2.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); - return arr2; - }; - Sha256.prototype.array = Sha256.prototype.digest; - Sha256.prototype.arrayBuffer = function() { - this.finalize(); - var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); - var dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - dataView.setUint32(20, this.h5); - dataView.setUint32(24, this.h6); - if (!this.is224) - dataView.setUint32(28, this.h7); - return buffer; - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/hash.js -var hash_exports; -var init_hash2 = __esm(() => { - init_runtime2(); - init_hash(); - hash_exports = /* @__PURE__ */ __exportAll({ sha256: () => sha256 }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/caches/index.js -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== undefined) - return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message) - }; - else - return { text: storedGeneration.text }; +function _ulid2(Class3, params) { + return new Class3({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function serializeGeneration(generation) { - const serializedValue = { text: generation.text }; - if (generation.message !== undefined) - serializedValue.message = generation.message.toDict(); - return serializedValue; +function _xid2(Class3, params) { + return new Class3({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -var caches_exports, defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")), BaseCache = class { - keyEncoder = defaultHashKeyEncoder; - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } -}, GLOBAL_MAP, InMemoryCache; -var init_caches = __esm(() => { - init_runtime2(); - init_hash(); - init_hash2(); - init_utils3(); - caches_exports = /* @__PURE__ */ __exportAll({ - BaseCache: () => BaseCache, - InMemoryCache: () => InMemoryCache, - defaultHashKeyEncoder: () => defaultHashKeyEncoder, - deserializeStoredGeneration: () => deserializeStoredGeneration, - serializeGeneration: () => serializeGeneration +function _ksuid2(Class3, params) { + return new Class3({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); - GLOBAL_MAP = /* @__PURE__ */ new Map; - InMemoryCache = class InMemoryCache2 extends BaseCache { - cache; - constructor(map2) { - super(); - this.cache = map2 ?? /* @__PURE__ */ new Map; - } - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); - } - async update(prompt, llmKey, value) { - this.cache.set(this.keyEncoder(prompt, llmKey), value); - } - static global() { - return new InMemoryCache2(GLOBAL_MAP); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompt_values.js -var prompt_values_exports, BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue; -var init_prompt_values = __esm(() => { - init_runtime2(); - init_serializable(); - init_human(); - init_utils3(); - prompt_values_exports = /* @__PURE__ */ __exportAll({ - BasePromptValue: () => BasePromptValue, - ChatPromptValue: () => ChatPromptValue, - ImagePromptValue: () => ImagePromptValue, - StringPromptValue: () => StringPromptValue +} +function _ipv42(Class3, params) { + return new Class3({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); - BasePromptValue = class extends Serializable { - }; - StringPromptValue = class extends BasePromptValue { - static lc_name() { - return "StringPromptValue"; - } - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - value; - constructor(value) { - super({ value }); - this.value = value; - } - toString() { - return this.value; - } - toChatMessages() { - return [new HumanMessage(this.value)]; - } - }; - ChatPromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ChatPromptValue"; - } - messages; - constructor(fields) { - if (Array.isArray(fields)) - fields = { messages: fields }; - super(fields); - this.messages = fields.messages; - } - toString() { - return getBufferString(this.messages); - } - toChatMessages() { - return this.messages; - } - }; - ImagePromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ImagePromptValue"; - } - imageUrl; - value; - constructor(fields) { - if (!("imageUrl" in fields)) - fields = { imageUrl: fields }; - super(fields); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [new HumanMessage({ content: [{ - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url - } - }] })]; - } - }; -}); - -// ../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js -var require_base64_js = __commonJS((exports) => { - exports.byteLength = byteLength; - exports.toByteArray = toByteArray; - exports.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i = 0, len = code.length;i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - var i; - var len; - revLookup[45] = 62; - revLookup[95] = 63; - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) - validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr2 = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i2; - for (i2 = 0;i2 < len2; i2 += 4) { - tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; - arr2[curByte++] = tmp >> 16 & 255; - arr2[curByte++] = tmp >> 8 & 255; - arr2[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; - arr2[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; - arr2[curByte++] = tmp >> 8 & 255; - arr2[curByte++] = tmp & 255; - } - return arr2; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i2 = start;i2 < end; i2 += 3) { - tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength) { - parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); - } - return parts.join(""); - } -}); - -// ../../node_modules/.pnpm/js-tiktoken@1.0.21/node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js -function bytePairMerge(piece, ranks) { - let parts = Array.from({ length: piece.length }, (_, i) => ({ start: i, end: i + 1 })); - while (parts.length > 1) { - let minRank = null; - for (let i = 0;i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; } -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +function _ipv62(Class3, params) { + return new Class3({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function escapeRegex2(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +function _cidrv42(Class3, params) { + return new Class3({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "davinci-002": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "babbage-002": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-instruct-0914": - case "gpt-3.5-turbo-instruct": - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "gpt-3.5-turbo-1106": - case "gpt-35-turbo": - case "gpt-4-1106-preview": - case "gpt-4-vision-preview": - case "gpt-3.5-turbo-0125": - case "gpt-4-turbo": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-turbo-preview": - case "gpt-4-0125-preview": - case "text-embedding-ada-002": - case "text-embedding-3-small": - case "text-embedding-3-large": { - return "cl100k_base"; - } - case "gpt-4o": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - case "gpt-4o-2024-11-20": - case "gpt-4o-mini-2024-07-18": - case "gpt-4o-mini": - case "gpt-4o-search-preview": - case "gpt-4o-search-preview-2025-03-11": - case "gpt-4o-mini-search-preview": - case "gpt-4o-mini-search-preview-2025-03-11": - case "gpt-4o-audio-preview": - case "gpt-4o-audio-preview-2024-12-17": - case "gpt-4o-audio-preview-2024-10-01": - case "gpt-4o-mini-audio-preview": - case "gpt-4o-mini-audio-preview-2024-12-17": - case "o1": - case "o1-2024-12-17": - case "o1-mini": - case "o1-mini-2024-09-12": - case "o1-preview": - case "o1-preview-2024-09-12": - case "o1-pro": - case "o1-pro-2025-03-19": - case "o3": - case "o3-2025-04-16": - case "o3-mini": - case "o3-mini-2025-01-31": - case "o4-mini": - case "o4-mini-2025-04-16": - case "chatgpt-4o-latest": - case "gpt-4o-realtime": - case "gpt-4o-realtime-preview-2024-10-01": - case "gpt-4o-realtime-preview-2024-12-17": - case "gpt-4o-mini-realtime-preview": - case "gpt-4o-mini-realtime-preview-2024-12-17": - case "gpt-4.1": - case "gpt-4.1-2025-04-14": - case "gpt-4.1-mini": - case "gpt-4.1-mini-2025-04-14": - case "gpt-4.1-nano": - case "gpt-4.1-nano-2025-04-14": - case "gpt-4.5-preview": - case "gpt-4.5-preview-2025-02-27": - case "gpt-5": - case "gpt-5-2025-08-07": - case "gpt-5-nano": - case "gpt-5-nano-2025-08-07": - case "gpt-5-mini": - case "gpt-5-mini-2025-08-07": - case "gpt-5-chat-latest": { - return "o200k_base"; - } - default: - throw new Error("Unknown model"); - } +function _cidrv62(Class3, params) { + return new Class3({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -var import_base64_js, __defProp3, __defNormalProp = (obj, key, value) => (key in obj) ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}, _Tiktoken = class { - specialTokens; - inverseSpecialTokens; - patStr; - textEncoder = new TextEncoder; - textDecoder = new TextDecoder("utf-8"); - rankMap = /* @__PURE__ */ new Map; - textMap = /* @__PURE__ */ new Map; - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split(` -`).filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = import_base64_js.default.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); - } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex(Object.keys(this.specialTokens)); - const ret = []; - const allowedSpecialSet = new Set(allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial); - const disallowedSpecialSet = new Set(disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter((x) => !allowedSpecialSet.has(x)) : disallowedSpecial); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error(`The text contains a special token that is not allowed: ${specialMatch[0]}`); - } - } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match2 of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match2[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; - } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0;i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}, Tiktoken; -var init_chunk_VL2OQCWN = __esm(() => { - import_base64_js = __toESM(require_base64_js(), 1); - __defProp3 = Object.defineProperty; - Tiktoken = _Tiktoken; - __publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => escapeRegex2(i)).join("|"), "g"); +function _base642(Class3, params) { + return new Class3({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); -}); - -// ../../node_modules/.pnpm/js-tiktoken@1.0.21/node_modules/js-tiktoken/dist/lite.js -var init_lite = __esm(() => { - init_chunk_VL2OQCWN(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/tiktoken.js -async function getEncoding(encoding) { - if (!(encoding in cache)) - cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { - delete cache[encoding]; - throw e; - }); - return await cache[encoding]; } -async function encodingForModel(model) { - return getEncoding(getEncodingNameForModel(model)); +function _base64url2(Class3, params) { + return new Class3({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams2(params) + }); } -var tiktoken_exports, cache, caller; -var init_tiktoken = __esm(() => { - init_runtime2(); - init_async_caller2(); - init_lite(); - tiktoken_exports = /* @__PURE__ */ __exportAll({ - encodingForModel: () => encodingForModel, - getEncoding: () => getEncoding +function _e1642(Class3, params) { + return new Class3({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); - cache = {}; - caller = /* @__PURE__ */ new AsyncCaller2({}); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/base.js -function isOpenAITool(tool) { - if (typeof tool !== "object" || !tool) - return false; - if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) - return true; - return false; } -var base_exports3, getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-5")) - return "gpt-5"; - if (modelName.startsWith("gpt-3.5-turbo-16k")) - return "gpt-3.5-turbo-16k"; - if (modelName.startsWith("gpt-3.5-turbo-")) - return "gpt-3.5-turbo"; - if (modelName.startsWith("gpt-4-32k")) - return "gpt-4-32k"; - if (modelName.startsWith("gpt-4-")) - return "gpt-4"; - if (modelName.startsWith("gpt-4o")) - return "gpt-4o"; - return modelName; -}, getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": - return 8191; - default: - return 2046; - } -}, getModelContextSize = (modelName) => { - switch (getModelNameForTiktoken(modelName)) { - case "gpt-5": - case "gpt-5-turbo": - case "gpt-5-turbo-preview": - return 400000; - case "gpt-4o": - case "gpt-4o-mini": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - return 128000; - case "gpt-4-turbo": - case "gpt-4-turbo-preview": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-0125-preview": - case "gpt-4-1106-preview": - return 128000; - case "gpt-4-32k": - case "gpt-4-32k-0314": - case "gpt-4-32k-0613": - return 32768; - case "gpt-4": - case "gpt-4-0314": - case "gpt-4-0613": - return 8192; - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-16k-0613": - return 16384; - case "gpt-3.5-turbo": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-1106": - case "gpt-3.5-turbo-0125": - return 4096; - case "text-davinci-003": - case "text-davinci-002": - return 4097; - case "text-davinci-001": - return 2049; - case "text-curie-001": - case "text-babbage-001": - case "text-ada-001": - return 2048; - case "code-davinci-002": - case "code-davinci-001": - return 8000; - case "code-cushman-001": - return 2048; - case "claude-3-5-sonnet-20241022": - case "claude-3-5-sonnet-20240620": - case "claude-3-opus-20240229": - case "claude-3-sonnet-20240229": - case "claude-3-haiku-20240307": - case "claude-2.1": - return 200000; - case "claude-2.0": - case "claude-instant-1.2": - return 1e5; - case "gemini-1.5-pro": - case "gemini-1.5-pro-latest": - case "gemini-1.5-flash": - case "gemini-1.5-flash-latest": - return 1e6; - case "gemini-pro": - case "gemini-pro-vision": - return 32768; - default: - return 4097; - } -}, calculateMaxTokens = async ({ prompt, modelName }) => { - let numTokens; - try { - numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; - } catch { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - numTokens = Math.ceil(prompt.length / 4); - } - return getModelContextSize(modelName) - numTokens; -}, getVerbosity = () => false, BaseLangChain, BaseLanguageModel; -var init_base5 = __esm(() => { - init_runtime2(); - init_utils3(); - init_caches(); - init_async_caller2(); - init_base4(); - init_prompt_values(); - init_tiktoken(); - base_exports3 = /* @__PURE__ */ __exportAll({ - BaseLangChain: () => BaseLangChain, - BaseLanguageModel: () => BaseLanguageModel, - calculateMaxTokens: () => calculateMaxTokens, - getEmbeddingContextSize: () => getEmbeddingContextSize, - getModelContextSize: () => getModelContextSize, - getModelNameForTiktoken: () => getModelNameForTiktoken, - isOpenAITool: () => isOpenAITool +function _jwt2(Class3, params) { + return new Class3({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams2(params) }); - BaseLangChain = class extends Runnable { - verbose; - callbacks; - tags; - metadata; - get lc_attributes() { - return { - callbacks: undefined, - verbose: undefined - }; - } - constructor(params) { - super(params); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; - this._addVersion("@langchain/core", "1.1.46"); - } - _addVersion(pkg, version3) { - const existing = this.metadata?.versions; - this.metadata = { - ...this.metadata, - versions: { - ...typeof existing === "object" && existing !== null ? existing : {}, - [pkg]: version3 - } - }; - } - }; - BaseLanguageModel = class extends BaseLangChain { - get callKeys() { - return [ - "stop", - "timeout", - "signal", - "tags", - "metadata", - "callbacks" - ]; - } - caller; - cache; - constructor({ callbacks, callbackManager, ...params }) { - const { cache: cache2, ...rest } = params; - super({ - callbacks: callbacks ?? callbackManager, - ...rest - }); - if (typeof cache2 === "object") - this.cache = cache2; - else if (cache2) - this.cache = InMemoryCache.global(); - else - this.cache = undefined; - this.caller = new AsyncCaller2(params ?? {}); - } - _encoding; - async getNumTokens(content) { - let textContent; - if (typeof content === "string") - textContent = content; - else - textContent = content.map((item) => { - if (typeof item === "string") - return item; - if (item.type === "text" && "text" in item) - return item.text; - return ""; - }).join(""); - let numTokens = Math.ceil(textContent.length / 4); - if (!this._encoding) - try { - this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); - } catch (error51) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error51); - } - if (this._encoding) - try { - numTokens = this._encoding.encode(textContent).length; - } catch (error51) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error51); - } - return numTokens; - } - static _convertInputToPromptValue(input) { - if (typeof input === "string") - return new StringPromptValue(input); - else if (Array.isArray(input)) - return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); - else - return input; - } - _identifyingParams() { - return {}; - } - _getSerializedCacheKeyParametersForCall({ config: config2, ...callOptions }) { - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType() - }; - return Object.entries(params).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); - } - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType() - }; - } - static async deserialize(_data) { - throw new Error("Use .toJSON() instead"); - } - get profile() { - return {}; - } - _filterInvocationParamsForTracing(params) { - const { tools, functions, messages, response_format, ...rest } = params; - return rest; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/utils.js -function castStandardMessageContent(message) { - const Cls = message.constructor; - return new Cls({ - ...message, - content: message.contentBlocks, - response_metadata: { - ...message.response_metadata, - output_version: "v1" - } +} +function _isoDateTime2(Class3, params) { + return new Class3({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams2(params) }); } -var iife3 = (fn) => fn(); -var init_utils5 = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/passthrough.js -var RunnablePassthrough; -var init_passthrough = __esm(() => { - init_config(); - init_stream(); - init_base4(); - RunnablePassthrough = class extends Runnable { - static lc_name() { - return "RunnablePassthrough"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - func; - constructor(fields) { - super(fields); - if (fields) - this.func = fields.func; - } - async invoke(input, options) { - const config2 = ensureConfig(options); - if (this.func) - await this.func(input, config2); - return this._callWithConfig((input2) => Promise.resolve(input2), input, config2); - } - async* transform(generator, options) { - const config2 = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config2)) { - yield chunk; - if (finalOutputSupported) - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = undefined; - finalOutputSupported = false; - } - } - if (this.func && finalOutput !== undefined) - await this.func(finalOutput, config2); - } - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/router.js -var RouterRunnable; -var init_router = __esm(() => { - init_config(); - init_base4(); - RouterRunnable = class extends Runnable { - static lc_name() { - return "RouterRunnable"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnables; - constructor(fields) { - super(fields); - this.runnables = fields.runnables; - } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) - throw new Error(`No runnable associated with key "${key}".`); - return runnable.invoke(actualInput, ensureConfig(options)); +function _isoDate2(Class3, params) { + return new Class3({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams2(params) + }); +} +function _isoTime2(Class3, params) { + return new Class3({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams2(params) + }); +} +function _isoDuration2(Class3, params) { + return new Class3({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams2(params) + }); +} +function _number2(Class3, params) { + return new Class3({ + type: "number", + checks: [], + ...normalizeParams2(params) + }); +} +function _coercedNumber2(Class3, params) { + return new Class3({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams2(params) + }); +} +function _int2(Class3, params) { + return new Class3({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams2(params) + }); +} +function _float322(Class3, params) { + return new Class3({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams2(params) + }); +} +function _float642(Class3, params) { + return new Class3({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams2(params) + }); +} +function _int322(Class3, params) { + return new Class3({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams2(params) + }); +} +function _uint322(Class3, params) { + return new Class3({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams2(params) + }); +} +function _boolean2(Class3, params) { + return new Class3({ + type: "boolean", + ...normalizeParams2(params) + }); +} +function _coercedBoolean2(Class3, params) { + return new Class3({ + type: "boolean", + coerce: true, + ...normalizeParams2(params) + }); +} +function _bigint2(Class3, params) { + return new Class3({ + type: "bigint", + ...normalizeParams2(params) + }); +} +function _coercedBigint2(Class3, params) { + return new Class3({ + type: "bigint", + coerce: true, + ...normalizeParams2(params) + }); +} +function _int642(Class3, params) { + return new Class3({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams2(params) + }); +} +function _uint642(Class3, params) { + return new Class3({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams2(params) + }); +} +function _symbol2(Class3, params) { + return new Class3({ + type: "symbol", + ...normalizeParams2(params) + }); +} +function _undefined5(Class3, params) { + return new Class3({ + type: "undefined", + ...normalizeParams2(params) + }); +} +function _null5(Class3, params) { + return new Class3({ + type: "null", + ...normalizeParams2(params) + }); +} +function _any2(Class3) { + return new Class3({ + type: "any" + }); +} +function _unknown2(Class3) { + return new Class3({ + type: "unknown" + }); +} +function _never2(Class3, params) { + return new Class3({ + type: "never", + ...normalizeParams2(params) + }); +} +function _void3(Class3, params) { + return new Class3({ + type: "void", + ...normalizeParams2(params) + }); +} +function _date2(Class3, params) { + return new Class3({ + type: "date", + ...normalizeParams2(params) + }); +} +function _coercedDate2(Class3, params) { + return new Class3({ + type: "date", + coerce: true, + ...normalizeParams2(params) + }); +} +function _nan2(Class3, params) { + return new Class3({ + type: "nan", + ...normalizeParams2(params) + }); +} +function _lt2(value, params) { + return new $ZodCheckLessThan2({ + check: "less_than", + ...normalizeParams2(params), + value, + inclusive: false + }); +} +function _lte2(value, params) { + return new $ZodCheckLessThan2({ + check: "less_than", + ...normalizeParams2(params), + value, + inclusive: true + }); +} +function _gt2(value, params) { + return new $ZodCheckGreaterThan2({ + check: "greater_than", + ...normalizeParams2(params), + value, + inclusive: false + }); +} +function _gte2(value, params) { + return new $ZodCheckGreaterThan2({ + check: "greater_than", + ...normalizeParams2(params), + value, + inclusive: true + }); +} +function _positive2(params) { + return _gt2(0, params); +} +function _negative2(params) { + return _lt2(0, params); +} +function _nonpositive2(params) { + return _lte2(0, params); +} +function _nonnegative2(params) { + return _gte2(0, params); +} +function _multipleOf2(value, params) { + return new $ZodCheckMultipleOf2({ + check: "multiple_of", + ...normalizeParams2(params), + value + }); +} +function _maxSize2(maximum, params) { + return new $ZodCheckMaxSize2({ + check: "max_size", + ...normalizeParams2(params), + maximum + }); +} +function _minSize2(minimum, params) { + return new $ZodCheckMinSize2({ + check: "min_size", + ...normalizeParams2(params), + minimum + }); +} +function _size2(size, params) { + return new $ZodCheckSizeEquals2({ + check: "size_equals", + ...normalizeParams2(params), + size + }); +} +function _maxLength2(maximum, params) { + const ch = new $ZodCheckMaxLength2({ + check: "max_length", + ...normalizeParams2(params), + maximum + }); + return ch; +} +function _minLength2(minimum, params) { + return new $ZodCheckMinLength2({ + check: "min_length", + ...normalizeParams2(params), + minimum + }); +} +function _length2(length, params) { + return new $ZodCheckLengthEquals2({ + check: "length_equals", + ...normalizeParams2(params), + length + }); +} +function _regex2(pattern, params) { + return new $ZodCheckRegex2({ + check: "string_format", + format: "regex", + ...normalizeParams2(params), + pattern + }); +} +function _lowercase2(params) { + return new $ZodCheckLowerCase2({ + check: "string_format", + format: "lowercase", + ...normalizeParams2(params) + }); +} +function _uppercase2(params) { + return new $ZodCheckUpperCase2({ + check: "string_format", + format: "uppercase", + ...normalizeParams2(params) + }); +} +function _includes2(includes, params) { + return new $ZodCheckIncludes2({ + check: "string_format", + format: "includes", + ...normalizeParams2(params), + includes + }); +} +function _startsWith2(prefix, params) { + return new $ZodCheckStartsWith2({ + check: "string_format", + format: "starts_with", + ...normalizeParams2(params), + prefix + }); +} +function _endsWith2(suffix, params) { + return new $ZodCheckEndsWith2({ + check: "string_format", + format: "ends_with", + ...normalizeParams2(params), + suffix + }); +} +function _property2(property, schema, params) { + return new $ZodCheckProperty2({ + check: "property", + property, + schema, + ...normalizeParams2(params) + }); +} +function _mime2(types, params) { + return new $ZodCheckMimeType2({ + check: "mime_type", + mime: types, + ...normalizeParams2(params) + }); +} +function _overwrite2(tx) { + return new $ZodCheckOverwrite2({ + check: "overwrite", + tx + }); +} +function _normalize2(form) { + return _overwrite2((input) => input.normalize(form)); +} +function _trim2() { + return _overwrite2((input) => input.trim()); +} +function _toLowerCase2() { + return _overwrite2((input) => input.toLowerCase()); +} +function _toUpperCase2() { + return _overwrite2((input) => input.toUpperCase()); +} +function _array2(Class3, element, params) { + return new Class3({ + type: "array", + element, + ...normalizeParams2(params) + }); +} +function _union2(Class3, options, params) { + return new Class3({ + type: "union", + options, + ...normalizeParams2(params) + }); +} +function _discriminatedUnion2(Class3, discriminator, options, params) { + return new Class3({ + type: "union", + options, + discriminator, + ...normalizeParams2(params) + }); +} +function _intersection2(Class3, left, right) { + return new Class3({ + type: "intersection", + left, + right + }); +} +function _tuple2(Class3, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType2; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class3({ + type: "tuple", + items, + rest, + ...normalizeParams2(params) + }); +} +function _record2(Class3, keyType, valueType, params) { + return new Class3({ + type: "record", + keyType, + valueType, + ...normalizeParams2(params) + }); +} +function _map2(Class3, keyType, valueType, params) { + return new Class3({ + type: "map", + keyType, + valueType, + ...normalizeParams2(params) + }); +} +function _set2(Class3, valueType, params) { + return new Class3({ + type: "set", + valueType, + ...normalizeParams2(params) + }); +} +function _enum3(Class3, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new Class3({ + type: "enum", + entries, + ...normalizeParams2(params) + }); +} +function _nativeEnum2(Class3, entries, params) { + return new Class3({ + type: "enum", + entries, + ...normalizeParams2(params) + }); +} +function _literal2(Class3, value, params) { + return new Class3({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams2(params) + }); +} +function _file2(Class3, params) { + return new Class3({ + type: "file", + ...normalizeParams2(params) + }); +} +function _transform2(Class3, fn) { + return new Class3({ + type: "transform", + transform: fn + }); +} +function _optional2(Class3, innerType) { + return new Class3({ + type: "optional", + innerType + }); +} +function _nullable2(Class3, innerType) { + return new Class3({ + type: "nullable", + innerType + }); +} +function _default3(Class3, innerType, defaultValue) { + return new Class3({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - if (keys.find((key) => this.runnables[key] === undefined) !== undefined) - throw new Error(`One or more keys do not have a corresponding runnable.`); - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; - const batchResults = []; - for (let i = 0;i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i2) => runnables[i2].invoke(actualInput, optionsList[i2])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); + }); +} +function _nonoptional2(Class3, innerType, params) { + return new Class3({ + type: "nonoptional", + innerType, + ...normalizeParams2(params) + }); +} +function _success2(Class3, innerType) { + return new Class3({ + type: "success", + innerType + }); +} +function _catch3(Class3, innerType, catchValue) { + return new Class3({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +function _pipe2(Class3, in_, out) { + return new Class3({ + type: "pipe", + in: in_, + out + }); +} +function _readonly2(Class3, innerType) { + return new Class3({ + type: "readonly", + innerType + }); +} +function _templateLiteral2(Class3, parts, params) { + return new Class3({ + type: "template_literal", + parts, + ...normalizeParams2(params) + }); +} +function _lazy2(Class3, getter) { + return new Class3({ + type: "lazy", + getter + }); +} +function _promise2(Class3, innerType) { + return new Class3({ + type: "promise", + innerType + }); +} +function _custom2(Class3, fn, _params) { + const norm = normalizeParams2(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class3({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; +} +function _refine2(Class3, fn, _params) { + const schema = new Class3({ + type: "custom", + check: "custom", + fn, + ...normalizeParams2(_params) + }); + return schema; +} +function _stringbool2(Classes, _params) { + const params = normalizeParams2(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Pipe = Classes.Pipe ?? $ZodPipe2; + const _Boolean = Classes.Boolean ?? $ZodBoolean2; + const _String = Classes.String ?? $ZodString2; + const _Transform = Classes.Transform ?? $ZodTransform2; + const tx = new _Transform({ + type: "transform", + transform: (input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: tx + }); + return {}; } - return batchResults.flat(); - } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) - throw new Error(`No runnable associated with key "${key}".`); - return runnable.stream(actualInput, options); - } + }, + error: params.error + }); + const innerPipe = new _Pipe({ + type: "pipe", + in: new _String({ type: "string", error: params.error }), + out: tx, + error: params.error + }); + const outerPipe = new _Pipe({ + type: "pipe", + in: innerPipe, + out: new _Boolean({ + type: "boolean", + error: params.error + }), + error: params.error + }); + return outerPipe; +} +function _stringFormat2(Class3, format, fnOrRegex, _params = {}) { + const params = normalizeParams2(_params); + const def = { + ...normalizeParams2(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class3(def); + return inst; +} +var TimePrecision2; +var init_api2 = __esm(() => { + init_checks3(); + init_schemas3(); + init_util2(); + TimePrecision2 = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/branch.js -var RunnableBranch; -var init_branch = __esm(() => { - init_config(); - init_stream(); - init_base4(); - RunnableBranch = class extends Runnable { - static lc_name() { - return "RunnableBranch"; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/function.js +class $ZodFunction2 { + constructor(def) { + this._def = def; + this.def = def; + } + implement(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - default; - branches; - constructor(fields) { - super(fields); - this.branches = fields.branches; - this.default = fields.default; + const impl = (...args) => { + const parsedArgs = this._def.input ? parse9(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = func(...parsedArgs); + return this._def.output ? parse9(this._def.output, output, undefined, { callee: impl }) : output; + }; + return impl; + } + implementAsync(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); } - static from(branches) { - if (branches.length < 1) - throw new Error("RunnableBranch requires at least one branch"); - const coercedBranches = branches.slice(0, -1).map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch + const impl = async (...args) => { + const parsedArgs = this._def.input ? await parseAsync3(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = await func(...parsedArgs); + return this._def.output ? parseAsync3(this._def.output, output, undefined, { callee: impl }) : output; + }; + return impl; + } + input(...args) { + const F = this.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple2({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: this._def.output }); } - async _invoke(input, config2, runManager) { - let result; - for (let i = 0;i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - if (await condition.invoke(input, patchConfig(config2, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { - result = await branchRunnable.invoke(input, patchConfig(config2, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - break; - } + return new F({ + type: "function", + input: args[0], + output: this._def.output + }); + } + output(output) { + const F = this.constructor; + return new F({ + type: "function", + input: this._def.input, + output + }); + } +} +function _function2(params) { + return new $ZodFunction2({ + type: "function", + input: Array.isArray(params?.input) ? _tuple2($ZodTuple2, params?.input) : params?.input ?? _array2($ZodArray2, _unknown2($ZodUnknown2)), + output: params?.output ?? _unknown2($ZodUnknown2) + }); +} +var init_function2 = __esm(() => { + init_api2(); + init_parse5(); + init_schemas3(); + init_schemas3(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js +class JSONSchemaGenerator2 { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? globalRegistry2; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => {}); + this.io = params?.io ?? "output"; + this.seen = new Map; + } + process(schema, _params = { path: [], schemaPath: [] }) { + var _a3; + const def = schema._zod.def; + const formatMap2 = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + }; + const seen = this.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; } - if (!result) - result = await this.default.invoke(input, patchConfig(config2, { callbacks: runManager?.getChild("branch:default") })); - return result; - } - async invoke(input, config2 = {}) { - return this._callWithConfig(this._invoke, input, config2); + return seen.schema; } - async* _streamIterator(input, config2) { - const runManager = await (await getCallbackManagerForConfig(config2))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config2?.runId, undefined, undefined, undefined, config2?.runName); - let finalOutput; - let finalOutputSupported = true; - let stream2; - try { - for (let i = 0;i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - if (await condition.invoke(input, patchConfig(config2, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { - stream2 = await branchRunnable.stream(input, patchConfig(config2, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - for await (const chunk of stream2) { - yield chunk; - if (finalOutputSupported) - if (finalOutput === undefined) - finalOutput = chunk; + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + this.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + const parent = schema._zod.parent; + if (parent) { + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; + } else { + const _json = result.schema; + switch (def.type) { + case "string": { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = formatMap2[format] ?? format; + if (json2.format === "") + delete json2.format; + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex) => ({ + ...this.target === "draft-7" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + break; + } + case "number": { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") + json2.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; else - try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = undefined; - finalOutputSupported = false; - } + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json2.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; break; } - } - if (stream2 === undefined) { - stream2 = await this.default.stream(input, patchConfig(config2, { callbacks: runManager?.getChild("branch:default") })); - for await (const chunk of stream2) { - yield chunk; - if (finalOutputSupported) - if (finalOutput === undefined) - finalOutput = chunk; - else - try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = undefined; - finalOutputSupported = false; - } + case "boolean": { + const json2 = _json; + json2.type = "boolean"; + break; } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/history.js -var RunnableWithMessageHistory; -var init_history = __esm(() => { - init_base(); - init_ai(); - init_human(); - init_base4(); - init_messages(); - init_passthrough(); - RunnableWithMessageHistory = class extends RunnableBinding { - runnable; - inputMessagesKey; - outputMessagesKey; - historyMessagesKey; - getMessageHistory; - constructor(fields) { - let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); - const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; - if (messagesKey) - historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); - const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run2, config3) => this._exitHistory(run2, config3 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); - const config2 = fields.config ?? {}; - super({ - ...fields, - config: config2, - bound - }); - this.runnable = fields.runnable; - this.getMessageHistory = fields.getMessageHistory; - this.inputMessagesKey = fields.inputMessagesKey; - this.outputMessagesKey = fields.outputMessagesKey; - this.historyMessagesKey = fields.historyMessagesKey; - } - _getInputMessages(inputValue) { - let parsedInputValue; - if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { - let key; - if (this.inputMessagesKey) - key = this.inputMessagesKey; - else if (Object.keys(inputValue).length === 1) - key = Object.keys(inputValue)[0]; - else - key = "input"; - if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) - parsedInputValue = inputValue[key][0]; - else - parsedInputValue = inputValue[key]; - } else - parsedInputValue = inputValue; - if (typeof parsedInputValue === "string") - return [new HumanMessage(parsedInputValue)]; - else if (Array.isArray(parsedInputValue)) - return parsedInputValue; - else if (isBaseMessage(parsedInputValue)) - return [parsedInputValue]; - else - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. -Got ${JSON.stringify(parsedInputValue, null, 2)}`); - } - _getOutputMessages(outputValue) { - let parsedOutputValue; - if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { - let key; - if (this.outputMessagesKey !== undefined) - key = this.outputMessagesKey; - else if (Object.keys(outputValue).length === 1) - key = Object.keys(outputValue)[0]; - else - key = "output"; - if (outputValue.generations !== undefined) - parsedOutputValue = outputValue.generations[0][0].message; - else - parsedOutputValue = outputValue[key]; - } else - parsedOutputValue = outputValue; - if (typeof parsedOutputValue === "string") - return [new AIMessage(parsedOutputValue)]; - else if (Array.isArray(parsedOutputValue)) - return parsedOutputValue; - else if (isBaseMessage(parsedOutputValue)) - return [parsedOutputValue]; - else - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); - } - async _enterHistory(input, kwargs) { - const messages = await (kwargs?.configurable?.messageHistory).getMessages(); - if (this.historyMessagesKey === undefined) - return messages.concat(this._getInputMessages(input)); - return messages; - } - async _exitHistory(run2, config2) { - const history = config2.configurable?.messageHistory; - let inputs; - if (Array.isArray(run2.inputs) && Array.isArray(run2.inputs[0])) - inputs = run2.inputs[0]; - else - inputs = run2.inputs; - let inputMessages = this._getInputMessages(inputs); - if (this.historyMessagesKey === undefined) { - const existingMessages = await history.getMessages(); - inputMessages = inputMessages.slice(existingMessages.length); - } - const outputValue = run2.outputs; - if (!outputValue) - throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run2, null, 2)}`); - const outputMessages = this._getOutputMessages(outputValue); - await history.addMessages([...inputMessages, ...outputMessages]); - } - async _mergeConfig(...configs) { - const config2 = await super._mergeConfig(...configs); - if (!config2.configurable || !config2.configurable.sessionId) { - const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; - throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream() -eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify({ configurable: { sessionId: "123" } })})`); - } - const { sessionId } = config2.configurable; - config2.configurable.messageHistory = await this.getMessageHistory(sessionId); - return config2; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/runnables/index.js -var runnables_exports; -var init_runnables = __esm(() => { - init_runtime2(); - init_config(); - init_signal(); - init_base4(); - init_passthrough(); - init_router(); - init_branch(); - init_history(); - runnables_exports = /* @__PURE__ */ __exportAll({ - RouterRunnable: () => RouterRunnable, - Runnable: () => Runnable, - RunnableAssign: () => RunnableAssign, - RunnableBinding: () => RunnableBinding, - RunnableBranch: () => RunnableBranch, - RunnableEach: () => RunnableEach, - RunnableLambda: () => RunnableLambda, - RunnableMap: () => RunnableMap, - RunnableParallel: () => RunnableParallel, - RunnablePassthrough: () => RunnablePassthrough, - RunnablePick: () => RunnablePick, - RunnableRetry: () => RunnableRetry, - RunnableSequence: () => RunnableSequence, - RunnableToolLike: () => RunnableToolLike, - RunnableWithFallbacks: () => RunnableWithFallbacks, - RunnableWithMessageHistory: () => RunnableWithMessageHistory, - _coerceToRunnable: () => _coerceToRunnable, - ensureConfig: () => ensureConfig, - getCallbackManagerForConfig: () => getCallbackManagerForConfig, - mergeConfigs: () => mergeConfigs, - patchConfig: () => patchConfig, - pickRunnableConfigKeys: () => pickRunnableConfigKeys, - raceWithSignal: () => raceWithSignal - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/base.js -var BaseLLMOutputParser, BaseOutputParser, OutputParserException; -var init_base6 = __esm(() => { - init_errors3(); - init_base4(); - init_runnables(); - BaseLLMOutputParser = class extends Runnable { - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); - } - async invoke(input, options) { - if (typeof input === "string") - return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { - ...options, - runType: "parser" - }); - else - return this._callWithConfig(async (input2, options2) => this.parseResult([{ - message: input2, - text: this._baseMessageToString(input2) - }], options2?.callbacks), input, { - ...options, - runType: "parser" - }); - } - }; - BaseOutputParser = class extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - _type() { - throw new Error("_type not implemented"); - } - }; - OutputParserException = class extends Error { - llmOutput; - observation; - sendToLLM; - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === undefined || llmOutput === undefined) - throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "undefined": { + if (this.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "never": { + _json.not = {}; + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json2 = _json; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json2 = _json; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (this.io === "input") { + return v.optin === undefined; + } else { + return v.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (this.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + break; + } + case "union": { + const json2 = _json; + json2.anyOf = def.options.map((x, i) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i] + })); + break; + } + case "intersection": { + const json2 = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => ("allOf" in val) && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b) ? b.allOf : [b] + ]; + json2.allOf = allOf; + break; + } + case "tuple": { + const json2 = _json; + json2.type = "array"; + const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); + if (this.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + } else { + json2.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + if (this.target === "draft-2020-12") { + json2.items = rest; + } else { + json2.additionalItems = rest; + } + } + if (def.rest) { + json2.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + break; + } + case "record": { + const json2 = _json; + json2.type = "object"; + json2.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json2.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"] + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json2 = _json; + const values = getEnumValues2(def.entries); + if (values.every((v) => typeof v === "number")) + json2.type = "number"; + if (values.every((v) => typeof v === "string")) + json2.type = "string"; + json2.enum = values; + break; + } + case "literal": { + const json2 = _json; + const vals = []; + for (const val of def.values) { + if (val === undefined) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else {} + } else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) {} else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + json2.const = val; + } else { + if (vals.every((v) => typeof v === "number")) + json2.type = "number"; + if (vals.every((v) => typeof v === "string")) + json2.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json2.type = "string"; + if (vals.every((v) => v === null)) + json2.type = "null"; + json2.enum = vals; + } + break; + } + case "file": { + const json2 = _json; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file2.minLength = minimum; + if (maximum !== undefined) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(json2, file2); + } else { + json2.anyOf = mime.map((m) => { + const mFile = { ...file2, contentMediaType: m }; + return mFile; + }); + } + } else { + Object.assign(json2, file2); + } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json2 = _json; + json2.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json2 = _json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json2.type = "string"; + json2.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: {} + } } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/transform.js -var BaseTransformOutputParser, BaseCumulativeTransformOutputParser; -var init_transform = __esm(() => { - init_base(); - init_utils3(); - init_outputs(); - init_base6(); - init_esm(); - BaseTransformOutputParser = class extends BaseOutputParser { - async* _transform(inputGenerator) { - for await (const chunk of inputGenerator) - if (typeof chunk === "string") - yield this.parseResult([{ text: chunk }]); - else - yield this.parseResult([{ - message: chunk, - text: this._baseMessageToString(chunk) - }]); - } - async* transform(inputGenerator, options) { - yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { - ...options, - runType: "parser" - }); } - }; - BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { - diff = false; - constructor(fields) { - super(fields); - this.diff = fields?.diff ?? this.diff; + const meta3 = this.metadataRegistry.get(schema); + if (meta3) + Object.assign(result.schema, meta3); + if (this.io === "input" && isTransforming2(schema)) { + delete result.schema.examples; + delete result.schema.default; } - async* _transform(inputGenerator) { - let prevParsed; - let accGen; - for await (const chunk of inputGenerator) { - if (typeof chunk !== "string" && typeof chunk.content !== "string") - throw new Error("Cannot handle non-string output."); - let chunkGen; - if (isBaseMessageChunk(chunk)) { - if (typeof chunk.content !== "string") - throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: chunk, - text: chunk.content - }); - } else if (isBaseMessage(chunk)) { - if (typeof chunk.content !== "string") - throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: convertToChunk(chunk), - text: chunk.content - }); - } else - chunkGen = new GenerationChunk({ text: chunk }); - if (accGen === undefined) - accGen = chunkGen; - else - accGen = accGen.concat(chunkGen); - const parsed = await this.parsePartialResult([accGen]); - if (parsed !== undefined && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { - if (this.diff) - yield this._diff(prevParsed, parsed); - else - yield parsed; - prevParsed = parsed; + if (this.io === "input" && result.schema._prefault) + (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault); + delete result.schema._prefault; + const _result = this.seen.get(schema); + return _result.schema; + } + emit(schema, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + external: _params?.external ?? undefined + }; + const root = this.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const makeURI = (entry) => { + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; + const uriGenerator = params.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } - } - getFormatInstructions() { - return ""; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/json_patch.js -var json_patch_exports; -var init_json_patch = __esm(() => { - init_runtime2(); - init_core3(); - init_duplex(); - init_fast_json_patch(); - json_patch_exports = /* @__PURE__ */ __exportAll({ - applyPatch: () => applyPatch, - compare: () => compare - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/json.js -var JsonOutputParser; -var init_json2 = __esm(() => { - init_json(); - init_duplex(); - init_transform(); - init_json_patch(); - JsonOutputParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputParser"; - } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - _concatOutputChunks(first, second) { - if (this.diff) - return super._concatOutputChunks(first, second); - return second; - } - _diff(prev, next) { - if (!next) + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { return; - if (!prev) - return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); - } - async parsePartialResult(generations) { - return parseJsonMarkdown(generations[0].text); - } - async parse(text) { - return parseJsonMarkdown(text, JSON.parse); - } - getFormatInstructions() { - return ""; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (params.cycles === "throw") { + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } } - _baseMessageToString(message) { - return message.text; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + continue; + } + } } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/standard_schema.js -var StandardSchemaOutputParser; -var init_standard_schema2 = __esm(() => { - init_json(); - init_base6(); - init_json2(); - StandardSchemaOutputParser = class extends BaseOutputParser { - static lc_name() { - return "StandardSchemaOutputParser"; + const flattenRef = (zodSchema, params2) => { + const seen = this.seen.get(zodSchema); + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + if (seen.ref === null) { + return; + } + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref, params2); + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params2.target === "draft-7") { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + Object.assign(schema2, _cached); + } + } + if (!seen.isParent) + this.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); } - lc_namespace = [ - "langchain", - "output_parsers", - "standard_schema" - ]; - schema; - constructor(schema) { - super(); - this.schema = schema; + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else { + console.warn(`Invalid target: ${this.target}`); } - static fromSerializableSchema(schema) { - return new this(schema); + if (params.external?.uri) { + const id = params.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = params.external.uri(id); } - async parse(text) { - try { - const json2 = parseJsonMarkdown(text, JSON.parse); - const result = await this.schema["~standard"].validate(json2); - if (result.issues) - throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`); - return result.value; - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + Object.assign(result, root.def); + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; } } - _baseMessageToString(message) { - return message.text; - } - getFormatInstructions() { - return ""; + if (params.external) {} else { + if (Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/structured.js -var StructuredOutputParser, JsonMarkdownStructuredOutputParser, AsymmetricStructuredOutputParser; -var init_structured = __esm(() => { - init_zod2(); - init_json_schema2(); - init_base6(); - init_v3(); - StructuredOutputParser = class extends BaseOutputParser { - static lc_name() { - return "StructuredOutputParser"; + try { + return JSON.parse(JSON.stringify(result)); + } catch (_err) { + throw new Error("Error converting schema to JSON."); } - lc_namespace = [ - "langchain", - "output_parsers", - "structured" - ]; - toJSON() { - return this.toJSONNotImplemented(); + } +} +function toJSONSchema2(input, _params) { + if (input instanceof $ZodRegistry2) { + const gen2 = new JSONSchemaGenerator2(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_, schema] = entry; + gen2.process(schema); } - constructor(schema) { - super(schema); - this.schema = schema; + const schemas3 = {}; + const external2 = { + registry: input, + uri: _params?.uri, + defs + }; + for (const entry of input._idmap.entries()) { + const [key, schema] = entry; + schemas3[key] = gen2.emit(schema, { + ..._params, + external: external2 + }); } - static fromZodSchema(schema) { - return new this(schema); + if (Object.keys(defs).length > 0) { + const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas3.__shared = { + [defsSegment]: defs + }; } - static fromNamesAndDescriptions(schemas3) { - const zodSchema = exports_external2.object(Object.fromEntries(Object.entries(schemas3).map(([name, description]) => [name, exports_external2.string().describe(description)]))); - return new this(zodSchema); + return { schemas: schemas3 }; + } + const gen = new JSONSchemaGenerator2(_params); + gen.process(input); + return gen.emit(input, _params); +} +function isTransforming2(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema = _schema; + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming2(def.element, ctx); } - getFormatInstructions() { - return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. - -"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. - -For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} -would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. -Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. - -Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! - -Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: -\`\`\`json -${JSON.stringify(toJsonSchema(this.schema))} -\`\`\` -`; + case "object": { + for (const key in def.shape) { + if (isTransforming2(def.shape[key], ctx)) + return true; + } + return false; } - async parse(text) { - try { - const trimmedText = text.trim(); - const escapedJson = (trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { - return `"${capturedGroup.replace(/\n/g, "\\n")}"`; - }).replace(/\n/g, ""); - return await interopParseAsync(this.schema, JSON.parse(escapedJson)); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + case "union": { + for (const option of def.options) { + if (isTransforming2(option, ctx)) + return true; } + return false; } - _baseMessageToString(message) { - return message.text; + case "intersection": { + return isTransforming2(def.left, ctx) || isTransforming2(def.right, ctx); } - }; - JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { - static lc_name() { - return "JsonMarkdownStructuredOutputParser"; + case "tuple": { + for (const item of def.items) { + if (isTransforming2(item, ctx)) + return true; + } + if (def.rest && isTransforming2(def.rest, ctx)) + return true; + return false; } - getFormatInstructions(options) { - const interpolationDepth = options?.interpolationDepth ?? 1; - if (interpolationDepth < 1) - throw new Error("f string interpolation depth must be at least 1"); - return `Return a markdown code snippet with a JSON object formatted to look like: -\`\`\`json -${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))} -\`\`\``; + case "record": { + return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); } - _schemaToInstruction(schemaInput, indent = 2) { - const schema = schemaInput; - if ("type" in schema) { - let nullable2 = false; - let type; - if (Array.isArray(schema.type)) { - const nullIdx = schema.type.findIndex((type2) => type2 === "null"); - if (nullIdx !== -1) { - nullable2 = true; - schema.type.splice(nullIdx, 1); - } - type = schema.type.join(" | "); - } else - type = schema.type; - if (schema.type === "object" && schema.properties) { - const description2 = schema.description ? ` // ${schema.description}` : ""; - return `{ -${Object.entries(schema.properties).map(([key, value]) => { - const isOptional = schema.required?.includes(key) ? "" : " (optional)"; - return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; - }).join(` -`)} -${" ".repeat(indent - 2)}}${description2}`; - } - if (schema.type === "array" && schema.items) { - const description2 = schema.description ? ` // ${schema.description}` : ""; - return `array[ -${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)} -${" ".repeat(indent - 2)}] ${description2}`; - } - const isNullable = nullable2 ? " (nullable)" : ""; - const description = schema.description ? ` // ${schema.description}` : ""; - return `${type}${description}${isNullable}`; - } - if ("anyOf" in schema) - return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(` -${" ".repeat(indent - 2)}`); - throw new Error("unsupported schema type"); + case "map": { + return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); } - static fromZodSchema(schema) { - return new this(schema); + case "set": { + return isTransforming2(def.valueType, ctx); } - static fromNamesAndDescriptions(schemas3) { - const zodSchema = exports_external2.object(Object.fromEntries(Object.entries(schemas3).map(([name, description]) => [name, exports_external2.string().describe(description)]))); - return new this(zodSchema); + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming2(def.innerType, ctx); + case "lazy": + return isTransforming2(def.getter(), ctx); + case "default": { + return isTransforming2(def.innerType, ctx); } - }; - AsymmetricStructuredOutputParser = class extends BaseOutputParser { - structuredInputParser; - constructor({ inputSchema }) { - super(...arguments); - this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); + case "prefault": { + return isTransforming2(def.innerType, ctx); } - async parse(text) { - let parsedInput; - try { - parsedInput = await this.structuredInputParser.parse(text); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); - } - return this.outputProcessor(parsedInput); + case "custom": { + return false; } - getFormatInstructions() { - return this.structuredInputParser.getFormatInstructions(); + case "transform": { + return true; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/bytes.js -var BytesOutputParser; -var init_bytes = __esm(() => { - init_transform(); - BytesOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "BytesOutputParser"; + case "pipe": { + return isTransforming2(def.in, ctx) || isTransforming2(def.out, ctx); } - lc_namespace = [ - "langchain_core", - "output_parsers", - "bytes" - ]; - lc_serializable = true; - textEncoder = new TextEncoder; - parse(text) { - return Promise.resolve(this.textEncoder.encode(text)); + case "success": { + return false; } - getFormatInstructions() { - return ""; + case "catch": { + return false; } - }; + default: + } + throw new Error(`Unknown schema type: ${def.type}`); +} +var init_to_json_schema2 = __esm(() => { + init_registries2(); + init_util2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/list.js -var ListOutputParser, CommaSeparatedListOutputParser, CustomListOutputParser, NumberedListOutputParser, MarkdownListOutputParser; -var init_list = __esm(() => { - init_base6(); - init_transform(); - ListOutputParser = class extends BaseTransformOutputParser { - re; - async* _transform(inputGenerator) { - let buffer = ""; - for await (const input of inputGenerator) { - if (typeof input === "string") - buffer += input; - else - buffer += input.content; - if (!this.re) { - const parts = await this.parse(buffer); - if (parts.length > 1) { - for (const part of parts.slice(0, -1)) - yield [part]; - buffer = parts[parts.length - 1]; - } - } else { - const matches = [...buffer.matchAll(this.re)]; - if (matches.length > 1) { - let doneIdx = 0; - for (const match2 of matches.slice(0, -1)) { - yield [match2[1]]; - doneIdx += (match2.index ?? 0) + match2[0].length; - } - buffer = buffer.slice(doneIdx); - } - } - } - for (const part of await this.parse(buffer)) - yield [part]; - } - }; - CommaSeparatedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "CommaSeparatedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - async parse(text) { - try { - return text.trim().split(",").map((s) => s.trim()); - } catch { - throw new OutputParserException(`Could not parse output: ${text}`, text); - } +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/json-schema.js +var exports_json_schema2 = {}; +var init_json_schema2 = () => {}; + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/index.js +var exports_core4 = {}; +__export(exports_core4, { + version: () => version4, + util: () => exports_util2, + treeifyError: () => treeifyError2, + toJSONSchema: () => toJSONSchema2, + toDotPath: () => toDotPath2, + safeParseAsync: () => safeParseAsync3, + safeParse: () => safeParse3, + registry: () => registry2, + regexes: () => exports_regexes2, + prettifyError: () => prettifyError2, + parseAsync: () => parseAsync3, + parse: () => parse9, + locales: () => exports_locales2, + isValidJWT: () => isValidJWT2, + isValidBase64URL: () => isValidBase64URL2, + isValidBase64: () => isValidBase642, + globalRegistry: () => globalRegistry2, + globalConfig: () => globalConfig2, + function: () => _function2, + formatError: () => formatError3, + flattenError: () => flattenError2, + config: () => config2, + clone: () => clone2, + _xid: () => _xid2, + _void: () => _void3, + _uuidv7: () => _uuidv72, + _uuidv6: () => _uuidv62, + _uuidv4: () => _uuidv42, + _uuid: () => _uuid2, + _url: () => _url2, + _uppercase: () => _uppercase2, + _unknown: () => _unknown2, + _union: () => _union2, + _undefined: () => _undefined5, + _ulid: () => _ulid2, + _uint64: () => _uint642, + _uint32: () => _uint322, + _tuple: () => _tuple2, + _trim: () => _trim2, + _transform: () => _transform2, + _toUpperCase: () => _toUpperCase2, + _toLowerCase: () => _toLowerCase2, + _templateLiteral: () => _templateLiteral2, + _symbol: () => _symbol2, + _success: () => _success2, + _stringbool: () => _stringbool2, + _stringFormat: () => _stringFormat2, + _string: () => _string2, + _startsWith: () => _startsWith2, + _size: () => _size2, + _set: () => _set2, + _safeParseAsync: () => _safeParseAsync2, + _safeParse: () => _safeParse2, + _regex: () => _regex2, + _refine: () => _refine2, + _record: () => _record2, + _readonly: () => _readonly2, + _property: () => _property2, + _promise: () => _promise2, + _positive: () => _positive2, + _pipe: () => _pipe2, + _parseAsync: () => _parseAsync2, + _parse: () => _parse2, + _overwrite: () => _overwrite2, + _optional: () => _optional2, + _number: () => _number2, + _nullable: () => _nullable2, + _null: () => _null5, + _normalize: () => _normalize2, + _nonpositive: () => _nonpositive2, + _nonoptional: () => _nonoptional2, + _nonnegative: () => _nonnegative2, + _never: () => _never2, + _negative: () => _negative2, + _nativeEnum: () => _nativeEnum2, + _nanoid: () => _nanoid2, + _nan: () => _nan2, + _multipleOf: () => _multipleOf2, + _minSize: () => _minSize2, + _minLength: () => _minLength2, + _min: () => _gte2, + _mime: () => _mime2, + _maxSize: () => _maxSize2, + _maxLength: () => _maxLength2, + _max: () => _lte2, + _map: () => _map2, + _lte: () => _lte2, + _lt: () => _lt2, + _lowercase: () => _lowercase2, + _literal: () => _literal2, + _length: () => _length2, + _lazy: () => _lazy2, + _ksuid: () => _ksuid2, + _jwt: () => _jwt2, + _isoTime: () => _isoTime2, + _isoDuration: () => _isoDuration2, + _isoDateTime: () => _isoDateTime2, + _isoDate: () => _isoDate2, + _ipv6: () => _ipv62, + _ipv4: () => _ipv42, + _intersection: () => _intersection2, + _int64: () => _int642, + _int32: () => _int322, + _int: () => _int2, + _includes: () => _includes2, + _guid: () => _guid2, + _gte: () => _gte2, + _gt: () => _gt2, + _float64: () => _float642, + _float32: () => _float322, + _file: () => _file2, + _enum: () => _enum3, + _endsWith: () => _endsWith2, + _emoji: () => _emoji4, + _email: () => _email2, + _e164: () => _e1642, + _discriminatedUnion: () => _discriminatedUnion2, + _default: () => _default3, + _date: () => _date2, + _custom: () => _custom2, + _cuid2: () => _cuid22, + _cuid: () => _cuid3, + _coercedString: () => _coercedString2, + _coercedNumber: () => _coercedNumber2, + _coercedDate: () => _coercedDate2, + _coercedBoolean: () => _coercedBoolean2, + _coercedBigint: () => _coercedBigint2, + _cidrv6: () => _cidrv62, + _cidrv4: () => _cidrv42, + _catch: () => _catch3, + _boolean: () => _boolean2, + _bigint: () => _bigint2, + _base64url: () => _base64url2, + _base64: () => _base642, + _array: () => _array2, + _any: () => _any2, + TimePrecision: () => TimePrecision2, + NEVER: () => NEVER2, + JSONSchemaGenerator: () => JSONSchemaGenerator2, + JSONSchema: () => exports_json_schema2, + Doc: () => Doc2, + $output: () => $output2, + $input: () => $input2, + $constructor: () => $constructor2, + $brand: () => $brand2, + $ZodXID: () => $ZodXID2, + $ZodVoid: () => $ZodVoid2, + $ZodUnknown: () => $ZodUnknown2, + $ZodUnion: () => $ZodUnion2, + $ZodUndefined: () => $ZodUndefined2, + $ZodUUID: () => $ZodUUID2, + $ZodURL: () => $ZodURL2, + $ZodULID: () => $ZodULID2, + $ZodType: () => $ZodType2, + $ZodTuple: () => $ZodTuple2, + $ZodTransform: () => $ZodTransform2, + $ZodTemplateLiteral: () => $ZodTemplateLiteral2, + $ZodSymbol: () => $ZodSymbol2, + $ZodSuccess: () => $ZodSuccess2, + $ZodStringFormat: () => $ZodStringFormat2, + $ZodString: () => $ZodString2, + $ZodSet: () => $ZodSet2, + $ZodRegistry: () => $ZodRegistry2, + $ZodRecord: () => $ZodRecord2, + $ZodRealError: () => $ZodRealError2, + $ZodReadonly: () => $ZodReadonly2, + $ZodPromise: () => $ZodPromise2, + $ZodPrefault: () => $ZodPrefault2, + $ZodPipe: () => $ZodPipe2, + $ZodOptional: () => $ZodOptional2, + $ZodObject: () => $ZodObject2, + $ZodNumberFormat: () => $ZodNumberFormat2, + $ZodNumber: () => $ZodNumber2, + $ZodNullable: () => $ZodNullable2, + $ZodNull: () => $ZodNull2, + $ZodNonOptional: () => $ZodNonOptional2, + $ZodNever: () => $ZodNever2, + $ZodNanoID: () => $ZodNanoID2, + $ZodNaN: () => $ZodNaN2, + $ZodMap: () => $ZodMap2, + $ZodLiteral: () => $ZodLiteral2, + $ZodLazy: () => $ZodLazy2, + $ZodKSUID: () => $ZodKSUID2, + $ZodJWT: () => $ZodJWT2, + $ZodIntersection: () => $ZodIntersection2, + $ZodISOTime: () => $ZodISOTime2, + $ZodISODuration: () => $ZodISODuration2, + $ZodISODateTime: () => $ZodISODateTime2, + $ZodISODate: () => $ZodISODate2, + $ZodIPv6: () => $ZodIPv62, + $ZodIPv4: () => $ZodIPv42, + $ZodGUID: () => $ZodGUID2, + $ZodFunction: () => $ZodFunction2, + $ZodFile: () => $ZodFile2, + $ZodError: () => $ZodError2, + $ZodEnum: () => $ZodEnum2, + $ZodEmoji: () => $ZodEmoji2, + $ZodEmail: () => $ZodEmail2, + $ZodE164: () => $ZodE1642, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion2, + $ZodDefault: () => $ZodDefault2, + $ZodDate: () => $ZodDate2, + $ZodCustomStringFormat: () => $ZodCustomStringFormat2, + $ZodCustom: () => $ZodCustom2, + $ZodCheckUpperCase: () => $ZodCheckUpperCase2, + $ZodCheckStringFormat: () => $ZodCheckStringFormat2, + $ZodCheckStartsWith: () => $ZodCheckStartsWith2, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals2, + $ZodCheckRegex: () => $ZodCheckRegex2, + $ZodCheckProperty: () => $ZodCheckProperty2, + $ZodCheckOverwrite: () => $ZodCheckOverwrite2, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat2, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf2, + $ZodCheckMinSize: () => $ZodCheckMinSize2, + $ZodCheckMinLength: () => $ZodCheckMinLength2, + $ZodCheckMimeType: () => $ZodCheckMimeType2, + $ZodCheckMaxSize: () => $ZodCheckMaxSize2, + $ZodCheckMaxLength: () => $ZodCheckMaxLength2, + $ZodCheckLowerCase: () => $ZodCheckLowerCase2, + $ZodCheckLessThan: () => $ZodCheckLessThan2, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals2, + $ZodCheckIncludes: () => $ZodCheckIncludes2, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan2, + $ZodCheckEndsWith: () => $ZodCheckEndsWith2, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat2, + $ZodCheck: () => $ZodCheck2, + $ZodCatch: () => $ZodCatch2, + $ZodCUID2: () => $ZodCUID22, + $ZodCUID: () => $ZodCUID3, + $ZodCIDRv6: () => $ZodCIDRv62, + $ZodCIDRv4: () => $ZodCIDRv42, + $ZodBoolean: () => $ZodBoolean2, + $ZodBigIntFormat: () => $ZodBigIntFormat2, + $ZodBigInt: () => $ZodBigInt2, + $ZodBase64URL: () => $ZodBase64URL2, + $ZodBase64: () => $ZodBase642, + $ZodAsyncError: () => $ZodAsyncError2, + $ZodArray: () => $ZodArray2, + $ZodAny: () => $ZodAny2 +}); +var init_core4 = __esm(() => { + init_util2(); + init_regexes2(); + init_locales2(); + init_json_schema2(); + init_core3(); + init_parse5(); + init_errors4(); + init_schemas3(); + init_checks3(); + init_versions2(); + init_registries2(); + init_function2(); + init_api2(); + init_to_json_schema2(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/types/zod.js +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) + return false; + const obj = schema; + if (!("_zod" in obj)) + return false; + const zod = obj._zod; + return typeof zod === "object" && zod !== null && "def" in zod; +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) + return false; + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) + return false; + const def = obj._def; + return typeof def === "object" && def != null && "typeName" in def; +} +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) + console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); + return isZodSchemaV3(schema); +} +function isInteropZodSchema(input) { + if (!input) + return false; + if (typeof input !== "object") + return false; + if (Array.isArray(input)) + return false; + if (isZodSchemaV4(input) || isZodSchemaV3(input)) + return true; + return false; +} +function isZodLiteralV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") + return true; + return false; +} +function isZodLiteralV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") + return true; + return false; +} +function isInteropZodLiteral(obj) { + if (isZodLiteralV3(obj)) + return true; + if (isZodLiteralV4(obj)) + return true; + return false; +} +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) + try { + return { + success: true, + data: await parseAsync3(schema, input) + }; + } catch (error90) { + return { + success: false, + error: error90 + }; } - getFormatInstructions() { - return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; + if (isZodSchemaV3(schema)) + return await schema.safeParseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) + return await parseAsync3(schema, input); + if (isZodSchemaV3(schema)) + return await schema.parseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) + try { + return { + success: true, + data: parse9(schema, input) + }; + } catch (error90) { + return { + success: false, + error: error90 + }; } - }; - CustomListOutputParser = class extends ListOutputParser { - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - length; - separator; - constructor({ length, separator }) { - super(...arguments); - this.length = length; - this.separator = separator || ","; + if (isZodSchemaV3(schema)) + return schema.safeParse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) + return parse9(schema, input); + if (isZodSchemaV3(schema)) + return schema.parse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) + return globalRegistry2.get(schema)?.description; + if (isZodSchemaV3(schema)) + return schema.description; + if ("description" in schema && typeof schema.description === "string") + return schema.description; +} +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) + return false; + if (isZodSchemaV3(schema)) { + const def = schema._def; + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; } - async parse(text) { - try { - const items = text.trim().split(this.separator).map((s) => s.trim()); - if (this.length !== undefined && items.length !== this.length) - throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); - return items; - } catch (e) { - if (Object.getPrototypeOf(e) === OutputParserException.prototype) - throw e; - throw new OutputParserException(`Could not parse output: ${text}`); + if (def.typeName === "ZodRecord") + return true; + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.type === "record") + return true; + } + if (typeof schema === "object" && schema !== null && !("shape" in schema)) + return true; + return false; +} +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) + return false; + if (isZodSchemaV3(schema)) + return schema._def.typeName === "ZodString"; + if (isZodSchemaV4(schema)) + return schema._zod.def.type === "string"; + return false; +} +function isZodObjectV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") + return true; + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") + return true; + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") + return true; + return false; +} +function isZodOptionalV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional") + return true; + return false; +} +function isZodNullableV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable") + return true; + return false; +} +function isInteropZodObject(obj) { + if (isZodObjectV3(obj)) + return true; + if (isZodObjectV4(obj)) + return true; + return false; +} +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) + return schema.shape; + if (isZodSchemaV4(schema)) + return schema._zod.def.shape; + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) + return schema.extend(extension); + if (isZodSchemaV4(schema)) + return exports_util2.extend(schema, extension); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) + return schema.partial(); + if (isZodSchemaV4(schema)) + return exports_util2.partial($ZodOptional2, schema, undefined); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectStrict(schema, recursive = false) { + if (isZodObjectV3(schema)) + return schema.strict(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) + outputShape[key] = interopZodObjectStrict(keySchema, recursive); + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) + elementSchema = interopZodObjectStrict(elementSchema, recursive); + outputShape[key] = clone2(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else + outputShape[key] = keySchema; + const meta4 = globalRegistry2.get(keySchema); + if (meta4) + globalRegistry2.add(outputShape[key], meta4); + } + const modifiedSchema = clone2(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _never2($ZodNever2) + }); + const meta3 = globalRegistry2.get(schema); + if (meta3) + globalRegistry2.add(modifiedSchema, meta3); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) + return schema.passthrough(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) + outputShape[key] = interopZodObjectPassthrough(keySchema, recursive); + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) + elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + outputShape[key] = clone2(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else + outputShape[key] = keySchema; + const meta4 = globalRegistry2.get(keySchema); + if (meta4) + globalRegistry2.add(outputShape[key], meta4); } + const modifiedSchema = clone2(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _unknown2($ZodUnknown2) + }); + const meta3 = globalRegistry2.get(schema); + if (meta3) + globalRegistry2.add(modifiedSchema, meta3); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) + try { + const defaultValue = schema.parse(undefined); + return () => defaultValue; + } catch { + return; } - getFormatInstructions() { - return `Your response should be a list of ${this.length === undefined ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; + if (isZodSchemaV4(schema)) + try { + const defaultValue = parse9(schema, undefined); + return () => defaultValue; + } catch { + return; } - }; - NumberedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; +} +function isZodTransformV3(schema) { + return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +} +function interopZodTransformInputSchemaImpl(schema, recursive, cache) { + const cached3 = cache.get(schema); + if (cached3 !== undefined) + return cached3; + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) + return interopZodTransformInputSchemaImpl(schema._def.schema, recursive, cache); + return schema; + } + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) + outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache); + if (recursive) { + if (isZodObjectV4(outputSchema)) { + const outputShape = {}; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) + outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache); + outputSchema = clone2(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape + }); + } else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.element, recursive, cache); + outputSchema = clone2(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema + }); + } else if (isZodOptionalV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone2(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } else if (isZodNullableV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone2(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: + const meta3 = globalRegistry2.get(schema); + if (meta3) + globalRegistry2.add(outputSchema, meta3); + cache.set(schema, outputSchema); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +function interopZodTransformInputSchema(schema, recursive = false) { + return interopZodTransformInputSchemaImpl(schema, recursive, /* @__PURE__ */ new WeakMap); +} +function interopZodObjectMakeFieldsOptional(schema, predicate) { + if (isZodSchemaV3(schema)) { + const shape = getInteropZodObjectShape(schema); + const modifiedShape = {}; + for (const [key, value] of Object.entries(shape)) + if (predicate(key, value)) + modifiedShape[key] = value.optional(); + else + modifiedShape[key] = value; + return schema.extend(modifiedShape); + } + if (isZodSchemaV4(schema)) { + const shape = getInteropZodObjectShape(schema); + const outputShape = { ...schema._zod.def.shape }; + for (const [key, value] of Object.entries(shape)) + if (predicate(key, value)) + outputShape[key] = new $ZodOptional2({ + type: "optional", + innerType: value + }); + const modifiedSchema = clone2(schema, { + ...schema._zod.def, + shape: outputShape + }); + const meta3 = globalRegistry2.get(schema); + if (meta3) + globalRegistry2.add(modifiedSchema, meta3); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function isInteropZodError(e) { + return e instanceof Error && (e.constructor.name === "ZodError" || e.constructor.name === "$ZodError"); +} +var init_zod2 = __esm(() => { + init_core4(); +}); -1. foo +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/standard_schema.js +function isStandardSchema(schema) { + return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +} +function isStandardJsonSchema(schema) { + return (typeof schema === "object" || typeof schema === "function") && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +} +function isSerializableSchema(schema) { + return isStandardSchema(schema) && isStandardJsonSchema(schema); +} +var standard_schema_exports; +var init_standard_schema = __esm(() => { + init_runtime2(); + standard_schema_exports = /* @__PURE__ */ __exportAll({ + isSerializableSchema: () => isSerializableSchema, + isStandardJsonSchema: () => isStandardJsonSchema, + isStandardSchema: () => isStandardSchema + }); +}); -2. bar +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js +var ignoreOverride, defaultOptions2, getDefaultOptions = (options) => typeof options === "string" ? { + ...defaultOptions2, + name: options +} : { + ...defaultOptions2, + ...options +}; +var init_Options = __esm(() => { + ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + defaultOptions2 = { + name: undefined, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" + }; +}); -3. baz`; - } - re = /\d+\.\s([^\n]+)/g; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js +var getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== undefined ? [ + ..._options.basePath, + _options.definitionPath, + _options.name + ] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: undefined, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { + def: def._def, + path: [ + ..._options.basePath, + _options.definitionPath, + name + ], + jsonSchema: undefined + }])) }; - MarkdownListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: +}; +var init_Refs = __esm(() => { + init_Options(); +}); -1. foo +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js +var getRelativePath = (pathA, pathB) => { + let i = 0; + for (;i < pathA.length && i < pathB.length; i++) + if (pathA[i] !== pathB[i]) + break; + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +var init_getRelativePath = () => {}; -2. bar +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js +function parseAnyDef(refs) { + if (refs.target !== "openAi") + return {}; + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; +} +var init_any = __esm(() => { + init_getRelativePath(); +}); -3. baz`; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +var init_errorMessages = () => {}; + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js +var util, objectUtil, ZodParsedType, getParsedType3 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; +var init_util3 = __esm(() => { + (function(util2) { + util2.assertEqual = (_) => {}; + function assertIs3(_arg) {} + util2.assertIs = assertIs3; + function assertNever3(_x) { + throw new Error; } - re = /^\s*[-*]\s([^\n]+)$/gm; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + util2.assertNever = assertNever3; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => { + const keys = []; + for (const key in object2) { + if (Object.prototype.hasOwnProperty.call(object2, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr2, checker) => { + for (const item of arr2) { + if (checker(item)) + return item; + } + return; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues3(array2, separator = " | ") { + return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } - }; + util2.joinValues = joinValues3; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util || (util = {})); + (function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + }; + }; + })(objectUtil || (objectUtil = {})); + ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/string.js -var StringOutputParser; -var init_string2 = __esm(() => { - init_transform(); - StringOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "StrOutputParser"; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js +var ZodIssueCode2, quotelessJson = (obj) => { + const json2 = JSON.stringify(obj, null, 2); + return json2.replace(/"([^"]+)":/g, "$1:"); +}, ZodError2; +var init_ZodError = __esm(() => { + init_util3(); + ZodIssueCode2 = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + ZodError2 = class ZodError2 extends Error { + get errors() { + return this.issues; } - lc_namespace = [ - "langchain_core", - "output_parsers", - "string" - ]; - lc_serializable = true; - parse(text) { - return Promise.resolve(text); + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; } - getFormatInstructions() { - return ""; + format(_mapper) { + const mapper = _mapper || function(issue3) { + return issue3.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error90) => { + for (const issue3 of error90.issues) { + if (issue3.code === "invalid_union") { + issue3.unionErrors.map(processError); + } else if (issue3.code === "invalid_return_type") { + processError(issue3.returnTypeError); + } else if (issue3.code === "invalid_arguments") { + processError(issue3.argumentsError); + } else if (issue3.path.length === 0) { + fieldErrors._errors.push(mapper(issue3)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue3.path.length) { + const el = issue3.path[i]; + const terminal = i === issue3.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue3)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; } - _textContentToString(content) { - return content.text; + static assert(value) { + if (!(value instanceof ZodError2)) { + throw new Error(`Not a ZodError: ${value}`); + } } - _imageUrlContentToString(_content) { - throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); + toString() { + return this.message; } - _messageContentToString(content) { - switch (content.type) { - case "text": - case "text_delta": - if ("text" in content) - return this._textContentToString(content); - break; - case "image_url": - if ("image_url" in content) - return this._imageUrlContentToString(content); - break; - case "reasoning": - case "thinking": - case "redacted_thinking": - return ""; - default: - throw new Error(`Cannot coerce "${content.type}" message part into a string.`); + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue3) => issue3.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } } - throw new Error(`Invalid content type: ${content.type}`); + return { formErrors, fieldErrors }; } - _baseMessageContentToString(content) { - return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); + get formErrors() { + return this.flatten(); } }; + ZodError2.create = (issues) => { + const error90 = new ZodError2(issues); + return error90; + }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/sax-js/sax.js -var initializeSax = function() { - const sax = {}; - sax.parser = function(strict, opt) { - return new SAXParser(strict, opt); - }; - sax.SAXParser = SAXParser; - sax.SAXStream = SAXStream; - sax.createStream = createStream; - sax.MAX_BUFFER_LENGTH = 64 * 1024; - const buffers = [ - "comment", - "sgmlDecl", - "textNode", - "tagName", - "doctype", - "procInstName", - "procInstBody", - "entity", - "attribName", - "attribValue", - "cdata", - "script" - ]; - sax.EVENTS = [ - "text", - "processinginstruction", - "sgmldeclaration", - "doctype", - "comment", - "opentagstart", - "attribute", - "opentag", - "closetag", - "opencdata", - "cdata", - "closecdata", - "error", - "end", - "ready", - "script", - "opennamespace", - "closenamespace" - ]; - function SAXParser(strict, opt) { - if (!(this instanceof SAXParser)) - return new SAXParser(strict, opt); - var parser = this; - clearBuffers(parser); - parser.q = parser.c = ""; - parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH; - parser.opt = opt || {}; - parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; - parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; - parser.tags = []; - parser.closed = parser.closedRoot = parser.sawRoot = false; - parser.tag = parser.error = null; - parser.strict = !!strict; - parser.noscript = !!(strict || parser.opt.noscript); - parser.state = S.BEGIN; - parser.strictEntities = parser.opt.strictEntities; - parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES); - parser.attribList = []; - if (parser.opt.xmlns) - parser.ns = Object.create(rootNS); - parser.trackPosition = parser.opt.position !== false; - if (parser.trackPosition) - parser.position = parser.line = parser.column = 0; - emit(parser, "onready"); - } - if (!Object.create) - Object.create = function(o) { - function F() {} - F.prototype = o; - return new F; - }; - if (!Object.keys) - Object.keys = function(o) { - var a = []; - for (var i in o) - if (o.hasOwnProperty(i)) - a.push(i); - return a; - }; - function checkBufferLength(parser) { - var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10); - var maxActual = 0; - for (var i = 0, l = buffers.length;i < l; i++) { - var len = parser[buffers[i]].length; - if (len > maxAllowed) - switch (buffers[i]) { - case "textNode": - closeText(parser); - break; - case "cdata": - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - break; - case "script": - emitNode(parser, "onscript", parser.script); - parser.script = ""; - break; - default: - error51(parser, "Max buffer length exceeded: " + buffers[i]); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js +var errorMap = (issue3, _ctx) => { + let message; + switch (issue3.code) { + case ZodIssueCode2.invalid_type: + if (issue3.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue3.expected}, received ${issue3.received}`; + } + break; + case ZodIssueCode2.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue3.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode2.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue3.keys, ", ")}`; + break; + case ZodIssueCode2.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue3.options)}`; + break; + case ZodIssueCode2.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue3.options)}, received '${issue3.received}'`; + break; + case ZodIssueCode2.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode2.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode2.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode2.invalid_string: + if (typeof issue3.validation === "object") { + if ("includes" in issue3.validation) { + message = `Invalid input: must include "${issue3.validation.includes}"`; + if (typeof issue3.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue3.validation.position}`; + } + } else if ("startsWith" in issue3.validation) { + message = `Invalid input: must start with "${issue3.validation.startsWith}"`; + } else if ("endsWith" in issue3.validation) { + message = `Invalid input: must end with "${issue3.validation.endsWith}"`; + } else { + util.assertNever(issue3.validation); } - maxActual = Math.max(maxActual, len); - } - parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - maxActual + parser.position; + } else if (issue3.validation !== "regex") { + message = `Invalid ${issue3.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode2.too_small: + if (issue3.type === "array") + message = `Array must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `more than`} ${issue3.minimum} element(s)`; + else if (issue3.type === "string") + message = `String must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `over`} ${issue3.minimum} character(s)`; + else if (issue3.type === "number") + message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; + else if (issue3.type === "bigint") + message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; + else if (issue3.type === "date") + message = `Date must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue3.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.too_big: + if (issue3.type === "array") + message = `Array must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `less than`} ${issue3.maximum} element(s)`; + else if (issue3.type === "string") + message = `String must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `under`} ${issue3.maximum} character(s)`; + else if (issue3.type === "number") + message = `Number must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; + else if (issue3.type === "bigint") + message = `BigInt must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; + else if (issue3.type === "date") + message = `Date must be ${issue3.exact ? `exactly` : issue3.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue3.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.custom: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode2.not_multiple_of: + message = `Number must be a multiple of ${issue3.multipleOf}`; + break; + case ZodIssueCode2.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue3); } - function clearBuffers(parser) { - for (var i = 0, l = buffers.length;i < l; i++) - parser[buffers[i]] = ""; + return { message }; +}, en_default3; +var init_en3 = __esm(() => { + init_ZodError(); + init_util3(); + en_default3 = errorMap; +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js +function setErrorMap2(map2) { + overrideErrorMap = map2; +} +function getErrorMap2() { + return overrideErrorMap; +} +var overrideErrorMap; +var init_errors5 = __esm(() => { + init_en3(); + overrideErrorMap = en_default3; +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap2(); + const issue3 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === en_default3 ? undefined : en_default3 + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue3); +} + +class ParseStatus { + constructor() { + this.value = "valid"; } - function flushBuffers(parser) { - closeText(parser); - if (parser.cdata !== "") { - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - } - if (parser.script !== "") { - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } + dirty() { + if (this.value === "valid") + this.value = "dirty"; } - SAXParser.prototype = { - end: function() { - end(this); - }, - write, - resume: function() { - this.error = null; - return this; - }, - close: function() { - return this.write(null); - }, - flush: function() { - flushBuffers(this); + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); } - }; - var Stream = ReadableStream; - if (!Stream) - Stream = function() {}; - var streamWraps = sax.EVENTS.filter(function(ev) { - return ev !== "error" && ev !== "end"; - }); - function createStream(strict, opt) { - return new SAXStream(strict, opt); + return { status: status.value, value: arrayValue }; } - function SAXStream(strict, opt) { - if (!(this instanceof SAXStream)) - return new SAXStream(strict, opt); - Stream.apply(this); - this._parser = new SAXParser(strict, opt); - this.writable = true; - this.readable = true; - var me = this; - this._parser.onend = function() { - me.emit("end"); - }; - this._parser.onerror = function(er) { - me.emit("error", er); - me._parser.error = null; - }; - this._decoder = null; - streamWraps.forEach(function(ev) { - Object.defineProperty(me, "on" + ev, { - get: function() { - return me._parser["on" + ev]; - }, - set: function(h) { - if (!h) { - me.removeAllListeners(ev); - me._parser["on" + ev] = h; - return h; - } - me.on(ev, h); - }, - enumerable: true, - configurable: false + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value }); - }); - } - SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }); - SAXStream.prototype.write = function(data) { - this._parser.write(data.toString()); - this.emit("data", data); - return true; - }; - SAXStream.prototype.end = function(chunk) { - if (chunk && chunk.length) - this.write(chunk); - this._parser.end(); - return true; - }; - SAXStream.prototype.on = function(ev, handler) { - var me = this; - if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) - me._parser["on" + ev] = function() { - var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); - args.splice(0, 0, ev); - me.emit.apply(me, args); - }; - return Stream.prototype.on.call(me, ev, handler); - }; - var CDATA = "[CDATA["; - var DOCTYPE = "DOCTYPE"; - var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; - var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; - var rootNS = { - xml: XML_NAMESPACE, - xmlns: XMLNS_NAMESPACE - }; - var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - function isWhitespace(c) { - return c === " " || c === ` -` || c === "\r" || c === "\t"; - } - function isQuote(c) { - return c === '"' || c === "'"; + } + return ParseStatus.mergeObjectSync(status, syncPairs); } - function isAttribEnd(c) { - return c === ">" || isWhitespace(c); + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; } - function isMatch(regex2, c) { - return regex2.test(c); +} +var makeIssue = (params) => { + const { data, path: path2, errorMaps, issueData } = params; + const fullPath = [...path2, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; } - function notMatch(regex2, c) { - return !isMatch(regex2, c); + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map2 of maps) { + errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } - var S = 0; - sax.STATE = { - BEGIN: S++, - BEGIN_WHITESPACE: S++, - TEXT: S++, - TEXT_ENTITY: S++, - OPEN_WAKA: S++, - SGML_DECL: S++, - SGML_DECL_QUOTED: S++, - DOCTYPE: S++, - DOCTYPE_QUOTED: S++, - DOCTYPE_DTD: S++, - DOCTYPE_DTD_QUOTED: S++, - COMMENT_STARTING: S++, - COMMENT: S++, - COMMENT_ENDING: S++, - COMMENT_ENDED: S++, - CDATA: S++, - CDATA_ENDING: S++, - CDATA_ENDING_2: S++, - PROC_INST: S++, - PROC_INST_BODY: S++, - PROC_INST_ENDING: S++, - OPEN_TAG: S++, - OPEN_TAG_SLASH: S++, - ATTRIB: S++, - ATTRIB_NAME: S++, - ATTRIB_NAME_SAW_WHITE: S++, - ATTRIB_VALUE: S++, - ATTRIB_VALUE_QUOTED: S++, - ATTRIB_VALUE_CLOSED: S++, - ATTRIB_VALUE_UNQUOTED: S++, - ATTRIB_VALUE_ENTITY_Q: S++, - ATTRIB_VALUE_ENTITY_U: S++, - CLOSE_TAG: S++, - CLOSE_TAG_SAW_WHITE: S++, - SCRIPT: S++, - SCRIPT_ENDING: S++ - }; - sax.XML_ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: '"', - apos: "'" - }; - sax.ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: '"', - apos: "'", - AElig: 198, - Aacute: 193, - Acirc: 194, - Agrave: 192, - Aring: 197, - Atilde: 195, - Auml: 196, - Ccedil: 199, - ETH: 208, - Eacute: 201, - Ecirc: 202, - Egrave: 200, - Euml: 203, - Iacute: 205, - Icirc: 206, - Igrave: 204, - Iuml: 207, - Ntilde: 209, - Oacute: 211, - Ocirc: 212, - Ograve: 210, - Oslash: 216, - Otilde: 213, - Ouml: 214, - THORN: 222, - Uacute: 218, - Ucirc: 219, - Ugrave: 217, - Uuml: 220, - Yacute: 221, - aacute: 225, - acirc: 226, - aelig: 230, - agrave: 224, - aring: 229, - atilde: 227, - auml: 228, - ccedil: 231, - eacute: 233, - ecirc: 234, - egrave: 232, - eth: 240, - euml: 235, - iacute: 237, - icirc: 238, - igrave: 236, - iuml: 239, - ntilde: 241, - oacute: 243, - ocirc: 244, - ograve: 242, - oslash: 248, - otilde: 245, - ouml: 246, - szlig: 223, - thorn: 254, - uacute: 250, - ucirc: 251, - ugrave: 249, - uuml: 252, - yacute: 253, - yuml: 255, - copy: 169, - reg: 174, - nbsp: 160, - iexcl: 161, - cent: 162, - pound: 163, - curren: 164, - yen: 165, - brvbar: 166, - sect: 167, - uml: 168, - ordf: 170, - laquo: 171, - not: 172, - shy: 173, - macr: 175, - deg: 176, - plusmn: 177, - sup1: 185, - sup2: 178, - sup3: 179, - acute: 180, - micro: 181, - para: 182, - middot: 183, - cedil: 184, - ordm: 186, - raquo: 187, - frac14: 188, - frac12: 189, - frac34: 190, - iquest: 191, - times: 215, - divide: 247, - OElig: 338, - oelig: 339, - Scaron: 352, - scaron: 353, - Yuml: 376, - fnof: 402, - circ: 710, - tilde: 732, - Alpha: 913, - Beta: 914, - Gamma: 915, - Delta: 916, - Epsilon: 917, - Zeta: 918, - Eta: 919, - Theta: 920, - Iota: 921, - Kappa: 922, - Lambda: 923, - Mu: 924, - Nu: 925, - Xi: 926, - Omicron: 927, - Pi: 928, - Rho: 929, - Sigma: 931, - Tau: 932, - Upsilon: 933, - Phi: 934, - Chi: 935, - Psi: 936, - Omega: 937, - alpha: 945, - beta: 946, - gamma: 947, - delta: 948, - epsilon: 949, - zeta: 950, - eta: 951, - theta: 952, - iota: 953, - kappa: 954, - lambda: 955, - mu: 956, - nu: 957, - xi: 958, - omicron: 959, - pi: 960, - rho: 961, - sigmaf: 962, - sigma: 963, - tau: 964, - upsilon: 965, - phi: 966, - chi: 967, - psi: 968, - omega: 969, - thetasym: 977, - upsih: 978, - piv: 982, - ensp: 8194, - emsp: 8195, - thinsp: 8201, - zwnj: 8204, - zwj: 8205, - lrm: 8206, - rlm: 8207, - ndash: 8211, - mdash: 8212, - lsquo: 8216, - rsquo: 8217, - sbquo: 8218, - ldquo: 8220, - rdquo: 8221, - bdquo: 8222, - dagger: 8224, - Dagger: 8225, - bull: 8226, - hellip: 8230, - permil: 8240, - prime: 8242, - Prime: 8243, - lsaquo: 8249, - rsaquo: 8250, - oline: 8254, - frasl: 8260, - euro: 8364, - image: 8465, - weierp: 8472, - real: 8476, - trade: 8482, - alefsym: 8501, - larr: 8592, - uarr: 8593, - rarr: 8594, - darr: 8595, - harr: 8596, - crarr: 8629, - lArr: 8656, - uArr: 8657, - rArr: 8658, - dArr: 8659, - hArr: 8660, - forall: 8704, - part: 8706, - exist: 8707, - empty: 8709, - nabla: 8711, - isin: 8712, - notin: 8713, - ni: 8715, - prod: 8719, - sum: 8721, - minus: 8722, - lowast: 8727, - radic: 8730, - prop: 8733, - infin: 8734, - ang: 8736, - and: 8743, - or: 8744, - cap: 8745, - cup: 8746, - int: 8747, - there4: 8756, - sim: 8764, - cong: 8773, - asymp: 8776, - ne: 8800, - equiv: 8801, - le: 8804, - ge: 8805, - sub: 8834, - sup: 8835, - nsub: 8836, - sube: 8838, - supe: 8839, - oplus: 8853, - otimes: 8855, - perp: 8869, - sdot: 8901, - lceil: 8968, - rceil: 8969, - lfloor: 8970, - rfloor: 8971, - lang: 9001, - rang: 9002, - loz: 9674, - spades: 9824, - clubs: 9827, - hearts: 9829, - diams: 9830 + return { + ...issueData, + path: fullPath, + message: errorMessage }; - Object.keys(sax.ENTITIES).forEach(function(key) { - var e = sax.ENTITIES[key]; - var s2 = typeof e === "number" ? String.fromCharCode(e) : e; - sax.ENTITIES[key] = s2; +}, EMPTY_PATH, INVALID, DIRTY = (value) => ({ status: "dirty", value }), OK = (value) => ({ status: "valid", value }), isAborted = (x) => x.status === "aborted", isDirty = (x) => x.status === "dirty", isValid = (x) => x.status === "valid", isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +var init_parseUtil = __esm(() => { + init_errors5(); + init_en3(); + EMPTY_PATH = []; + INVALID = Object.freeze({ + status: "aborted" }); - for (var s in sax.STATE) - sax.STATE[sax.STATE[s]] = s; - S = sax.STATE; - function emit(parser, event, data) { - parser[event] && parser[event](data); - } - function emitNode(parser, nodeType, data) { - if (parser.textNode) - closeText(parser); - emit(parser, nodeType, data); - } - function closeText(parser) { - parser.textNode = textopts(parser.opt, parser.textNode); - if (parser.textNode) - emit(parser, "ontext", parser.textNode); - parser.textNode = ""; +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js +var init_typeAliases = () => {}; + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +var init_errorUtil = __esm(() => { + (function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil || (errorUtil = {})); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js +class ParseInputLazyPath { + constructor(parent, value, path2, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path2; + this._key = key; } - function textopts(opt, text) { - if (opt.trim) - text = text.trim(); - if (opt.normalize) - text = text.replace(/\s+/g, " "); - return text; + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; } - function error51(parser, er) { - closeText(parser); - if (parser.trackPosition) - er += ` -Line: ` + parser.line + ` -Column: ` + parser.column + ` -Char: ` + parser.c; - er = new Error(er); - parser.error = er; - emit(parser, "onerror", er); - return parser; +} +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - function end(parser) { - if (parser.sawRoot && !parser.closedRoot) - strictFail(parser, "Unclosed root tag"); - if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) - error51(parser, "Unexpected end"); - closeText(parser); - parser.c = ""; - parser.closed = true; - emit(parser, "onend"); - SAXParser.call(parser, parser.strict, parser.opt); - return parser; + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} + +class ZodType2 { + get description() { + return this._def.description; } - function strictFail(parser, message) { - if (typeof parser !== "object" || !(parser instanceof SAXParser)) - throw new Error("bad call to strictFail"); - if (parser.strict) - error51(parser, message); + _getType(input) { + return getParsedType3(input.data); } - function newTag(parser) { - if (!parser.strict) - parser.tagName = parser.tagName[parser.looseCase](); - var parent = parser.tags[parser.tags.length - 1] || parser; - var tag = parser.tag = { - name: parser.tagName, - attributes: {} + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType3(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent }; - if (parser.opt.xmlns) - tag.ns = parent.ns; - parser.attribList.length = 0; - emitNode(parser, "onopentagstart", tag); } - function qname(name, attribute) { - var qualName = name.indexOf(":") < 0 ? ["", name] : name.split(":"); - var prefix = qualName[0]; - var local = qualName[1]; - if (attribute && name === "xmlns") { - prefix = "xmlns"; - local = ""; - } + _processInputParams(input) { return { - prefix, - local + status: new ParseStatus, + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType3(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } }; } - function attrib(parser) { - if (!parser.strict) - parser.attribName = parser.attribName[parser.looseCase](); - if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { - parser.attribName = parser.attribValue = ""; - return; - } - if (parser.opt.xmlns) { - var qn = qname(parser.attribName, true); - var prefix = qn.prefix; - var local = qn.local; - if (prefix === "xmlns") - if (local === "xml" && parser.attribValue !== XML_NAMESPACE) - strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + ` -Actual: ` + parser.attribValue); - else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) - strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + ` -Actual: ` + parser.attribValue); - else { - var tag = parser.tag; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns === parent.ns) - tag.ns = Object.create(parent.ns); - tag.ns[local] = parser.attribValue; - } - parser.attribList.push([parser.attribName, parser.attribValue]); - } else { - parser.tag.attributes[parser.attribName] = parser.attribValue; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: parser.attribValue - }); + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); } - parser.attribName = parser.attribValue = ""; + return result; } - function openTag(parser, selfClosing) { - if (parser.opt.xmlns) { - var tag = parser.tag; - var qn = qname(parser.tagName); - tag.prefix = qn.prefix; - tag.local = qn.local; - tag.uri = tag.ns[qn.prefix] || ""; - if (tag.prefix && !tag.uri) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); - tag.uri = qn.prefix; - } - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns && parent.ns !== tag.ns) - Object.keys(tag.ns).forEach(function(p) { - emitNode(parser, "onopennamespace", { - prefix: p, - uri: tag.ns[p] - }); - }); - for (var i = 0, l = parser.attribList.length;i < l; i++) { - var nv = parser.attribList[i]; - var name = nv[0]; - var value = nv[1]; - var qualName = qname(name, true); - var prefix = qualName.prefix; - var local = qualName.local; - var uri2 = prefix === "" ? "" : tag.ns[prefix] || ""; - var a = { - name, - value, - prefix, - local, - uri: uri2 + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType3(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType3(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues }; - if (prefix && prefix !== "xmlns" && !uri2) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); - a.uri = prefix; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; } - parser.tag.attributes[name] = a; - emitNode(parser, "onattribute", a); + ctx.common = { + issues: [], + async: true + }; } - parser.attribList.length = 0; } - parser.tag.isSelfClosing = !!selfClosing; - parser.sawRoot = true; - parser.tags.push(parser.tag); - emitNode(parser, "onopentag", parser.tag); - if (!selfClosing) { - if (!parser.noscript && parser.tagName.toLowerCase() === "script") - parser.state = S.SCRIPT; - else - parser.state = S.TEXT; - parser.tag = null; - parser.tagName = ""; - } - parser.attribName = parser.attribValue = ""; - parser.attribList.length = 0; + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); } - function closeTag(parser) { - if (!parser.tagName) { - strictFail(parser, "Weird empty close tag."); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - if (parser.script) { - if (parser.tagName !== "script") { - parser.script += ""; - parser.tagName = ""; - parser.state = S.SCRIPT; - return; + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType3(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check2, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; } - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } - var t = parser.tags.length; - var tagName = parser.tagName; - if (!parser.strict) - tagName = tagName[parser.looseCase](); - var closeTo = tagName; - while (t--) - if (parser.tags[t].name !== closeTo) - strictFail(parser, "Unexpected close tag"); - else - break; - if (t < 0) { - strictFail(parser, "Unmatched closing tag: " + parser.tagName); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - parser.tagName = tagName; - var s2 = parser.tags.length; - while (s2-- > t) { - var tag = parser.tag = parser.tags.pop(); - parser.tagName = parser.tag.name; - emitNode(parser, "onclosetag", parser.tagName); - var x = {}; - for (var i in tag.ns) - x[i] = tag.ns[i]; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (parser.opt.xmlns && tag.ns !== parent.ns) - Object.keys(tag.ns).forEach(function(p) { - var n2 = tag.ns[p]; - emitNode(parser, "onclosenamespace", { - prefix: p, - uri: n2 - }); + }; + return this._refinement((val, ctx) => { + const result = check2(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode2.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } }); - } - if (t === 0) - parser.closedRoot = true; - parser.tagName = parser.attribValue = parser.attribName = ""; - parser.attribList.length = 0; - parser.state = S.TEXT; + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); } - function parseEntity(parser) { - var entity = parser.entity; - var entityLC = entity.toLowerCase(); - var num; - var numStr = ""; - if (parser.ENTITIES[entity]) - return parser.ENTITIES[entity]; - if (parser.ENTITIES[entityLC]) - return parser.ENTITIES[entityLC]; - entity = entityLC; - if (entity.charAt(0) === "#") - if (entity.charAt(1) === "x") { - entity = entity.slice(2); - num = parseInt(entity, 16); - numStr = num.toString(16); + refinement(check2, refinementData) { + return this._refinement((val, ctx) => { + if (!check2(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; } else { - entity = entity.slice(1); - num = parseInt(entity, 10); - numStr = num.toString(10); + return true; } - entity = entity.replace(/^0+/, ""); - if (isNaN(num) || numStr.toLowerCase() !== entity) { - strictFail(parser, "Invalid character entity"); - return "&" + parser.entity + ";"; + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional2.create(this, this._def); + } + nullable() { + return ZodNullable2.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray2.create(this); + } + promise() { + return ZodPromise2.create(this, this._def); + } + or(option) { + return ZodUnion2.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection2.create(this, incoming, this._def); + } + transform(transform2) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "transform", transform: transform2 } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault2({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind2.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch2({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly2.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version5) { + if ((version5 === "v4" || !version5) && ipv4Regex.test(ip)) { + return true; + } + if ((version5 === "v6" || !version5) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT3(jwt2, alg) { + if (!jwtRegex.test(jwt2)) + return false; + try { + const [header] = jwt2.split("."); + if (!header) + return false; + const base644 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base644)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version5) { + if ((version5 === "v4" || !version5) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version5 === "v6" || !version5) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +function floatSafeRemainder3(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function deepPartialify(schema) { + if (schema instanceof ZodObject2) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema)); } - return String.fromCodePoint(num); + return new ZodObject2({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray2) { + return new ZodArray2({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional2) { + return ZodOptional2.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable2) { + return ZodNullable2.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple2) { + return ZodTuple2.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; } - function beginWhiteSpace(parser, c) { - if (c === "<") { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else if (!isWhitespace(c)) { - strictFail(parser, "Non-whitespace before first tag."); - parser.textNode = c; - parser.state = S.TEXT; +} +function mergeValues3(a, b) { + const aType = getParsedType3(a); + const bType = getParsedType3(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues3(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0;index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues3(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; } - function charAt(chunk, i) { - var result = ""; - if (i < chunk.length) - result = chunk.charAt(i); - return result; +} +function createZodEnum(values, params) { + return new ZodEnum2({ + values, + typeName: ZodFirstPartyTypeKind2.ZodEnum, + ...processCreateParams(params) + }); +} +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom2(check2, _params = {}, fatal) { + if (check2) + return ZodAny2.create().superRefine((data, ctx) => { + const r = check2(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny2.create(); +} +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error90 = new ZodError2(ctx.common.issues); + this._error = error90; + return this._error; + } + }; } - function write(chunk) { - var parser = this; - if (this.error) - throw this.error; - if (parser.closed) - return error51(parser, "Cannot write after close. Assign an onready handler."); - if (chunk === null) - return end(parser); - if (typeof chunk === "object") - chunk = chunk.toString(); - var i = 0; - var c = ""; - while (true) { - c = charAt(chunk, i++); - parser.c = c; - if (!c) - break; - if (parser.trackPosition) { - parser.position++; - if (c === ` -`) { - parser.line++; - parser.column = 0; - } else - parser.column++; +}, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator = (type) => { + if (type instanceof ZodLazy2) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral2) { + return [type.value]; + } else if (type instanceof ZodEnum2) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault2) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined2) { + return [undefined]; + } else if (type instanceof ZodNull2) { + return [null]; + } else if (type instanceof ZodOptional2) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable2) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly2) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch2) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum, ZodPromise2, ZodEffects, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND, ZodBranded, ZodPipeline, ZodReadonly2, late, ZodFirstPartyTypeKind2, instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom2((data) => data instanceof cls, params), stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce, NEVER3; +var init_types = __esm(() => { + init_ZodError(); + init_errors5(); + init_errorUtil(); + init_parseUtil(); + init_util3(); + cuidRegex = /^c[^\s-]{8,}$/i; + cuid2Regex = /^[0-9a-z]+$/; + ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + nanoidRegex = /^[a-z0-9_-]{21}$/i; + jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + dateRegex = new RegExp(`^${dateRegexSource}$`); + ZodString2 = class ZodString2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); } - switch (parser.state) { - case S.BEGIN: - parser.state = S.BEGIN_WHITESPACE; - if (c === "\uFEFF") - continue; - beginWhiteSpace(parser, c); - continue; - case S.BEGIN_WHITESPACE: - beginWhiteSpace(parser, c); - continue; - case S.TEXT: - if (parser.sawRoot && !parser.closedRoot) { - var starti = i - 1; - while (c && c !== "<" && c !== "&") { - c = charAt(chunk, i++); - if (c && parser.trackPosition) { - parser.position++; - if (c === ` -`) { - parser.line++; - parser.column = 0; - } else - parser.column++; - } - } - parser.textNode += chunk.substring(starti, i - 1); - } - if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else { - if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) - strictFail(parser, "Text data outside of root node."); - if (c === "&") - parser.state = S.TEXT_ENTITY; - else - parser.textNode += c; + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus; + let ctx = undefined; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.length < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); } - continue; - case S.SCRIPT: - if (c === "<") - parser.state = S.SCRIPT_ENDING; - else - parser.script += c; - continue; - case S.SCRIPT_ENDING: - if (c === "/") - parser.state = S.CLOSE_TAG; - else { - parser.script += "<" + c; - parser.state = S.SCRIPT; + } else if (check2.kind === "max") { + if (input.data.length > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); } - continue; - case S.OPEN_WAKA: - if (c === "!") { - parser.state = S.SGML_DECL; - parser.sgmlDecl = ""; - } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { - parser.state = S.OPEN_TAG; - parser.tagName = c; - } else if (c === "/") { - parser.state = S.CLOSE_TAG; - parser.tagName = ""; - } else if (c === "?") { - parser.state = S.PROC_INST; - parser.procInstName = parser.procInstBody = ""; - } else { - strictFail(parser, "Unencoded <"); - if (parser.startTagPosition + 1 < parser.position) { - var pad = parser.position - parser.startTagPosition; - c = new Array(pad).join(" ") + c; + } else if (check2.kind === "length") { + const tooBig = input.data.length > check2.value; + const tooSmall = input.data.length < check2.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); } - parser.textNode += "<" + c; - parser.state = S.TEXT; + status.dirty(); } - continue; - case S.SGML_DECL: - if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { - emitNode(parser, "onopencdata"); - parser.state = S.CDATA; - parser.sgmlDecl = ""; - parser.cdata = ""; - } else if (parser.sgmlDecl + c === "--") { - parser.state = S.COMMENT; - parser.comment = ""; - parser.sgmlDecl = ""; - } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { - parser.state = S.DOCTYPE; - if (parser.doctype || parser.sawRoot) - strictFail(parser, "Inappropriately located doctype declaration"); - parser.doctype = ""; - parser.sgmlDecl = ""; - } else if (c === ">") { - emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); - parser.sgmlDecl = ""; - parser.state = S.TEXT; - } else if (isQuote(c)) { - parser.state = S.SGML_DECL_QUOTED; - parser.sgmlDecl += c; - } else - parser.sgmlDecl += c; - continue; - case S.SGML_DECL_QUOTED: - if (c === parser.q) { - parser.state = S.SGML_DECL; - parser.q = ""; + } else if (check2.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - parser.sgmlDecl += c; - continue; - case S.DOCTYPE: - if (c === ">") { - parser.state = S.TEXT; - emitNode(parser, "ondoctype", parser.doctype); - parser.doctype = true; - } else { - parser.doctype += c; - if (c === "[") - parser.state = S.DOCTYPE_DTD; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_QUOTED; - parser.q = c; - } + } else if (check2.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); } - continue; - case S.DOCTYPE_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.q = ""; - parser.state = S.DOCTYPE; + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.DOCTYPE_DTD: - parser.doctype += c; - if (c === "]") - parser.state = S.DOCTYPE; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_DTD_QUOTED; - parser.q = c; + } else if (check2.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.DOCTYPE_DTD_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.state = S.DOCTYPE_DTD; - parser.q = ""; + } else if (check2.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.COMMENT: - if (c === "-") - parser.state = S.COMMENT_ENDING; - else - parser.comment += c; - continue; - case S.COMMENT_ENDING: - if (c === "-") { - parser.state = S.COMMENT_ENDED; - parser.comment = textopts(parser.opt, parser.comment); - if (parser.comment) - emitNode(parser, "oncomment", parser.comment); - parser.comment = ""; - } else { - parser.comment += "-" + c; - parser.state = S.COMMENT; + } else if (check2.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.COMMENT_ENDED: - if (c !== ">") { - strictFail(parser, "Malformed comment"); - parser.comment += "--" + c; - parser.state = S.COMMENT; - } else - parser.state = S.TEXT; - continue; - case S.CDATA: - if (c === "]") - parser.state = S.CDATA_ENDING; - else - parser.cdata += c; - continue; - case S.CDATA_ENDING: - if (c === "]") - parser.state = S.CDATA_ENDING_2; - else { - parser.cdata += "]" + c; - parser.state = S.CDATA; + } else if (check2.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.CDATA_ENDING_2: - if (c === ">") { - if (parser.cdata) - emitNode(parser, "oncdata", parser.cdata); - emitNode(parser, "onclosecdata"); - parser.cdata = ""; - parser.state = S.TEXT; - } else if (c === "]") - parser.cdata += "]"; - else { - parser.cdata += "]]" + c; - parser.state = S.CDATA; + } else if (check2.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.PROC_INST: - if (c === "?") - parser.state = S.PROC_INST_ENDING; - else if (isWhitespace(c)) - parser.state = S.PROC_INST_BODY; - else - parser.procInstName += c; - continue; - case S.PROC_INST_BODY: - if (!parser.procInstBody && isWhitespace(c)) - continue; - else if (c === "?") - parser.state = S.PROC_INST_ENDING; - else - parser.procInstBody += c; - continue; - case S.PROC_INST_ENDING: - if (c === ">") { - emitNode(parser, "onprocessinginstruction", { - name: parser.procInstName, - body: parser.procInstBody + } else if (check2.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode2.invalid_string, + message: check2.message }); - parser.procInstName = parser.procInstBody = ""; - parser.state = S.TEXT; - } else { - parser.procInstBody += "?" + c; - parser.state = S.PROC_INST_BODY; + status.dirty(); } - continue; - case S.OPEN_TAG: - if (isMatch(nameBody, c)) - parser.tagName += c; - else { - newTag(parser); - if (c === ">") - openTag(parser); - else if (c === "/") - parser.state = S.OPEN_TAG_SLASH; - else { - if (!isWhitespace(c)) - strictFail(parser, "Invalid character in tag name"); - parser.state = S.ATTRIB; - } + } else if (check2.kind === "regex") { + check2.regex.lastIndex = 0; + const testResult = check2.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - case S.OPEN_TAG_SLASH: - if (c === ">") { - openTag(parser, true); - closeTag(parser); - } else { - strictFail(parser, "Forward-slash in opening tag not followed by >"); - parser.state = S.ATTRIB; + } else if (check2.kind === "trim") { + input.data = input.data.trim(); + } else if (check2.kind === "includes") { + if (!input.data.includes(check2.value, check2.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { includes: check2.value, position: check2.position }, + message: check2.message + }); + status.dirty(); } - continue; - case S.ATTRIB: - if (isWhitespace(c)) - continue; - else if (c === ">") - openTag(parser); - else if (c === "/") - parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else - strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME: - if (c === "=") - parser.state = S.ATTRIB_VALUE; - else if (c === ">") { - strictFail(parser, "Attribute without value"); - parser.attribValue = parser.attribName; - attrib(parser); - openTag(parser); - } else if (isWhitespace(c)) - parser.state = S.ATTRIB_NAME_SAW_WHITE; - else if (isMatch(nameBody, c)) - parser.attribName += c; - else - strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME_SAW_WHITE: - if (c === "=") - parser.state = S.ATTRIB_VALUE; - else if (isWhitespace(c)) - continue; - else { - strictFail(parser, "Attribute without value"); - parser.tag.attributes[parser.attribName] = ""; - parser.attribValue = ""; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: "" + } else if (check2.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check2.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check2.kind === "startsWith") { + if (!input.data.startsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { startsWith: check2.value }, + message: check2.message }); - parser.attribName = ""; - if (c === ">") - openTag(parser); - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.state = S.ATTRIB_NAME; - } else { - strictFail(parser, "Invalid attribute name"); - parser.state = S.ATTRIB; - } + status.dirty(); } - continue; - case S.ATTRIB_VALUE: - if (isWhitespace(c)) - continue; - else if (isQuote(c)) { - parser.q = c; - parser.state = S.ATTRIB_VALUE_QUOTED; - } else { - strictFail(parser, "Unquoted attribute value"); - parser.state = S.ATTRIB_VALUE_UNQUOTED; - parser.attribValue = c; + } else if (check2.kind === "endsWith") { + if (!input.data.endsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { endsWith: check2.value }, + message: check2.message + }); + status.dirty(); } - continue; - case S.ATTRIB_VALUE_QUOTED: - if (c !== parser.q) { - if (c === "&") - parser.state = S.ATTRIB_VALUE_ENTITY_Q; - else - parser.attribValue += c; - continue; + } else if (check2.kind === "datetime") { + const regex = datetimeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "datetime", + message: check2.message + }); + status.dirty(); } - attrib(parser); - parser.q = ""; - parser.state = S.ATTRIB_VALUE_CLOSED; - continue; - case S.ATTRIB_VALUE_CLOSED: - if (isWhitespace(c)) - parser.state = S.ATTRIB; - else if (c === ">") - openTag(parser); - else if (c === "/") - parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - strictFail(parser, "No whitespace between attributes"); - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else - strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_VALUE_UNQUOTED: - if (!isAttribEnd(c)) { - if (c === "&") - parser.state = S.ATTRIB_VALUE_ENTITY_U; - else - parser.attribValue += c; - continue; + } else if (check2.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "date", + message: check2.message + }); + status.dirty(); } - attrib(parser); - if (c === ">") - openTag(parser); - else - parser.state = S.ATTRIB; - continue; - case S.CLOSE_TAG: - if (!parser.tagName) - if (isWhitespace(c)) - continue; - else if (notMatch(nameStart, c)) - if (parser.script) { - parser.script += "") - closeTag(parser); - else if (isMatch(nameBody, c)) - parser.tagName += c; - else if (parser.script) { - parser.script += "") - closeTag(parser); - else - strictFail(parser, "Invalid characters in closing tag"); - continue; - case S.TEXT_ENTITY: - case S.ATTRIB_VALUE_ENTITY_Q: - case S.ATTRIB_VALUE_ENTITY_U: - var returnState; - var buffer; - switch (parser.state) { - case S.TEXT_ENTITY: - returnState = S.TEXT; - buffer = "textNode"; - break; - case S.ATTRIB_VALUE_ENTITY_Q: - returnState = S.ATTRIB_VALUE_QUOTED; - buffer = "attribValue"; - break; - case S.ATTRIB_VALUE_ENTITY_U: - returnState = S.ATTRIB_VALUE_UNQUOTED; - buffer = "attribValue"; - break; + } else if (check2.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - if (c === ";") - if (parser.opt.unparsedEntities) { - var parsedEntity = parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - parser.write(parsedEntity); - } else { - parser[buffer] += parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - } - else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) - parser.entity += c; - else { - strictFail(parser, "Invalid character in entity name"); - parser[buffer] += "&" + parser.entity + c; - parser.entity = ""; - parser.state = returnState; + } else if (check2.kind === "ip") { + if (!isValidIP(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - continue; - default: - throw new Error(parser, "Unknown state: " + parser.state); - } - } - if (parser.position >= parser.bufferCheckPosition) - checkBufferLength(parser); - return parser; - } - /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ - if (!String.fromCodePoint) - (function() { - var stringFromCharCode = String.fromCharCode; - var floor = Math.floor; - var fromCodePoint = function() { - var MAX_SIZE = 16384; - var codeUnits = []; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) - return ""; - var result = ""; - while (++index < length) { - var codePoint = Number(arguments[index]); - if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) - throw RangeError("Invalid code point: " + codePoint); - if (codePoint <= 65535) - codeUnits.push(codePoint); - else { - codePoint -= 65536; - highSurrogate = (codePoint >> 10) + 55296; - lowSurrogate = codePoint % 1024 + 56320; - codeUnits.push(highSurrogate, lowSurrogate); + } else if (check2.kind === "jwt") { + if (!isValidJWT3(input.data, check2.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } - if (index + 1 === length || codeUnits.length > MAX_SIZE) { - result += stringFromCharCode.apply(null, codeUnits); - codeUnits.length = 0; + } else if (check2.kind === "cidr") { + if (!isValidCidr(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode2.invalid_string, + message: check2.message + }); + status.dirty(); } + } else { + util.assertNever(check2); } - return result; - }; - if (Object.defineProperty) - Object.defineProperty(String, "fromCodePoint", { - value: fromCodePoint, - configurable: true, - writable: true - }); - else - String.fromCodePoint = fromCodePoint; - })(); - return sax; -}, sax; -var init_sax = __esm(() => { - sax = initializeSax(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/xml.js -function parseXMLMarkdown(s) { - const cleanedString = strip(s); - const parser = sax.parser(true); - let parsedResult = {}; - const elementStack = []; - parser.onopentag = (node) => { - const element = { - name: node.name, - attributes: node.attributes, - children: [], - text: "", - isSelfClosing: node.isSelfClosing - }; - if (elementStack.length > 0) - elementStack[elementStack.length - 1].children.push(element); - else - parsedResult = element; - if (!node.isSelfClosing) - elementStack.push(element); - }; - parser.onclosetag = () => { - if (elementStack.length > 0) { - const lastElement = elementStack.pop(); - if (elementStack.length === 0 && lastElement) - parsedResult = lastElement; - } - }; - parser.ontext = (text) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.text += text; + } + return { status: status.value, value: input.data }; } - }; - parser.onattribute = (attr) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.attributes[attr.name] = attr.value; + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode2.invalid_string, + ...errorUtil.errToObj(message) + }); } - }; - const match2 = /```(xml)?(.*)```/s.exec(cleanedString); - const xmlString = match2 ? match2[2] : cleanedString; - parser.write(xmlString).close(); - if (parsedResult && parsedResult.name === "?xml") - parsedResult = parsedResult.children[0]; - return parseParsedResult(parsedResult); -} -var XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. -1. Output should conform to the tags below. -2. If tags are not given, make them on your own. -3. Remember to always open and close all the tags. - -As an example, for the tags ["foo", "bar", "baz"]: -1. String " - - - -" is a well-formatted instance of the schema. -2. String " - - " is a badly-formatted instance. -3. String " - - -" is a badly-formatted instance. - -Here are the output tags: -\`\`\` -{tags} -\`\`\``, XMLOutputParser, strip = (text) => text.split(` -`).map((line) => line.replace(/^\s+/, "")).join(` -`).trim(), parseParsedResult = (input) => { - if (Object.keys(input).length === 0) - return {}; - const result = {}; - if (input.children.length > 0) { - result[input.name] = input.children.map(parseParsedResult); - return result; - } else { - result[input.name] = input.text ?? undefined; - return result; - } -}; -var init_xml = __esm(() => { - init_duplex(); - init_transform(); - init_json_patch(); - init_sax(); - XMLOutputParser = class extends BaseCumulativeTransformOutputParser { - tags; - constructor(fields) { - super(fields); - this.tags = fields?.tags; + _addCheck(check2) { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - static lc_name() { - return "XMLOutputParser"; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - _diff(prev, next) { - if (!next) - return; - if (!prev) - return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } - async parsePartialResult(generations) { - return parseXMLMarkdown(generations[0].text); + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } - async parse(text) { - return parseXMLMarkdown(text); + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } - getFormatInstructions() { - return this.tags && this.tags.length > 0 ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/index.js -var output_parsers_exports; -var init_output_parsers = __esm(() => { - init_runtime2(); - init_json(); - init_base6(); - init_transform(); - init_bytes(); - init_list(); - init_string2(); - init_json2(); - init_standard_schema2(); - init_structured(); - init_xml(); - output_parsers_exports = /* @__PURE__ */ __exportAll({ - AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, - BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, - BaseLLMOutputParser: () => BaseLLMOutputParser, - BaseOutputParser: () => BaseOutputParser, - BaseTransformOutputParser: () => BaseTransformOutputParser, - BytesOutputParser: () => BytesOutputParser, - CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, - CustomListOutputParser: () => CustomListOutputParser, - JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, - JsonOutputParser: () => JsonOutputParser, - ListOutputParser: () => ListOutputParser, - MarkdownListOutputParser: () => MarkdownListOutputParser, - NumberedListOutputParser: () => NumberedListOutputParser, - OutputParserException: () => OutputParserException, - StandardSchemaOutputParser: () => StandardSchemaOutputParser, - StringOutputParser: () => StringOutputParser, - StructuredOutputParser: () => StructuredOutputParser, - XMLOutputParser: () => XMLOutputParser, - XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, - parseJsonMarkdown: () => parseJsonMarkdown, - parsePartialJson: () => parsePartialJson, - parseXMLMarkdown: () => parseXMLMarkdown - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js -function parseToolCall(rawToolCall, options) { - if (rawToolCall.function === undefined) - return; - let functionArgs; - if (options?.partial) - try { - functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); - } catch { - return; + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } - else - try { - functionArgs = JSON.parse(rawToolCall.function.arguments); - } catch (e) { - throw new OutputParserException([ - `Function "${rawToolCall.function.name}" arguments:`, - ``, - rawToolCall.function.arguments, - ``, - `are not valid JSON.`, - `Error: ${e.message}` - ].join(` -`)); + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } - const parsedToolCall = { - name: rawToolCall.function.name, - args: functionArgs, - type: "tool_call" - }; - if (options?.returnId) - parsedToolCall.id = rawToolCall.id; - return parsedToolCall; -} -function convertLangChainToolCallToOpenAI(toolCall) { - if (toolCall.id === undefined) - throw new Error(`All OpenAI tool calls must have an "id" field.`); - return { - id: toolCall.id, - type: "function", - function: { - name: toolCall.name, - arguments: JSON.stringify(toolCall.args) + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } - }; -} -function makeInvalidToolCall(rawToolCall, errorMsg) { - return { - name: rawToolCall.function?.name, - args: rawToolCall.function?.arguments, - id: rawToolCall.id, - error: errorMsg, - type: "invalid_tool_call" - }; -} -var JsonOutputToolsParser, JsonOutputKeyToolsParser; -var init_json_output_tools_parsers = __esm(() => { - init_json(); - init_ai(); - init_zod2(); - init_base6(); - init_transform(); - init_json2(); - JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputToolsParser"; + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } - returnId = false; - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - constructor(fields) { - super(fields); - this.returnId = fields?.returnId ?? this.returnId; + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); } - _diff() { - throw new Error("Not supported."); + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); } - async parse() { - throw new Error("Not implemented."); + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } - async parseResult(generations) { - return await this.parsePartialResult(generations, false); + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } - async parsePartialResult(generations, partial2 = true) { - const message = generations[0].message; - let toolCalls; - if (isAIMessage(message) && message.tool_calls?.length) - toolCalls = message.tool_calls.map((toolCall) => { - const { id, ...rest } = toolCall; - if (!this.returnId) - return rest; - return { - id, - ...rest - }; - }); - else if (message.additional_kwargs.tool_calls !== undefined) - toolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)).map((rawToolCall) => { - return parseToolCall(rawToolCall, { - returnId: this.returnId, - partial: partial2 - }); + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options }); - if (!toolCalls) - return []; - const parsedToolCalls = []; - for (const toolCall of toolCalls) - if (toolCall !== undefined) { - const backwardsCompatibleToolCall = { - type: toolCall.name, - args: toolCall.args, - id: toolCall.id - }; - parsedToolCalls.push(backwardsCompatibleToolCall); - } - return parsedToolCalls; - } - }; - JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { - static lc_name() { - return "JsonOutputKeyToolsParser"; + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - returnId = false; - keyName; - returnSingle = false; - zodSchema; - serializableSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - if ("zodSchema" in params) - this.zodSchema = params.zodSchema; - if ("serializableSchema" in params) - this.serializableSchema = params.serializableSchema; + date(message) { + return this._addCheck({ kind: "date", message }); } - async _validateResult(result) { - if (this.serializableSchema !== undefined) { - const validated = await this.serializableSchema["~standard"].validate(result); - if (validated.issues) - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(result, null, 2)); - return validated.value; + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); } - if (this.zodSchema === undefined) - return result; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); - if (zodParsedResult.success) - return zodParsedResult.data; - else - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); - } - async parsePartialResult(generations) { - const matchingResults = (await super.parsePartialResult(generations)).filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) - return; - if (!this.returnId) - returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) - return returnedValues[0]; - return returnedValues; + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); } - async parseResult(generations) { - const matchingResults = (await super.parsePartialResult(generations, false)).filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) - return; - if (!this.returnId) - returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) - return this._validateResult(returnedValues[0]); - return await Promise.all(returnedValues.map((value) => this._validateResult(value))); + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/types/index.js -var types_exports; -var init_types3 = __esm(() => { - init_runtime2(); - init_zod2(); - types_exports = /* @__PURE__ */ __exportAll({ - extendInteropZodObject: () => extendInteropZodObject, - getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, - getInteropZodObjectShape: () => getInteropZodObjectShape, - getSchemaDescription: () => getSchemaDescription, - interopParse: () => interopParse, - interopParseAsync: () => interopParseAsync, - interopSafeParse: () => interopSafeParse, - interopSafeParseAsync: () => interopSafeParseAsync, - interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, - interopZodObjectPartial: () => interopZodObjectPartial, - interopZodObjectPassthrough: () => interopZodObjectPassthrough, - interopZodObjectStrict: () => interopZodObjectStrict, - interopZodTransformInputSchema: () => interopZodTransformInputSchema, - isInteropZodError: () => isInteropZodError, - isInteropZodLiteral: () => isInteropZodLiteral, - isInteropZodObject: () => isInteropZodObject, - isInteropZodSchema: () => isInteropZodSchema, - isShapelessZodSchema: () => isShapelessZodSchema, - isSimpleStringZodSchema: () => isSimpleStringZodSchema, - isZodArrayV4: () => isZodArrayV4, - isZodLiteralV3: () => isZodLiteralV3, - isZodLiteralV4: () => isZodLiteralV4, - isZodNullableV4: () => isZodNullableV4, - isZodObjectV3: () => isZodObjectV3, - isZodObjectV4: () => isZodObjectV4, - isZodOptionalV4: () => isZodOptionalV4, - isZodSchema: () => isZodSchema, - isZodSchemaV3: () => isZodSchemaV3, - isZodSchemaV4: () => isZodSchemaV4 - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/structured_output.js -function createContentParser(schema) { - if (isInteropZodSchema(schema)) - return StructuredOutputParser.fromZodSchema(schema); - if (isSerializableSchema(schema)) - return StandardSchemaOutputParser.fromSerializableSchema(schema); - return new JsonOutputParser; -} -function createFunctionCallingParser(schema, keyName, ParserClass) { - const Ctor = ParserClass ?? JsonOutputKeyToolsParser; - if (isInteropZodSchema(schema)) - return new Ctor({ - returnSingle: true, - keyName, - zodSchema: schema - }); - if (isSerializableSchema(schema)) - return new Ctor({ - returnSingle: true, - keyName, - serializableSchema: schema - }); - return new Ctor({ - returnSingle: true, - keyName - }); -} -function assembleStructuredOutputPipeline(llm, outputParser, includeRaw, runName) { - if (!includeRaw) { - const result2 = llm.pipe(outputParser); - return runName ? result2.withConfig({ runName }) : result2; - } - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config2) => outputParser.invoke(input.raw, config2) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - const result = RunnableSequence.from([{ raw: llm }, parsedWithFallback]); - return runName ? result.withConfig({ runName }) : result; -} -var structured_output_exports; -var init_structured_output = __esm(() => { - init_runtime2(); - init_zod2(); - init_standard_schema(); - init_base4(); - init_passthrough(); - init_runnables(); - init_json2(); - init_standard_schema2(); - init_structured(); - init_output_parsers(); - init_json_output_tools_parsers(); - init_types3(); - structured_output_exports = /* @__PURE__ */ __exportAll({ - assembleStructuredOutputPipeline: () => assembleStructuredOutputPipeline, - createContentParser: () => createContentParser, - createFunctionCallingParser: () => createFunctionCallingParser - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/stream.js -function applyDelta(block, delta) { - switch (delta.type) { - case "text-delta": - if (block.type === "text") - return { - ...block, - text: (block.text ?? "") + delta.text - }; - return block; - case "reasoning-delta": - if (block.type === "thinking") - return { - ...block, - thinking: (block.thinking ?? "") + delta.reasoning - }; - if (block.type === "reasoning") - return { - ...block, - reasoning: (block.reasoning ?? "") + delta.reasoning - }; - return block; - case "data-delta": - return { - ...block, - data: (block.data ?? "") + delta.data - }; - case "block-delta": - return { - ...block, - ...delta.fields - }; - default: - throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); - } -} -function getEventDelta(event) { - if (event.event !== "content-block-delta") - return; - if ("delta" in event && event.delta) - return event.delta; - const content = event.content; - if (content == null || typeof content !== "object") - return; - const block = content; - if (block.type === "text" && typeof block.text === "string") - return { - type: "text-delta", - text: block.text - }; - if (block.type === "reasoning" && typeof block.reasoning === "string") - return { - type: "reasoning-delta", - reasoning: block.reasoning - }; - if (block.type === "thinking" && typeof block.thinking === "string") - return { - type: "reasoning-delta", - reasoning: block.thinking - }; - if (typeof block.data === "string") - return { - type: "data-delta", - data: block.data, - encoding: "base64" - }; - if (typeof block.type === "string") - return { - type: "block-delta", - fields: { - ...block, - type: block.type - } - }; -} -function getReasoningDelta(content) { - if (content == null || typeof content !== "object") - return; - const block = content; - if (block.type === "reasoning" && typeof block.reasoning === "string") - return block.reasoning; - if (block.type === "thinking" && typeof block.thinking === "string") - return block.thinking; -} -function isReasoningContent(content) { - if (content == null || typeof content !== "object") - return false; - const type = content.type; - return type === "reasoning" || type === "thinking"; -} -function normalizeUsage(usage) { - if (!usage) - return; - return { - ...usage, - input_tokens: usage.input_tokens ?? 0, - output_tokens: usage.output_tokens ?? 0, - total_tokens: usage.total_tokens ?? 0 - }; -} -function parseToolArgs(value) { - if (value != null && typeof value === "object" && !Array.isArray(value)) - return value; - if (typeof value !== "string" || value.length === 0) - return {}; - try { - const parsed = JSON.parse(value); - return parsed != null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; - } catch { - return {}; - } -} -function standardizeToolBlock(block) { - const record2 = block; - if (block.type === "tool_call") - return block; - if (block.type !== "tool_call_chunk" && block.type !== "tool_use" && block.type !== "input_json_delta") - return block; - const name = typeof record2.name === "string" ? record2.name : undefined; - if (name == null) - return block; - const args = record2.args ?? record2.input; - return { - ...record2, - type: "tool_call", - name, - args: parseToolArgs(args) - }; -} -var stream_exports2, ReplayBuffer2 = class { - events = []; - finished = false; - waiters = []; - error = null; - push(event) { - this.events.push(event); - const toWake = this.waiters.splice(0); - for (const waiter of toWake) - waiter(); - } - finish() { - this.finished = true; - const toWake = this.waiters.splice(0); - for (const waiter of toWake) - waiter(); - } - setError(err) { - this.error = err; - this.finished = true; - const toWake = this.waiters.splice(0); - for (const waiter of toWake) - waiter(); - } - async* iterate() { - if (this.finished) { - if (this.error) - throw this.error; - yield* this.events; - return; + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); } - let cursor = 0; - while (true) { - while (cursor < this.events.length) { - yield this.events[cursor]; - cursor++; - } - if (this.finished) { - if (this.error) - throw this.error; - return; - } - await new Promise((resolve2) => { - if (cursor < this.events.length || this.finished) { - resolve2(); - return; - } - this.waiters.push(resolve2); + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) }); } - } -}, TextContentStream, ToolCallsStream, ReasoningContentStream, UsageMetadataStream, ChatModelStream; -var init_stream2 = __esm(() => { - init_runtime2(); - init_ai(); - stream_exports2 = /* @__PURE__ */ __exportAll({ - ChatModelStream: () => ChatModelStream, - ReasoningContentStream: () => ReasoningContentStream, - TextContentStream: () => TextContentStream, - ToolCallsStream: () => ToolCallsStream, - UsageMetadataStream: () => UsageMetadataStream - }); - TextContentStream = class { - _buffer; - constructor(buffer) { - this._buffer = buffer; + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); } - get full() { - const buffer = this._buffer; - return { async* [Symbol.asyncIterator]() { - let accumulated = ""; - for await (const event of buffer.iterate()) { - const delta = getEventDelta(event); - if (delta?.type === "text-delta") { - accumulated += delta.text; - yield accumulated; - } - } - } }; + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); } - [Symbol.asyncIterator]() { - const buffer = this._buffer; - async function* gen() { - for await (const event of buffer.iterate()) { - const delta = getEventDelta(event); - if (delta?.type === "text-delta") - yield delta.text; - } - } - return gen(); + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); } - then(onfulfilled, onrejected) { - return (async () => { - let text = ""; - for await (const delta of this) - text += delta; - return text; - })().then(onfulfilled, onrejected); + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); } - }; - ToolCallsStream = class { - _buffer; - constructor(buffer) { - this._buffer = buffer; + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); } - get full() { - const buffer = this._buffer; - return { async* [Symbol.asyncIterator]() { - const calls = []; - for await (const event of buffer.iterate()) - if (event.event === "content-block-finish" && event.content.type === "tool_call") { - calls.push(event.content); - yield [...calls]; - } - } }; + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); } - [Symbol.asyncIterator]() { - const buffer = this._buffer; - async function* gen() { - for await (const event of buffer.iterate()) - if (event.event === "content-block-finish" && event.content.type === "tool_call") - yield event.content; - } - return gen(); + trim() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); } - then(onfulfilled, onrejected) { - return (async () => { - const calls = []; - for await (const call of this) - calls.push(call); - return calls; - })().then(onfulfilled, onrejected); + toLowerCase() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); } - }; - ReasoningContentStream = class { - _buffer; - constructor(buffer) { - this._buffer = buffer; + toUpperCase() { + return new ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); } - get full() { - const buffer = this._buffer; - return { async* [Symbol.asyncIterator]() { - let accumulated = ""; - let seenReasoning = false; - for await (const event of buffer.iterate()) - if (event.event === "content-block-start") { - if (!isReasoningContent(event.content)) { - if (seenReasoning) - return; - continue; - } - seenReasoning = true; - const delta = getReasoningDelta(event.content); - if (delta == null || delta.length === 0) - continue; - accumulated += delta; - yield accumulated; - } else if (event.event === "content-block-delta") { - const eventDelta = getEventDelta(event); - if (eventDelta?.type !== "reasoning-delta") - continue; - seenReasoning = true; - const delta = eventDelta.reasoning; - if (delta == null || delta.length === 0) - continue; - accumulated += delta; - yield accumulated; - } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) - return; - else if (event.event === "message-finish") - return; - } }; + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); } - [Symbol.asyncIterator]() { - const buffer = this._buffer; - async function* gen() { - let seenReasoning = false; - for await (const event of buffer.iterate()) - if (event.event === "content-block-start") { - if (!isReasoningContent(event.content)) { - if (seenReasoning) - return; - continue; - } - seenReasoning = true; - const delta = getReasoningDelta(event.content); - if (delta != null && delta.length > 0) - yield delta; - } else if (event.event === "content-block-delta") { - const eventDelta = getEventDelta(event); - if (eventDelta?.type !== "reasoning-delta") - continue; - seenReasoning = true; - const delta = eventDelta.reasoning; - if (delta != null && delta.length > 0) - yield delta; - } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) - return; - else if (event.event === "message-finish") - return; - } - return gen(); + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); } - then(onfulfilled, onrejected) { - return (async () => { - let text = ""; - for await (const delta of this) - text += delta; - return text; - })().then(onfulfilled, onrejected); + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); } - }; - UsageMetadataStream = class { - _buffer; - constructor(buffer) { - this._buffer = buffer; + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); } - [Symbol.asyncIterator]() { - const buffer = this._buffer; - async function* gen() { - for await (const event of buffer.iterate()) - if (event.event === "usage") { - const usage = normalizeUsage(event.usage); - if (usage) - yield usage; - } else if (event.event === "message-start" && event.usage) { - const usage = normalizeUsage(event.usage); - if (usage) - yield usage; - } else if (event.event === "message-finish" && event.usage) { - const usage = normalizeUsage(event.usage); - if (usage) - yield usage; - } - } - return gen(); + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); } - then(onfulfilled, onrejected) { - return (async () => { - let latest; - for await (const usage of this) - latest = usage; - return latest; - })().then(onfulfilled, onrejected); + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); } - }; - ChatModelStream = class { - _buffer; - constructor(source) { - this._buffer = new ReplayBuffer2; - this._consume(source); + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); } - async _consume(source) { - try { - for await (const event of source) - this._buffer.push(event); - this._buffer.finish(); - } catch (err) { - this._buffer.setError(err instanceof Error ? err : new Error(String(err))); - } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); } - [Symbol.asyncIterator]() { - return this._buffer.iterate(); + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); } - get text() { - return new TextContentStream(this._buffer); + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); } - get toolCalls() { - return new ToolCallsStream(this._buffer); + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } - get reasoning() { - return new ReasoningContentStream(this._buffer); + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); } - get usage() { - return new UsageMetadataStream(this._buffer); + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); } - get output() { - return this._assembleMessage(); + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); } - then(onfulfilled, onrejected) { - return this._assembleMessage().then(onfulfilled, onrejected); + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); } - async _assembleMessage() { - const contentBlocks = []; - let id; - let usage; - let metadata = {}; - let finishReason; - for await (const event of this._buffer.iterate()) - switch (event.event) { - case "message-start": - id = event.id ?? id; - if (event.usage) - usage = normalizeUsage(event.usage); - break; - case "content-block-start": - contentBlocks[event.index] = event.content; - break; - case "content-block-delta": { - const current = contentBlocks[event.index]; - const delta = getEventDelta(event); - if (current) { - if (delta) - contentBlocks[event.index] = applyDelta(current, delta); - } - break; - } - case "content-block-finish": - contentBlocks[event.index] = event.content; - break; - case "usage": - usage = normalizeUsage(event.usage); - break; - case "message-finish": - finishReason = event.reason; - if (event.usage) - usage = normalizeUsage(event.usage); - if (event.responseMetadata) - metadata = { - ...metadata, - ...event.responseMetadata - }; - break; - default: - break; + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - const filteredBlocks = contentBlocks.filter((b) => b != null).map(standardizeToolBlock); - return new AIMessage({ - id, - content: filteredBlocks, - usage_metadata: usage, - response_metadata: { - ...metadata, - ...finishReason ? { finish_reason: finishReason } : {}, - output_version: "v1" + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - }); + } + return max; } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/compat.js -function nextBlockIndex(activeBlocks) { - let next = 0; - for (const index of activeBlocks.keys()) - if (index >= next) - next = index + 1; - return next; -} -function getAdditionalKwargs(message) { - const additional = message.additional_kwargs; - return additional != null && typeof additional === "object" ? additional : {}; -} -function extractImageBlocksFromToolOutputs(message) { - const toolOutputs = getAdditionalKwargs(message).tool_outputs; - if (!Array.isArray(toolOutputs)) - return []; - const blocks2 = []; - for (const entry of toolOutputs) { - if (entry == null || typeof entry !== "object") - continue; - const record2 = entry; - if (record2.type !== "image_generation_call") - continue; - const data = typeof record2.result === "string" ? record2.result : undefined; - const url2 = typeof record2.url === "string" ? record2.url : undefined; - if (data == null && url2 == null) - continue; - const outputFormat = typeof record2.output_format === "string" ? record2.output_format.toLowerCase() : undefined; - const mimeType = (outputFormat != null ? MIME_TYPE_BY_IMAGE_FORMAT[outputFormat] : undefined) ?? "image/png"; - blocks2.push({ - type: "image", - ...typeof record2.id === "string" ? { id: record2.id } : {}, - ...url2 != null ? { url: url2 } : {}, - ...data != null ? { data } : {}, - mimeType + ZodString2.create = (params) => { + return new ZodString2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) }); - } - return blocks2; -} -function getAudioPayload(message) { - const audio = getAdditionalKwargs(message).audio; - if (audio == null || typeof audio !== "object") - return; - const record2 = audio; - const data = typeof record2.data === "string" ? record2.data : undefined; - const url2 = typeof record2.url === "string" ? record2.url : undefined; - const transcript = typeof record2.transcript === "string" ? record2.transcript : undefined; - if (data == null && url2 == null && transcript == null) - return; - const explicitMimeType = typeof record2.mime_type === "string" ? record2.mime_type : typeof record2.mimeType === "string" ? record2.mimeType : undefined; - const format3 = typeof record2.format === "string" ? record2.format.toLowerCase() : undefined; - const mimeType = explicitMimeType ?? (format3 != null ? MIME_TYPE_BY_AUDIO_FORMAT[format3] : undefined) ?? (data != null ? "audio/wav" : "audio/pcm"); - return { - ...typeof record2.id === "string" ? { id: record2.id } : {}, - ...data != null ? { data } : {}, - ...url2 != null ? { url: url2 } : {}, - ...transcript != null ? { transcript } : {}, - mimeType }; -} -async function* convertChunksToEvents(chunks, options) { - const activeBlocks = /* @__PURE__ */ new Map; - let messageStarted = false; - let lastUsage; - let audioStream; - const emittedImageKeys = /* @__PURE__ */ new Set; - for await (const chunk of chunks) { - options?.signal?.throwIfAborted(); - const msg = chunk.message; - let usageHandledInStart = false; - if (!messageStarted) { - messageStarted = true; - const startEvent = { - event: "message-start", - id: msg.id ?? undefined - }; - if (AIMessageChunk.isInstance(msg) && msg.usage_metadata) { - startEvent.usage = msg.usage_metadata; - lastUsage = { ...msg.usage_metadata }; - usageHandledInStart = true; - } - yield startEvent; + ZodNumber2 = class ZodNumber2 extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; } - const content = msg.content; - if (typeof content === "string") { - if (content !== "") { - const blockIndex = 0; - if (!activeBlocks.has(blockIndex)) { - const initial = { - type: "text", - text: "" - }; - activeBlocks.set(blockIndex, { - type: "text", - accumulated: initial - }); - yield { - event: "content-block-start", - index: blockIndex, - content: initial - }; - } - const block = activeBlocks.get(blockIndex); - block.accumulated = { - ...block.accumulated, - text: (block.accumulated.text ?? "") + content - }; - yield { - event: "content-block-delta", - index: blockIndex, - delta: { - type: "text-delta", - text: content - } - }; - } - } else if (Array.isArray(content)) - for (const part of content) { - const blockIndex = typeof part.index === "number" ? part.index : activeBlocks.size; - if (!activeBlocks.has(blockIndex)) { - activeBlocks.set(blockIndex, { - type: part.type, - accumulated: { ...part } - }); - yield { - event: "content-block-start", - index: blockIndex, - content: { ...part } - }; - } else { - const block = activeBlocks.get(blockIndex); - const delta = contentBlockToDelta(part); - block.accumulated = applyDeltaToBlock(block.accumulated, delta); - yield { - event: "content-block-delta", - index: blockIndex, - delta - }; - } - } - if (AIMessageChunk.isInstance(msg) && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) - for (const toolChunk of msg.tool_call_chunks) { - const blockIndex = typeof toolChunk.index === "number" ? toolChunk.index : activeBlocks.size; - if (!activeBlocks.has(blockIndex)) { - const initial = { - type: "tool_call_chunk", - id: toolChunk.id, - name: toolChunk.name, - args: "", - index: blockIndex - }; - activeBlocks.set(blockIndex, { - type: "tool_call_chunk", - accumulated: initial - }); - yield { - event: "content-block-start", - index: blockIndex, - content: initial - }; - } - const acc = activeBlocks.get(blockIndex).accumulated; - if (toolChunk.id != null) - acc.id = toolChunk.id; - if (toolChunk.name != null) - acc.name = toolChunk.name; - acc.args = (acc.args ?? "") + (toolChunk.args ?? ""); - yield { - event: "content-block-delta", - index: blockIndex, - delta: { - type: "block-delta", - fields: { - type: "tool_call_chunk", - ..."id" in acc && acc.id != null ? { id: acc.id } : {}, - ..."name" in acc && acc.name != null ? { name: acc.name } : {}, - args: acc.args - } - } - }; + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); } - const audioPayload = getAudioPayload(msg); - if (audioPayload != null) { - if (audioStream == null) { - const index = nextBlockIndex(activeBlocks); - audioStream = { - index, - id: audioPayload.id, - mimeType: audioPayload.mimeType, - transcript: "" - }; - const initial = { - type: "audio", - ...audioPayload.id != null ? { id: audioPayload.id } : {}, - ...audioPayload.url != null ? { url: audioPayload.url } : {}, - data: "", - mimeType: audioPayload.mimeType - }; - activeBlocks.set(index, { - type: "audio", - accumulated: initial + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType }); - yield { - event: "content-block-start", - index, - content: initial - }; + return INVALID; } - const activeAudio = activeBlocks.get(audioStream.index); - if (activeAudio != null) { - const accumulated = activeAudio.accumulated; - if (audioPayload.id != null && audioStream.id == null) { - audioStream.id = audioPayload.id; - accumulated.id = audioPayload.id; - } - if (audioPayload.transcript != null) { - audioStream.transcript += audioPayload.transcript; - accumulated.transcript = audioStream.transcript; - yield { - event: "content-block-delta", - index: audioStream.index, - delta: { - type: "block-delta", - fields: { - type: "audio", - transcript: audioStream.transcript - } - } - }; - } - if (audioPayload.data != null && audioPayload.data.length > 0) { - accumulated.data = (accumulated.data ?? "") + audioPayload.data; - yield { - event: "content-block-delta", - index: audioStream.index, - delta: { - type: "data-delta", - data: audioPayload.data, - encoding: "base64" - } - }; + let ctx = undefined; + const status = new ParseStatus; + for (const check2 of this._def.checks) { + if (check2.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: "integer", + received: "float", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (floatSafeRemainder3(input.data, check2.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_finite, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); } } + return { status: status.value, value: input.data }; } - for (const imageBlock of extractImageBlocksFromToolOutputs(msg)) { - const imageRecord = imageBlock; - const imageKey = imageRecord.id ?? imageRecord.url ?? (imageRecord.data != null ? `${imageRecord.data.length}:${imageRecord.data.slice(0, 32)}` : undefined); - if (imageKey != null && emittedImageKeys.has(imageKey)) - continue; - if (imageKey != null) - emittedImageKeys.add(imageKey); - const index = nextBlockIndex(activeBlocks); - activeBlocks.set(index, { - type: "image", - accumulated: imageBlock + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber2({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] }); - yield { - event: "content-block-start", - index, - content: imageBlock - }; } - if (!usageHandledInStart && AIMessageChunk.isInstance(msg) && msg.usage_metadata) { - const chunkUsage = msg.usage_metadata; - if (!lastUsage) - lastUsage = { ...chunkUsage }; - else - lastUsage = { - input_tokens: lastUsage.input_tokens + chunkUsage.input_tokens, - output_tokens: lastUsage.output_tokens + chunkUsage.output_tokens, - total_tokens: lastUsage.total_tokens + chunkUsage.total_tokens - }; - yield { - event: "usage", - usage: { ...lastUsage } - }; + _addCheck(check2) { + return new ZodNumber2({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - } - for (const [index, block] of activeBlocks) - yield { - event: "content-block-finish", - index, - content: finalizeContentBlock(block.accumulated) - }; - yield { - event: "message-finish", - reason: "stop", - ...lastUsage ? { usage: lastUsage } : {} - }; -} -function applyDeltaToBlock(block, delta) { - switch (delta.type) { - case "text-delta": - if (block.type === "text") - return { - ...block, - text: (block.text ?? "") + delta.text - }; - return block; - case "reasoning-delta": - if (block.type === "thinking") - return { - ...block, - thinking: (block.thinking ?? "") + delta.reasoning - }; - if (block.type === "reasoning") - return { - ...block, - reasoning: (block.reasoning ?? "") + delta.reasoning - }; - return block; - case "data-delta": - return { - ...block, - data: (block.data ?? "") + delta.data - }; - case "block-delta": - return { - ...block, - ...delta.fields - }; - default: - throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); - } -} -function contentBlockToDelta(block) { - if (block.type === "text") - return { - type: "text-delta", - text: block.text - }; - if (block.type === "reasoning") - return { - type: "reasoning-delta", - reasoning: block.reasoning - }; - if (block.type === "thinking" && typeof block.thinking === "string") - return { - type: "reasoning-delta", - reasoning: block.thinking - }; - if (typeof block.data === "string") - return { - type: "data-delta", - data: block.data, - encoding: "base64" - }; - if (typeof block.type === "string") - return { - type: "block-delta", - fields: { ...block } - }; - throw new Error(`Unsupported content block delta: ${JSON.stringify(block)}`); -} -function finalizeContentBlock(block) { - if (block.type === "tool_call_chunk") { - const chunk = block; - let parsedArgs; - try { - parsedArgs = JSON.parse(chunk.args ?? "{}"); - } catch { - return { - type: "invalid_tool_call", - id: chunk.id, - name: chunk.name, - args: chunk.args, - error: "Failed to parse tool call arguments as JSON" - }; + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); } - return { - type: "tool_call", - id: chunk.id, - name: chunk.name, - args: parsedArgs - }; - } - return block; -} -var compat_exports, MIME_TYPE_BY_AUDIO_FORMAT, MIME_TYPE_BY_IMAGE_FORMAT; -var init_compat2 = __esm(() => { - init_runtime2(); - init_ai(); - compat_exports = /* @__PURE__ */ __exportAll({ - convertChunksToEvents: () => convertChunksToEvents, - finalizeContentBlock: () => finalizeContentBlock - }); - MIME_TYPE_BY_AUDIO_FORMAT = { - wav: "audio/wav", - mp3: "audio/mpeg", - flac: "audio/flac", - opus: "audio/opus", - aac: "audio/aac", - pcm16: "audio/pcm" - }; - MIME_TYPE_BY_IMAGE_FORMAT = { - png: "image/png", - jpeg: "image/jpeg", - jpg: "image/jpeg", - webp: "image/webp", - gif: "image/gif" - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/chat_models.js -function _formatForTracing(messages) { - const messagesToTrace = []; - for (const message of messages) { - let messageToTrace = message; - if (Array.isArray(message.content)) - for (let idx = 0;idx < message.content.length; idx++) { - const block = message.content[idx]; - if (isURLContentBlock(block) || isBase64ContentBlock(block)) { - if (messageToTrace === message) - messageToTrace = new message.constructor({ - ...messageToTrace, - content: [ - ...message.content.slice(0, idx), - convertToOpenAIImageBlock(block), - ...message.content.slice(idx + 1) - ] - }); - } - } - messagesToTrace.push(messageToTrace); - } - return messagesToTrace; -} -var chat_models_exports, BaseChatModel, SimpleChatModel; -var init_chat_models = __esm(() => { - init_runtime2(); - init_errors3(); - init_data(); - init_base(); - init_ai(); - init_utils3(); - init_env(); - init_base2(); - init_manager(); - init_stream(); - init_outputs(); - init_zod2(); - init_standard_schema(); - init_json_schema2(); - init_base4(); - init_messages(); - init_base5(); - init_utils5(); - init_structured_output(); - init_stream2(); - init_compat2(); - chat_models_exports = /* @__PURE__ */ __exportAll({ - BaseChatModel: () => BaseChatModel, - SimpleChatModel: () => SimpleChatModel - }); - BaseChatModel = class BaseChatModel2 extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "chat_models", - this._llmType() - ]; - disableStreaming = false; - outputVersion; - get callKeys() { - return [...super.callKeys, "outputVersion"]; + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); } - constructor(fields) { - super(fields); - this.outputVersion = iife3(() => { - const outputVersion = fields.outputVersion ?? getEnvironmentVariable("LC_OUTPUT_VERSION"); - if (outputVersion && ["v0", "v1"].includes(outputVersion)) - return outputVersion; - return "v0"; + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) }); } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); } - async invoke(input, options) { - const promptValue = BaseChatModel2._convertInputToPromptValue(input); - return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].message; + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); } - async* _streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); } - async* _streamChatModelEvents(messages, options, runManager) { - yield* convertChunksToEvents(this._streamResponseChunks(messages, options, runManager), { signal: options.signal }); + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); } - streamV2(input, options) { - const messages = BaseChatModel2._convertInputToPromptValue(input).toChatMessages(); - const [, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - return new ChatModelStream(this._streamChatModelEvents(messages, callOptions)); + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); } - async* _streamIterator(input, options) { - if (this._streamResponseChunks === BaseChatModel2.prototype._streamResponseChunks || this.disableStreaming) - yield this.invoke(input, options); - else { - const messages = BaseChatModel2._convertInputToPromptValue(input).toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const inheritableMetadata = { - ...runnableConfig.metadata, - ...this.getLsParamsWithDefaults(callOptions) - }; - const invocationParams = this.invocationParams(callOptions); - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) - }); - const extra = { - options: callOptions, - invocation_params: invocationParams, - batch_size: 1 - }; - const outputVersion = callOptions.outputVersion ?? this.outputVersion; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); - let generationChunk; - let llmOutput; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - callOptions.signal?.throwIfAborted(); - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - if (outputVersion === "v1") - yield castStandardMessageContent(chunk.message); - else - yield chunk.message; - if (!generationChunk) - generationChunk = chunk; - else - generationChunk = generationChunk.concat(chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== undefined) - llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; - } - callOptions.signal?.throwIfAborted(); - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - generations: [[generationChunk]], - llmOutput - }))); } + return min; } - getLsParams(options) { - const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); - return { - ls_model_type: "chat", - ls_stop: options.stop, - ls_provider: providerName - }; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } - getLsParamsWithDefaults(options) { - return { - ...this.getLsParams(options), - ls_integration: "langchain_chat_model" - }; + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } - async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - let runManagers; - if (startedRunManagers !== undefined && startedRunManagers.length === baseMessages.length) - runManagers = startedRunManagers; - else { - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParamsWithDefaults(parsedOptions) - }; - const invocationParams = this.invocationParams(parsedOptions); - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) - }); - const extra = { - options: parsedOptions, - invocation_params: invocationParams, - batch_size: 1 - }; - runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - const llmOutputs = []; - const hasChatModelStreamEventHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersChatModelStreamEvents); - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - if (hasChatModelStreamEventHandler && !this.disableStreaming && baseMessages.length === 1 && (this._streamChatModelEvents !== BaseChatModel2.prototype._streamChatModelEvents || this._streamResponseChunks !== BaseChatModel2.prototype._streamResponseChunks)) + return Number.isFinite(min) && Number.isFinite(max); + } + }; + ZodNumber2.create = (params) => { + return new ZodNumber2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + }; + ZodBigInt2 = class ZodBigInt2 extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { try { - let sawEvent = false; - const runManager = runManagers?.[0]; - const events = this._streamChatModelEvents(baseMessages[0], parsedOptions); - const message = await new ChatModelStream({ async* [Symbol.asyncIterator]() { - for await (const event of events) { - parsedOptions.signal?.throwIfAborted(); - sawEvent = true; - const streamEvent = event.event === "message-start" && event.id == null && runManager?.runId != null ? { - ...event, - id: `run-${runManager.runId}` - } : event; - await runManager?.handleChatModelStreamEvent(streamEvent); - yield streamEvent; - } - } }); - parsedOptions.signal?.throwIfAborted(); - if (!sawEvent) - throw new Error("Received empty response from chat model call."); - if (message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - message._updateId(`run-${runId}`); - } - const generation = { - text: message.text, - message - }; - generations.push([generation]); - const llmOutput = message.usage_metadata !== undefined ? { tokenUsage: { - promptTokens: message.usage_metadata.input_tokens, - completionTokens: message.usage_metadata.output_tokens, - totalTokens: message.usage_metadata.total_tokens - } } : undefined; - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput - }); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); } - else if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel2.prototype._streamResponseChunks) - try { - const stream2 = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); - let aggregated; - let llmOutput; - for await (const chunk of stream2) { - if (parsedOptions.signal?.aborted) { - const partialMessage = aggregated?.message; - throw new ModelAbortError("Model invocation was aborted.", partialMessage); - } - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - if (aggregated === undefined) - aggregated = chunk; - else - aggregated = concat(aggregated, chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== undefined) - llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; + } + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + type: "bigint", + minimum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); } - if (parsedOptions.signal?.aborted) { - const partialMessage = aggregated?.message; - throw new ModelAbortError("Model invocation was aborted.", partialMessage); + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + type: "bigint", + maximum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); } - if (aggregated === undefined) - throw new Error("Received empty response from chat model call."); - generations.push([aggregated]); - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput - }); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { - const generateResults = await this._generate(messageList, { - ...parsedOptions, - promptIndex: i - }, runManagers?.[i]); - if (outputVersion === "v1") - for (const generation of generateResults.generations) - generation.message = castStandardMessageContent(generation.message); - return generateResults; - })); - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - for (const generation of result.generations) { - if (generation.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - generation.message._updateId(`run-${runId}`); - } - generation.message.response_metadata = { - ...generation.generationInfo, - ...generation.message.response_metadata - }; - } - if (result.generations.length === 1) - result.generations[0].message.response_metadata = { - ...result.llmOutput, - ...result.generations[0].message.response_metadata - }; - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput + } else if (check2.kind === "multipleOf") { + if (input.data % check2.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check2.value, + message: check2.message }); - } else { - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); + status.dirty(); } - })); + } else { + util.assertNever(check2); + } } - const output = { - generations, - llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : undefined - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, - configurable: true + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType }); - return output; + return INVALID; } - async _generateCached({ messages, cache: cache2, llmStringKey, parsedOptions, handledOptions }) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParamsWithDefaults(parsedOptions) - }; - const invocationParams = this.invocationParams(parsedOptions); - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt2({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] }); - const extra = { - options: parsedOptions, - invocation_params: invocationParams, - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); - const missingPromptIndices = []; - const cachedResults = (await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { - const prompt = BaseChatModel2._convertInputToPromptValue(baseMessage).toString(); - const result = await cache2.lookup(prompt, llmStringKey); - if (result == null) - missingPromptIndices.push(index); - return result; - }))).map((result, index) => ({ - result, - runManager: runManagers?.[index] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result2) => { - if ("message" in result2 && isBaseMessage(result2.message) && isAIMessage(result2.message)) { - result2.message.usage_metadata = { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0 - }; - if (outputVersion === "v1") - result2.message = castStandardMessageContent(result2.message); - } - result2.generationInfo = { - ...result2.generationInfo, - tokenUsage: {} - }; - return result2; - }); - if (result.length) - await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, undefined, undefined, undefined, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, - configurable: true + } + _addCheck(check2) { + return new ZodBigInt2({ + ...this._def, + checks: [...this._def.checks, check2] }); - return output; } - async generate(messages, options, callbacks) { - let parsedOptions; - if (Array.isArray(options)) - parsedOptions = { stop: options }; - else - parsedOptions = options; - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) - return this._generateUncached(baseMessages, callOptions, runnableConfig); - const { cache: cache2 } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - messages: baseMessages, - cache: cache2, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : undefined); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - const prompt = BaseChatModel2._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache2.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; } - invocationParams(_options) { - return {}; + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); } - _modelType() { - return "base_chat_model"; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); } - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); } - withStructuredOutput(outputSchema, config2) { - if (typeof this.bindTools !== "function") - throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); - if (config2?.strict) - throw new Error(`"strict" mode is not supported for this model by default.`); - const schema = outputSchema; - const name = config2?.name; - const description = getSchemaDescription(schema) ?? "A function available to call."; - const method = config2?.method; - const includeRaw = config2?.includeRaw; - if (method === "jsonMode") - throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); - let functionName = name ?? "extract"; - if (!isInteropZodSchema(schema) && !isSerializableSchema(schema) && "name" in schema) - functionName = schema.name; - const asJsonSchema = isInteropZodSchema(schema) || isSerializableSchema(schema) ? toJsonSchema(schema) : schema; - const tools = [{ - type: "function", - function: { - name: functionName, - description, - parameters: asJsonSchema + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - }]; - return assembleStructuredOutputPipeline(this.bindTools(tools), RunnableLambda.from((input) => { - if (!AIMessageChunk.isInstance(input)) - throw new Error("Input is not an AIMessageChunk."); - if (!input.tool_calls || input.tool_calls.length === 0) - throw new Error("No tool calls found in the response."); - const toolCall = input.tool_calls.find((tc) => tc.name === functionName); - if (!toolCall) - throw new Error(`No tool call found with name ${functionName}.`); - return toolCall.args; - }), includeRaw, includeRaw ? "StructuredOutputRunnable" : "StructuredOutput"); + } + return min; } - }; - SimpleChatModel = class extends BaseChatModel { - async _generate(messages, options, runManager) { - const message = new AIMessage(await this._call(messages, options, runManager)); - if (typeof message.content !== "string") - throw new Error("Cannot generate with a simple chat model when output is not a string."); - return { generations: [{ - text: message.content, - message - }] }; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } }; -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/chat_models/universal.js -async function getChatModelByClassName(className, modelProvider) { - let config2; - if (modelProvider) - config2 = MODEL_PROVIDER_CONFIG[modelProvider]; - else { - const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(([, c]) => c.className === className); - config2 = providerEntry ? providerEntry[1] : undefined; - } - if (!config2) - return; - try { - return (await import(config2.package))[config2.className]; - } catch (e) { - const err = e; - if ("code" in err && err.code?.toString().includes("ERR_MODULE_NOT_FOUND") && "message" in err && typeof err.message === "string") { - const attemptedPackage = (err.message.startsWith("Error: ") ? err.message.slice(7) : err.message).split("Cannot find package '")[1].split("'")[0]; - throw new Error(`Unable to import ${attemptedPackage}. Please install with \`npm install ${attemptedPackage}\` or \`pnpm install ${attemptedPackage}\``); + ZodBigInt2.create = (params) => { + return new ZodBigInt2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + }; + ZodBoolean2 = class ZodBoolean2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - throw e; - } -} -async function _initChatModelHelper(model, modelProvider, params = {}) { - const modelProviderCopy = modelProvider || _inferModelProvider(model); - if (!modelProviderCopy) - throw new Error(`Unable to infer model provider for { model: ${model} }, please specify modelProvider directly.`); - const config2 = MODEL_PROVIDER_CONFIG[modelProviderCopy]; - if (!config2) { - const supported = SUPPORTED_PROVIDERS.join(", "); - throw new Error(`Unsupported { modelProvider: ${modelProviderCopy} }. - -Supported model providers are: ${supported}`); - } - const { modelProvider: _unused, ...passedParams } = params; - return new (await getChatModelByClassName(config2.className, modelProviderCopy))({ - model, - ...passedParams - }); -} -function _inferModelProvider(modelName) { - if (modelName.startsWith("gpt-3") || modelName.startsWith("gpt-4") || modelName.startsWith("gpt-5") || modelName.startsWith("o1") || modelName.startsWith("o3") || modelName.startsWith("o4")) - return "openai"; - else if (modelName.startsWith("claude")) - return "anthropic"; - else if (modelName.startsWith("command")) - return "cohere"; - else if (modelName.startsWith("accounts/fireworks")) - return "fireworks"; - else if (modelName.startsWith("gemini")) - return "google-vertexai"; - else if (modelName.startsWith("amazon.")) - return "bedrock"; - else if (modelName.startsWith("mistral")) - return "mistralai"; - else if (modelName.startsWith("sonar") || modelName.startsWith("pplx")) - return "perplexity"; - else - return; -} -async function initChatModel(model, fields) { - let { configurableFields, configPrefix, modelProvider, profile, ...params } = { - configPrefix: "", - ...fields ?? {} }; - if (modelProvider === undefined && model?.includes(":")) { - const [provider, ...remainingParts] = model.split(":"); - const modelComponents = remainingParts.length === 0 ? [provider] : [provider, remainingParts.join(":")]; - if (SUPPORTED_PROVIDERS.includes(modelComponents[0])) - [modelProvider, model] = modelComponents; - } - let configurableFieldsCopy = Array.isArray(configurableFields) ? [...configurableFields] : configurableFields; - if (!model && configurableFieldsCopy === undefined) - configurableFieldsCopy = ["model", "modelProvider"]; - if (configPrefix && configurableFieldsCopy === undefined) - console.warn(`{ configPrefix: ${configPrefix} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`); - const paramsCopy = { ...params }; - let configurableModel; - if (configurableFieldsCopy === undefined) - configurableModel = new ConfigurableModel({ - defaultConfig: { - ...paramsCopy, - model, - modelProvider - }, - configPrefix, - profile - }); - else { - if (model) - paramsCopy.model = model; - if (modelProvider) - paramsCopy.modelProvider = modelProvider; - configurableModel = new ConfigurableModel({ - defaultConfig: paramsCopy, - configPrefix, - configurableFields: configurableFieldsCopy, - profile + ZodBoolean2.create = (params) => { + return new ZodBoolean2({ + typeName: ZodFirstPartyTypeKind2.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) }); - } - await configurableModel._getModelInstance(); - return configurableModel; -} -var MODEL_PROVIDER_CONFIG, SUPPORTED_PROVIDERS, ConfigurableModel; -var init_universal = __esm(() => { - init_runtime(); - init_chat_models(); - init_runnables(); - init_stream(); - MODEL_PROVIDER_CONFIG = { - openai: { - package: "@langchain/openai", - className: "ChatOpenAI" - }, - anthropic: { - package: "@langchain/anthropic", - className: "ChatAnthropic" - }, - azure_openai: { - package: "@langchain/openai", - className: "AzureChatOpenAI" - }, - cohere: { - package: "@langchain/cohere", - className: "ChatCohere" - }, - google: { - package: "@langchain/google", - className: "ChatGoogle" - }, - "google-vertexai": { - package: "@langchain/google-vertexai", - className: "ChatVertexAI" - }, - "google-vertexai-web": { - package: "@langchain/google-vertexai-web", - className: "ChatVertexAI" - }, - "google-genai": { - package: "@langchain/google-genai", - className: "ChatGoogleGenerativeAI" - }, - ollama: { - package: "@langchain/ollama", - className: "ChatOllama" - }, - mistralai: { - package: "@langchain/mistralai", - className: "ChatMistralAI" - }, - mistral: { - package: "@langchain/mistralai", - className: "ChatMistralAI" - }, - groq: { - package: "@langchain/groq", - className: "ChatGroq" - }, - bedrock: { - package: "@langchain/aws", - className: "ChatBedrockConverse" - }, - aws: { - package: "@langchain/aws", - className: "ChatBedrockConverse" - }, - deepseek: { - package: "@langchain/deepseek", - className: "ChatDeepSeek" - }, - xai: { - package: "@langchain/xai", - className: "ChatXAI" - }, - cerebras: { - package: "@langchain/cerebras", - className: "ChatCerebras" - }, - fireworks: { - package: "@langchain/fireworks", - className: "ChatFireworks" - }, - together: { - package: "@langchain/together-ai", - className: "ChatTogetherAI", - hasCircularDependency: true - }, - perplexity: { - package: "@langchain/perplexity", - className: "ChatPerplexity" - } }; - SUPPORTED_PROVIDERS = Object.keys(MODEL_PROVIDER_CONFIG); - ConfigurableModel = class ConfigurableModel2 extends BaseChatModel { - _llmType() { - return "chat_model"; - } - lc_namespace = ["langchain", "chat_models"]; - _defaultConfig = {}; - _configurableFields = "any"; - _configPrefix; - _queuedMethodOperations = {}; - _modelInstanceCache = /* @__PURE__ */ new Map; - _profile; - constructor(fields) { - super(fields); - this._defaultConfig = fields.defaultConfig ?? {}; - if (fields.configurableFields === "any") - this._configurableFields = "any"; - else - this._configurableFields = fields.configurableFields ?? ["model", "modelProvider"]; - if (fields.configPrefix) - this._configPrefix = fields.configPrefix.endsWith("_") ? fields.configPrefix : `${fields.configPrefix}_`; - else - this._configPrefix = ""; - this._queuedMethodOperations = fields.queuedMethodOperations ?? this._queuedMethodOperations; - this._profile = fields.profile ?? undefined; - this.metadata = { - ...this.metadata, - ls_integration: "langchain_init_chat_model" - }; - } - async _getModelInstance(config2) { - const cacheKey2 = this._getCacheKey(config2); - const cachedModel = this._modelInstanceCache.get(cacheKey2); - if (cachedModel) - return cachedModel; - const params = { - ...this._defaultConfig, - ...this._modelParams(config2) + ZodDate2 = class ZodDate2 extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_date + }); + return INVALID; + } + const status = new ParseStatus; + let ctx = undefined; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.getTime() < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + message: check2.message, + inclusive: true, + exact: false, + minimum: check2.value, + type: "date" + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.getTime() > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + message: check2.message, + inclusive: true, + exact: false, + maximum: check2.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) }; - let initializedModel = await _initChatModelHelper(params.model, params.modelProvider, params); - for (const [method, args] of Object.entries(this._queuedMethodOperations)) - if (method in initializedModel && typeof initializedModel[method] === "function") - initializedModel = await initializedModel[method](...args); - this._modelInstanceCache.set(cacheKey2, initializedModel); - return initializedModel; } - async _generate(messages, options, runManager) { - return (await this._getModelInstance(options))._generate(messages, options ?? {}, runManager); + _addCheck(check2) { + return new ZodDate2({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - bindTools(tools, params) { - const newQueuedOperations = { ...this._queuedMethodOperations }; - newQueuedOperations.bindTools = [tools, params]; - return new ConfigurableModel2({ - defaultConfig: this._defaultConfig, - configurableFields: this._configurableFields, - configPrefix: this._configPrefix, - queuedMethodOperations: newQueuedOperations + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) }); } - withStructuredOutput = (schema, ...args) => { - const newQueuedOperations = { ...this._queuedMethodOperations }; - newQueuedOperations.withStructuredOutput = [schema, ...args]; - return new ConfigurableModel2({ - defaultConfig: this._defaultConfig, - configurableFields: this._configurableFields, - configPrefix: this._configPrefix, - queuedMethodOperations: newQueuedOperations + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) }); - }; - _modelParams(config2) { - const configurable = config2?.configurable ?? {}; - let modelParams = {}; - for (const [key, value] of Object.entries(configurable)) - if (key.startsWith(this._configPrefix)) { - const strippedKey = this._removePrefix(key, this._configPrefix); - modelParams[strippedKey] = value; + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - if (this._configurableFields !== "any") - modelParams = Object.fromEntries(Object.entries(modelParams).filter(([key]) => this._configurableFields.includes(key))); - return modelParams; + } + return min != null ? new Date(min) : null; } - _removePrefix(str, prefix) { - return str.startsWith(prefix) ? str.slice(prefix.length) : str; + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; } - withConfig(config2) { - const mergedConfig = { ...config2 || {} }; - const modelParams = this._modelParams(mergedConfig); - const remainingConfig = Object.fromEntries(Object.entries(mergedConfig).filter(([k]) => k !== "configurable")); - remainingConfig.configurable = Object.fromEntries(Object.entries(mergedConfig.configurable || {}).filter(([k]) => this._configPrefix && !Object.keys(modelParams).includes(this._removePrefix(k, this._configPrefix)))); - return new RunnableBinding({ - config: mergedConfig, - bound: new ConfigurableModel2({ - defaultConfig: { - ...this._defaultConfig, - ...modelParams - }, - configurableFields: Array.isArray(this._configurableFields) ? [...this._configurableFields] : this._configurableFields, - configPrefix: this._configPrefix, - queuedMethodOperations: this._queuedMethodOperations - }) - }); + }; + ZodDate2.create = (params) => { + return new ZodDate2({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind2.ZodDate, + ...processCreateParams(params) + }); + }; + ZodSymbol2 = class ZodSymbol2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - async invoke(input, options) { - const model = await this._getModelInstance(options); - const config2 = ensureConfig(options); - return model.invoke(input, config2); + }; + ZodSymbol2.create = (params) => { + return new ZodSymbol2({ + typeName: ZodFirstPartyTypeKind2.ZodSymbol, + ...processCreateParams(params) + }); + }; + ZodUndefined2 = class ZodUndefined2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - async stream(input, options) { - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: await (await this._getModelInstance(options)).stream(input, options), - config: options - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + }; + ZodUndefined2.create = (params) => { + return new ZodUndefined2({ + typeName: ZodFirstPartyTypeKind2.ZodUndefined, + ...processCreateParams(params) + }); + }; + ZodNull2 = class ZodNull2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - async batch(inputs, options, batchOptions) { - return super.batch(inputs, options, batchOptions); + }; + ZodNull2.create = (params) => { + return new ZodNull2({ + typeName: ZodFirstPartyTypeKind2.ZodNull, + ...processCreateParams(params) + }); + }; + ZodAny2 = class ZodAny2 extends ZodType2 { + constructor() { + super(...arguments); + this._any = true; } - async* transform(generator, options) { - const model = await this._getModelInstance(options); - const config2 = ensureConfig(options); - yield* model.transform(generator, config2); + _parse(input) { + return OK(input.data); } - async* streamLog(input, options, streamOptions) { - const model = await this._getModelInstance(options); - const config2 = ensureConfig(options); - yield* model.streamLog(input, config2, { - ...streamOptions, - _schemaFormat: "original", - includeNames: streamOptions?.includeNames, - includeTypes: streamOptions?.includeTypes, - includeTags: streamOptions?.includeTags, - excludeNames: streamOptions?.excludeNames, - excludeTypes: streamOptions?.excludeTypes, - excludeTags: streamOptions?.excludeTags - }); + }; + ZodAny2.create = (params) => { + return new ZodAny2({ + typeName: ZodFirstPartyTypeKind2.ZodAny, + ...processCreateParams(params) + }); + }; + ZodUnknown2 = class ZodUnknown2 extends ZodType2 { + constructor() { + super(...arguments); + this._unknown = true; } - streamEvents(input, options, streamOptions) { - const outerThis = this; - async function* wrappedGenerator() { - const model = await outerThis._getModelInstance(options); - const config2 = ensureConfig(options); - const eventStream = model.streamEvents(input, config2, streamOptions); - for await (const chunk of eventStream) - yield chunk; - } - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator()); + _parse(input) { + return OK(input.data); } - get profile() { - if (this._profile) - return this._profile; - const cacheKey2 = this._getCacheKey({}); - return this._modelInstanceCache.get(cacheKey2)?.profile ?? {}; + }; + ZodUnknown2.create = (params) => { + return new ZodUnknown2({ + typeName: ZodFirstPartyTypeKind2.ZodUnknown, + ...processCreateParams(params) + }); + }; + ZodNever2 = class ZodNever2 extends ZodType2 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; } - _getCacheKey(config2) { - let toStringify = config2 ?? {}; - if (toStringify.configurable) { - const { configurable } = toStringify; - const filtered = {}; - for (const [k, v] of Object.entries(configurable)) - if (!k.startsWith("__pregel_")) - filtered[k] = v; - toStringify = { - ...toStringify, - configurable: filtered - }; + }; + ZodNever2.create = (params) => { + return new ZodNever2({ + typeName: ZodFirstPartyTypeKind2.ZodNever, + ...processCreateParams(params) + }); + }; + ZodVoid2 = class ZodVoid2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; } - return JSON.stringify(toStringify); + return OK(input.data); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tools/types.js -function isStructuredTool(tool) { - return tool !== undefined && Array.isArray(tool.lc_namespace); -} -function isRunnableToolLike(tool) { - return tool !== undefined && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; -} -function isStructuredToolParams(tool) { - return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && ("type" in tool.schema) && typeof tool.schema.type === "string" && [ - "null", - "boolean", - "object", - "array", - "number", - "string" - ].includes(tool.schema.type)); -} -function isLangChainTool(tool) { - return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); -} -var init_types4 = __esm(() => { - init_zod2(); - init_base4(); -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js -var init_classic = __esm(() => { - init_external(); - init_external(); -}); - -// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js -var init_v43 = __esm(() => { - init_classic(); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tools/index.js -function tool(func, fields) { - const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); - const isStringJSONSchema = validatesOnlyStrings(fields.schema); - if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) - return new DynamicTool({ - ...fields, - description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, - func: async (input, runManager, config2) => { - return new Promise((resolve2, reject) => { - const childConfig = patchConfig(config2, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - resolve2(func(input, childConfig)); - } catch (e) { - reject(e); - } - }); + ZodVoid2.create = (params) => { + return new ZodVoid2({ + typeName: ZodFirstPartyTypeKind2.ZodVoid, + ...processCreateParams(params) + }); + }; + ZodArray2 = class ZodArray2 extends ZodType2 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType }); + return INVALID; } - }); - const schema = fields.schema; - const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; - return new DynamicStructuredTool({ - ...fields, - description, - schema, - func: async (input, runManager, config2) => { - return new Promise((resolve2, reject) => { - let listener; - const cleanup = () => { - if (config2?.signal && listener) - config2.signal.removeEventListener("abort", listener); - }; - if (config2?.signal) { - listener = () => { - cleanup(); - reject(getAbortSignalError(config2.signal)); - }; - config2.signal.addEventListener("abort", listener, { once: true }); + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, + minimum: tooSmall ? def.exactLength.value : undefined, + maximum: tooBig ? def.exactLength.value : undefined, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); } - const childConfig = patchConfig(config2, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - const result = await func(input, childConfig); - if (isAsyncGenerator(result)) { - resolve2(result); - return; - } - if (config2?.signal?.aborted) { - cleanup(); - return; - } - cleanup(); - resolve2(result); - } catch (e) { - cleanup(); - reject(e); - } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); + return ParseStatus.mergeArray(status, result); } - }); -} -function _formatToolOutput(params) { - const { content, artifact, toolCallId, metadata } = params; - if (toolCallId && !isDirectToolOutput(content)) - if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) - return new ToolMessage({ - status: "success", - content, - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray2({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } }); - else - return new ToolMessage({ - status: "success", - content: _stringify(content), - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata + } + max(maxLength, message) { + return new ZodArray2({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } }); - else - return content; -} -function _stringify(content) { - try { - return JSON.stringify(content) ?? ""; - } catch (_noOp) { - return `${content}`; - } -} -var tools_exports, StructuredTool, Tool, DynamicTool, DynamicStructuredTool, BaseToolkit = class { - getTools() { - return this.tools; - } -}; -var init_tools2 = __esm(() => { - init_runtime2(); - init_utils2(); - init_tool(); - init_manager(); - init_async_local_storage(); - init_singletons(); - init_config(); - init_signal(); - init_zod2(); - init_json_schema2(); - init_iter(); - init_base5(); - init_types4(); - init_v3(); - init_esm(); - init_v43(); - tools_exports = /* @__PURE__ */ __exportAll({ - BaseToolkit: () => BaseToolkit, - DynamicStructuredTool: () => DynamicStructuredTool, - DynamicTool: () => DynamicTool, - StructuredTool: () => StructuredTool, - Tool: () => Tool, - ToolInputParsingException: () => ToolInputParsingException, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams, - tool: () => tool - }); - StructuredTool = class extends BaseLangChain { - extras; - returnDirect = false; - verboseParsingErrors = false; - get lc_namespace() { - return ["langchain", "tools"]; } - responseFormat = "content"; - defaultConfig; - constructor(fields) { - super(fields ?? {}); - this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; - this.responseFormat = fields?.responseFormat ?? this.responseFormat; - this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; - this.metadata = fields?.metadata ?? this.metadata; - this.extras = fields?.extras ?? this.extras; + length(len, message) { + return new ZodArray2({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); } - async invoke(input, config2) { - let toolInput; - let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config2)); - if (_isToolCall(input)) { - toolInput = input.args; - enrichedConfig = { - ...enrichedConfig, - toolCall: input - }; - } else - toolInput = input; - return this.call(toolInput, enrichedConfig); + nonempty(message) { + return this.min(1, message); } - async call(arg, configArg, tags) { - const inputForValidation = _isToolCall(arg) ? arg.args : arg; - let parsed; - if (isInteropZodSchema(this.schema)) - try { - parsed = await interopParseAsync(this.schema, inputForValidation); - } catch (e) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) - message = `${message} -Details: ${e.message}`; - if (isInteropZodError(e)) - message = `${message} - -${exports_external.prettifyError(e)}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); + }; + ZodArray2.create = (schema, params) => { + return new ZodArray2({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind2.ZodArray, + ...processCreateParams(params) + }); + }; + ZodObject2 = class ZodObject2 extends ZodType2 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } } - else { - const result2 = validate4(inputForValidation, this.schema); - if (!result2.valid) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) - message = `${message} -Details: ${result2.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join(` -`)}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever2) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode2.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") {} else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); } - parsed = inputForValidation; } - const config2 = parseCallbackConfigArg(configArg); - const callbackManager_ = CallbackManager.configure(config2.callbacks, this.callbacks, config2.tags || tags, this.tags, config2.metadata, this.metadata, { verbose: this.verbose }); - let toolCallId; - if (_isToolCall(arg)) - toolCallId = arg.id; - if (!toolCallId && _configHasToolCallId(config2)) - toolCallId = config2.toolCall.id; - const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config2.runId, undefined, undefined, undefined, config2.runName, toolCallId); - delete config2.runId; - let result; - try { - const raw2 = await this._call(parsed, runManager, config2); - result = isAsyncGenerator(raw2) ? await consumeAsyncGenerator(raw2, async (chunk) => { - try { - await runManager?.handleToolEvent(chunk); - } catch (streamError) { - await runManager?.handleToolError(streamError); + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); } - }) : raw2; - } catch (e) { - await runManager?.handleToolError(e); - throw e; + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); } - let content; - let artifact; - if (this.responseFormat === "content_and_artifact") - if (Array.isArray(result) && result.length === 2) - [content, artifact] = result; - else - throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple. -Result: ${JSON.stringify(result)}`); - else - content = result; - const formattedOutput = _formatToolOutput({ - content, - artifact, - toolCallId, - name: this.name, - metadata: this.metadata - }); - await runManager?.handleToolEnd(formattedOutput); - return formattedOutput; - } - }; - Tool = class extends StructuredTool { - schema = exports_external2.object({ input: exports_external2.string().optional() }).transform((obj) => obj.input); - constructor(fields) { - super(fields); - } - call(arg, callbacks) { - const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; - return super.call(structuredArg, callbacks); - } - }; - DynamicTool = class extends Tool { - static lc_name() { - return "DynamicTool"; - } - name; - description; - func; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - } - async call(arg, configArg) { - const config2 = parseCallbackConfigArg(configArg); - if (config2.runName === undefined) - config2.runName = this.name; - return super.call(arg, config2); } - _call(input, runManager, parentConfig) { - return this.func(input, runManager, parentConfig); + get shape() { + return this._def.shape(); } - }; - DynamicStructuredTool = class extends StructuredTool { - static lc_name() { - return "DynamicStructuredTool"; + strict(message) { + errorUtil.errToObj; + return new ZodObject2({ + ...this._def, + unknownKeys: "strict", + ...message !== undefined ? { + errorMap: (issue3, ctx) => { + const defaultError = this._def.errorMap?.(issue3, ctx).message ?? ctx.defaultError; + if (issue3.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); } - description; - func; - schema; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - this.schema = fields.schema; + strip() { + return new ZodObject2({ + ...this._def, + unknownKeys: "strip" + }); } - async call(arg, configArg, tags) { - const config2 = parseCallbackConfigArg(configArg); - if (config2.runName === undefined) - config2.runName = this.name; - return super.call(arg, config2, tags); + passthrough() { + return new ZodObject2({ + ...this._def, + unknownKeys: "passthrough" + }); } - _call(arg, runManager, parentConfig) { - return this.func(arg, runManager, parentConfig); + extend(augmentation) { + return new ZodObject2({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/setup/async_local_storage.js -import { AsyncLocalStorage } from "node:async_hooks"; -function initializeAsyncLocalStorageSingleton() { - AsyncLocalStorageProviderSingleton2.initializeGlobalInstance(new AsyncLocalStorage); -} -var init_async_local_storage2 = __esm(() => { - init_singletons(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/constants.js -function _isSendInterface(x) { - const operation = x; - return operation !== null && operation !== undefined && typeof operation.node === "string" && operation.args !== undefined; -} -function _isSend(x) { - return x instanceof Send; -} -function _getOverwriteValue(value) { - if (typeof value === "object" && value !== null && "__overwrite__" in value) - return [true, value[OVERWRITE]]; - return [false, undefined]; -} -function _isOverwriteValue(value) { - return _getOverwriteValue(value)[0]; -} -function isInterrupted(values) { - if (!values || typeof values !== "object") - return false; - if (!("__interrupt__" in values)) - return false; - return Array.isArray(values[INTERRUPT]); -} -function isCommand(x) { - if (typeof x !== "object") - return false; - if (x === null || x === undefined) - return false; - if ("lg_name" in x && x.lg_name === "Command") - return true; - return false; -} -function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map) { - if (x !== undefined && x !== null && typeof x === "object") { - if (seen.has(x)) - return seen.get(x); - let result; - if (Array.isArray(x)) { - result = []; - seen.set(x, result); - x.forEach((item, index) => { - result[index] = _deserializeCommandSendObjectGraph(item, seen); + merge(merging) { + const merged = new ZodObject2({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind2.ZodObject }); - } else if (isCommand(x) && !(x instanceof Command)) { - result = new Command(x); - seen.set(x, result); - } else if (_isSendInterface(x) && !(x instanceof Send)) { - result = new Send(x.node, x.args); - seen.set(x, result); - } else if (isCommand(x) || _isSend(x)) { - result = x; - seen.set(x, result); - } else if ("lc_serializable" in x && x.lc_serializable) { - result = x; - seen.set(x, result); - } else { - result = {}; - seen.set(x, result); - for (const [key, value] of Object.entries(x)) - result[key] = _deserializeCommandSendObjectGraph(value, seen); + return merged; } - return result; - } - return x; -} -var START = "__start__", END = "__end__", INPUT = "__input__", ERROR2 = "__error__", CACHE_NS_WRITES = "__pregel_ns_writes", CONFIG_KEY_SEND = "__pregel_send", CONFIG_KEY_CALL = "__pregel_call", CONFIG_KEY_READ = "__pregel_read", CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer", CONFIG_KEY_RESUMING = "__pregel_resuming", CONFIG_KEY_TASK_ID = "__pregel_task_id", CONFIG_KEY_STREAM = "__pregel_stream", CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value", CONFIG_KEY_RESUME_MAP = "__pregel_resume_map", CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad", CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous", CONFIG_KEY_DURABILITY = "__pregel_durability", CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id", CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns", CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished", CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map", CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals", INTERRUPT = "__interrupt__", RESUME = "__resume__", NO_WRITES = "__no_writes__", RETURN = "__return__", PREVIOUS = "__previous__", TAG_HIDDEN = "langsmith:hidden", SELF = "__self__", TASKS = "__pregel_tasks", PUSH = "__pregel_push", PULL = "__pregel_pull", NULL_TASK_ID = "00000000-0000-0000-0000-000000000000", RESERVED, COMMAND_SYMBOL, CommandInstance, Send = class { - lg_name = "Send"; - node; - args; - constructor(node, args) { - this.node = node; - this.args = _deserializeCommandSendObjectGraph(args); - } - toJSON() { - return { - lg_name: this.lg_name, - node: this.node, - args: this.args - }; - } -}, OVERWRITE = "__overwrite__", Overwrite, Command; -var init_constants3 = __esm(() => { - RESERVED = [ - TAG_HIDDEN, - INPUT, - INTERRUPT, - RESUME, - ERROR2, - NO_WRITES, - CONFIG_KEY_SEND, - CONFIG_KEY_READ, - CONFIG_KEY_CHECKPOINTER, - CONFIG_KEY_DURABILITY, - CONFIG_KEY_STREAM, - CONFIG_KEY_RESUMING, - CONFIG_KEY_TASK_ID, - CONFIG_KEY_CALL, - CONFIG_KEY_RESUME_VALUE, - CONFIG_KEY_SCRATCHPAD, - CONFIG_KEY_PREVIOUS_STATE, - CONFIG_KEY_CHECKPOINT_MAP, - CONFIG_KEY_CHECKPOINT_NS, - CONFIG_KEY_CHECKPOINT_ID - ]; - COMMAND_SYMBOL = Symbol.for("langgraph.command"); - CommandInstance = class { - [COMMAND_SYMBOL]; - constructor(args) { - this[COMMAND_SYMBOL] = args; + setKey(key, schema) { + return this.augment({ [key]: schema }); } - }; - Overwrite = class { - lg_name = "Overwrite"; - [OVERWRITE]; - constructor(value) { - this[OVERWRITE] = value; + catchall(index) { + return new ZodObject2({ + ...this._def, + catchall: index + }); } - get value() { - return this[OVERWRITE]; + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject2({ + ...this._def, + shape: () => shape + }); } - toJSON() { - return { [OVERWRITE]: this[OVERWRITE] }; + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject2({ + ...this._def, + shape: () => shape + }); } - static isInstance(value) { - if (!value || typeof value !== "object") - return false; - if ("__overwrite__" in value) - return true; - if ("lg_name" in value && value.lg_name === "Overwrite") - return true; - return false; + deepPartial() { + return deepPartialify(this); } - }; - Command = class extends CommandInstance { - lg_name = "Command"; - lc_direct_tool_output = true; - graph; - update; - resume; - goto = []; - static PARENT = "__parent__"; - constructor(args) { - super(args); - this.resume = args.resume; - this.graph = args.graph; - this.update = args.update; - if (args.goto) - this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject2({ + ...this._def, + shape: () => newShape + }); } - _updateAsTuples() { - if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) - return Object.entries(this.update); - else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) - return this.update; - else - return [["__root__", this.update]]; + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional2) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject2({ + ...this._def, + shape: () => newShape + }); } - toJSON() { - let serializedGoto; - if (typeof this.goto === "string") - serializedGoto = this.goto; - else if (_isSend(this.goto)) - serializedGoto = this.goto.toJSON(); - else - serializedGoto = this.goto?.map((innerGoto) => { - if (typeof innerGoto === "string") - return innerGoto; - else - return innerGoto.toJSON(); - }); - return { - lg_name: this.lg_name, - update: this.update, - resume: this.resume, - goto: serializedGoto - }; + keyof() { + return createZodEnum(util.objectKeys(this.shape)); } }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/errors.js -function isParentCommand(e) { - return e !== undefined && e.name === ParentCommand.unminifiable_name; -} -function isGraphBubbleUp(e) { - return e !== undefined && e.is_bubble_up === true; -} -function isGraphInterrupt(e) { - return e !== undefined && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); -} -var BaseLangGraphError, GraphBubbleUp, GraphRecursionError, GraphValueError, GraphInterrupt, NodeInterrupt, ParentCommand, EmptyInputError, EmptyChannelError, InvalidUpdateError, MultipleSubgraphsError, UnreachableNodeError, RemoteException, StateGraphInputError, getSubgraphsSeenSet = () => { - if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === undefined) - globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set; - return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; -}; -var init_errors5 = __esm(() => { - BaseLangGraphError = class extends Error { - lc_error_code; - constructor(message, fields) { - let finalMessage = message ?? ""; - if (fields?.lc_error_code) - finalMessage = `${finalMessage} - -Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/ -`; - super(finalMessage); - this.lc_error_code = fields?.lc_error_code; - } + ZodObject2.create = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); }; - GraphBubbleUp = class extends BaseLangGraphError { - get is_bubble_up() { - return true; - } + ZodObject2.strictCreate = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); }; - GraphRecursionError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphRecursionError"; - } - static get unminifiable_name() { - return "GraphRecursionError"; - } + ZodObject2.lazycreate = (shape, params) => { + return new ZodObject2({ + shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams(params) + }); }; - GraphValueError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphValueError"; + ZodUnion2 = class ZodUnion2 extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError2(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID; + } } - static get unminifiable_name() { - return "GraphValueError"; + get options() { + return this._def.options; } }; - GraphInterrupt = class extends GraphBubbleUp { - interrupts; - constructor(interrupts, fields) { - super(JSON.stringify(interrupts, null, 2), fields); - this.name = "GraphInterrupt"; - this.interrupts = interrupts ?? []; - } - static get unminifiable_name() { - return "GraphInterrupt"; - } + ZodUnion2.create = (types, params) => { + return new ZodUnion2({ + options: types, + typeName: ZodFirstPartyTypeKind2.ZodUnion, + ...processCreateParams(params) + }); }; - NodeInterrupt = class extends GraphInterrupt { - constructor(message, fields) { - super([{ value: message }], fields); - this.name = "NodeInterrupt"; - } - static get unminifiable_name() { - return "NodeInterrupt"; + ZodDiscriminatedUnion2 = class ZodDiscriminatedUnion2 extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } } - }; - ParentCommand = class extends GraphBubbleUp { - command; - constructor(command) { - super(); - this.name = "ParentCommand"; - this.command = command; + get discriminator() { + return this._def.discriminator; } - static get unminifiable_name() { - return "ParentCommand"; + get options() { + return this._def.options; } - }; - EmptyInputError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyInputError"; + get optionsMap() { + return this._def.optionsMap; } - static get unminifiable_name() { - return "EmptyInputError"; + static create(discriminator, options, params) { + const optionsMap = new Map; + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion2({ + typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); } }; - EmptyChannelError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyChannelError"; - } - static get unminifiable_name() { - return "EmptyChannelError"; + ZodIntersection2 = class ZodIntersection2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues3(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } } }; - InvalidUpdateError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "InvalidUpdateError"; - } - static get unminifiable_name() { - return "InvalidUpdateError"; - } + ZodIntersection2.create = (left, right, params) => { + return new ZodIntersection2({ + left, + right, + typeName: ZodFirstPartyTypeKind2.ZodIntersection, + ...processCreateParams(params) + }); }; - MultipleSubgraphsError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "MultipleSubgraphError"; - } - static get unminifiable_name() { - return "MultipleSubgraphError"; + ZodTuple2 = class ZodTuple2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } } - }; - UnreachableNodeError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "UnreachableNodeError"; + get items() { + return this._def.items; } - static get unminifiable_name() { - return "UnreachableNodeError"; + rest(rest) { + return new ZodTuple2({ + ...this._def, + rest + }); } }; - RemoteException = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "RemoteException"; - } - static get unminifiable_name() { - return "RemoteException"; + ZodTuple2.create = (schemas4, params) => { + if (!Array.isArray(schemas4)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } + return new ZodTuple2({ + items: schemas4, + typeName: ZodFirstPartyTypeKind2.ZodTuple, + rest: null, + ...processCreateParams(params) + }); }; - StateGraphInputError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "StateGraphInputError"; - this.message = "Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."; + ZodRecord2 = class ZodRecord2 extends ZodType2 { + get keySchema() { + return this._def.keyType; } - static get unminifiable_name() { - return "StateGraphInputError"; + get valueSchema() { + return this._def.valueType; } - }; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/max.js -var require_max = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _default3 = exports.default = "ffffffff-ffff-ffff-ffff-ffffffffffff"; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/nil.js -var require_nil = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _default3 = exports.default = "00000000-0000-0000-0000-000000000000"; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/regex.js -var require_regex = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _default3 = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/validate.js -var require_validate = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _regex2 = _interopRequireDefault(require_regex()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function validate7(uuid3) { - return typeof uuid3 === "string" && _regex2.default.test(uuid3); - } - var _default3 = exports.default = validate7; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/parse.js -var require_parse = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function parse8(uuid3) { - if (!(0, _validate.default)(uuid3)) { - throw TypeError("Invalid UUID"); + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } } - let v; - const arr2 = new Uint8Array(16); - arr2[0] = (v = parseInt(uuid3.slice(0, 8), 16)) >>> 24; - arr2[1] = v >>> 16 & 255; - arr2[2] = v >>> 8 & 255; - arr2[3] = v & 255; - arr2[4] = (v = parseInt(uuid3.slice(9, 13), 16)) >>> 8; - arr2[5] = v & 255; - arr2[6] = (v = parseInt(uuid3.slice(14, 18), 16)) >>> 8; - arr2[7] = v & 255; - arr2[8] = (v = parseInt(uuid3.slice(19, 23), 16)) >>> 8; - arr2[9] = v & 255; - arr2[10] = (v = parseInt(uuid3.slice(24, 36), 16)) / 1099511627776 & 255; - arr2[11] = v / 4294967296 & 255; - arr2[12] = v >>> 24 & 255; - arr2[13] = v >>> 16 & 255; - arr2[14] = v >>> 8 & 255; - arr2[15] = v & 255; - return arr2; - } - var _default3 = exports.default = parse8; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/stringify.js -var require_stringify = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - exports.unsafeStringify = unsafeStringify4; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var byteToHex4 = []; - for (let i = 0;i < 256; ++i) { - byteToHex4.push((i + 256).toString(16).slice(1)); - } - function unsafeStringify4(arr2, offset = 0) { - return (byteToHex4[arr2[offset + 0]] + byteToHex4[arr2[offset + 1]] + byteToHex4[arr2[offset + 2]] + byteToHex4[arr2[offset + 3]] + "-" + byteToHex4[arr2[offset + 4]] + byteToHex4[arr2[offset + 5]] + "-" + byteToHex4[arr2[offset + 6]] + byteToHex4[arr2[offset + 7]] + "-" + byteToHex4[arr2[offset + 8]] + byteToHex4[arr2[offset + 9]] + "-" + byteToHex4[arr2[offset + 10]] + byteToHex4[arr2[offset + 11]] + byteToHex4[arr2[offset + 12]] + byteToHex4[arr2[offset + 13]] + byteToHex4[arr2[offset + 14]] + byteToHex4[arr2[offset + 15]]).toLowerCase(); - } - function stringify2(arr2, offset = 0) { - const uuid3 = unsafeStringify4(arr2, offset); - if (!(0, _validate.default)(uuid3)) { - throw TypeError("Stringified UUID is invalid"); + get element() { + return this._def.valueType; } - return uuid3; - } - var _default3 = exports.default = stringify2; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/rng.js -var require_rng = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = rng3; - var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var rnds8Pool = new Uint8Array(256); - var poolPtr = rnds8Pool.length; - function rng3() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; + static create(first, second, third) { + if (second instanceof ZodType2) { + return new ZodRecord2({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams(third) + }); + } + return new ZodRecord2({ + keyType: ZodString2.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams(second) + }); } - return rnds8Pool.slice(poolPtr, poolPtr += 16); - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v1.js -var require_v1 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _rng = _interopRequireDefault(require_rng()); - var _stringify2 = require_stringify(); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var _nodeId; - var _clockseq; - var _lastMSecs = 0; - var _lastNSecs = 0; - function v12(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - if (!options._v6) { - if (!node) { - node = _nodeId; + }; + ZodMap2 = class ZodMap2 extends ZodType2 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; } - if (clockseq == null) { - clockseq = _clockseq; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = new Map; + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = new Map; + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; } } - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - if (!_nodeId && !options._v6) { - node[0] |= 1; - _nodeId = node; + }; + ZodMap2.create = (keyType, valueType, params) => { + return new ZodMap2({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind2.ZodMap, + ...processCreateParams(params) + }); + }; + ZodSet2 = class ZodSet2 extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); } } - if (clockseq == null) { - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = new Set; + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); } } - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 16383; + min(minSize, message) { + return new ZodSet2({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); } - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; + max(maxSize, message) { + return new ZodSet2({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); } - if (nsecs >= 1e4) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + size(size, message) { + return this.min(size, message).max(size, message); } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - msecs += 12219292800000; - const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; - b[i++] = tl >>> 24 & 255; - b[i++] = tl >>> 16 & 255; - b[i++] = tl >>> 8 & 255; - b[i++] = tl & 255; - const tmh = msecs / 4294967296 * 1e4 & 268435455; - b[i++] = tmh >>> 8 & 255; - b[i++] = tmh & 255; - b[i++] = tmh >>> 24 & 15 | 16; - b[i++] = tmh >>> 16 & 255; - b[i++] = clockseq >>> 8 | 128; - b[i++] = clockseq & 255; - for (let n2 = 0;n2 < 6; ++n2) { - b[i + n2] = node[n2]; + nonempty(message) { + return this.min(1, message); } - return buf || (0, _stringify2.unsafeStringify)(b); - } - var _default3 = exports.default = v12; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v1ToV6.js -var require_v1ToV6 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = v1ToV6; - var _parse2 = _interopRequireDefault(require_parse()); - var _stringify2 = require_stringify(); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function v1ToV6(uuid3) { - const v1Bytes2 = typeof uuid3 === "string" ? (0, _parse2.default)(uuid3) : uuid3; - const v6Bytes = _v1ToV6(v1Bytes2); - return typeof uuid3 === "string" ? (0, _stringify2.unsafeStringify)(v6Bytes) : v6Bytes; - } - function _v1ToV6(v1Bytes2, randomize = false) { - return Uint8Array.of((v1Bytes2[6] & 15) << 4 | v1Bytes2[7] >> 4 & 15, (v1Bytes2[7] & 15) << 4 | (v1Bytes2[4] & 240) >> 4, (v1Bytes2[4] & 15) << 4 | (v1Bytes2[5] & 240) >> 4, (v1Bytes2[5] & 15) << 4 | (v1Bytes2[0] & 240) >> 4, (v1Bytes2[0] & 15) << 4 | (v1Bytes2[1] & 240) >> 4, (v1Bytes2[1] & 15) << 4 | (v1Bytes2[2] & 240) >> 4, 96 | v1Bytes2[2] & 15, v1Bytes2[3], v1Bytes2[8], v1Bytes2[9], v1Bytes2[10], v1Bytes2[11], v1Bytes2[12], v1Bytes2[13], v1Bytes2[14], v1Bytes2[15]); - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v35.js -var require_v35 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.URL = exports.DNS = undefined; - exports.default = v354; - var _stringify2 = require_stringify(); - var _parse2 = _interopRequireDefault(require_parse()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function stringToBytes4(str) { - str = unescape(encodeURIComponent(str)); - const bytes = []; - for (let i = 0;i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); + }; + ZodSet2.create = (valueType, params) => { + return new ZodSet2({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind2.ZodSet, + ...processCreateParams(params) + }); + }; + ZodFunction2 = class ZodFunction2 extends ZodType2 { + constructor() { + super(...arguments); + this.validate = this.implement; } - return bytes; - } - var DNS4 = exports.DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - var URL5 = exports.URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - function v354(name, version3, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === "string") { - value = stringToBytes4(value); + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; } - if (typeof namespace === "string") { - namespace = (0, _parse2.default)(namespace); + function makeArgsIssue(args, error90) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default3].filter((x) => !!x), + issueData: { + code: ZodIssueCode2.invalid_arguments, + argumentsError: error90 + } + }); } - if (((_namespace = namespace) === null || _namespace === undefined ? undefined : _namespace.length) !== 16) { - throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + function makeReturnsIssue(returns, error90) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default3].filter((x) => !!x), + issueData: { + code: ZodIssueCode2.invalid_return_type, + returnTypeError: error90 + } + }); } - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 15 | version3; - bytes[8] = bytes[8] & 63 | 128; - if (buf) { - offset = offset || 0; - for (let i = 0;i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise2) { + const me = this; + return OK(async function(...args) { + const error90 = new ZodError2([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error90.addIssue(makeArgsIssue(args, e)); + throw error90; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error90.addIssue(makeReturnsIssue(result, e)); + throw error90; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); } - return (0, _stringify2.unsafeStringify)(bytes); } - try { - generateUUID.name = name; - } catch (err) {} - generateUUID.DNS = DNS4; - generateUUID.URL = URL5; - return generateUUID; - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/md5.js -var require_md5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === "string") { - bytes = Buffer.from(bytes, "utf8"); + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction2({ + ...this._def, + args: ZodTuple2.create(items).rest(ZodUnknown2.create()) + }); + } + returns(returnType) { + return new ZodFunction2({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction2({ + args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), + returns: returns || ZodUnknown2.create(), + typeName: ZodFirstPartyTypeKind2.ZodFunction, + ...processCreateParams(params) + }); } - return _nodeCrypto.default.createHash("md5").update(bytes).digest(); - } - var _default3 = exports.default = md5; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v3.js -var require_v3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _v = _interopRequireDefault(require_v35()); - var _md = _interopRequireDefault(require_md5()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var v3 = (0, _v.default)("v3", 48, _md.default); - var _default3 = exports.default = v3; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/native.js -var require_native = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var _default3 = exports.default = { - randomUUID: _nodeCrypto.default.randomUUID }; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v4.js -var require_v4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _native = _interopRequireDefault(require_native()); - var _rng = _interopRequireDefault(require_rng()); - var _stringify2 = require_stringify(); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function v43(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); + ZodLazy2 = class ZodLazy2 extends ZodType2 { + get schema() { + return this._def.getter(); } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - offset = offset || 0; - for (let i = 0;i < 16; ++i) { - buf[offset + i] = rnds[i]; + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + ZodLazy2.create = (getter, params) => { + return new ZodLazy2({ + getter, + typeName: ZodFirstPartyTypeKind2.ZodLazy, + ...processCreateParams(params) + }); + }; + ZodLiteral2 = class ZodLiteral2 extends ZodType2 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_literal, + expected: this._def.value + }); + return INVALID; } - return buf; + return { status: "valid", value: input.data }; } - return (0, _stringify2.unsafeStringify)(rnds); - } - var _default3 = exports.default = v43; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/sha1.js -var require_sha1 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function sha14(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === "string") { - bytes = Buffer.from(bytes, "utf8"); + get value() { + return this._def.value; } - return _nodeCrypto.default.createHash("sha1").update(bytes).digest(); - } - var _default3 = exports.default = sha14; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v5.js -var require_v5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _v = _interopRequireDefault(require_v35()); - var _sha = _interopRequireDefault(require_sha1()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var v54 = (0, _v.default)("v5", 80, _sha.default); - var _default3 = exports.default = v54; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v6.js -var require_v6 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = v6; - var _stringify2 = require_stringify(); - var _v = _interopRequireDefault(require_v1()); - var _v1ToV = _interopRequireDefault(require_v1ToV6()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function v6(options = {}, buf, offset = 0) { - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - bytes = (0, _v1ToV.default)(bytes); - if (buf) { - for (let i = 0;i < 16; i++) { - buf[offset + i] = bytes[i]; + }; + ZodLiteral2.create = (value, params) => { + return new ZodLiteral2({ + value, + typeName: ZodFirstPartyTypeKind2.ZodLiteral, + ...processCreateParams(params) + }); + }; + ZodEnum2 = class ZodEnum2 extends ZodType2 { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID; } - return buf; - } - return (0, _stringify2.unsafeStringify)(bytes); - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v6ToV1.js -var require_v6ToV1 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = v6ToV1; - var _parse2 = _interopRequireDefault(require_parse()); - var _stringify2 = require_stringify(); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function v6ToV1(uuid3) { - const v6Bytes = typeof uuid3 === "string" ? (0, _parse2.default)(uuid3) : uuid3; - const v1Bytes2 = _v6ToV1(v6Bytes); - return typeof uuid3 === "string" ? (0, _stringify2.unsafeStringify)(v1Bytes2) : v1Bytes2; - } - function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 15) << 4 | v6Bytes[4] >> 4 & 15, (v6Bytes[4] & 15) << 4 | (v6Bytes[5] & 240) >> 4, (v6Bytes[5] & 15) << 4 | v6Bytes[6] & 15, v6Bytes[7], (v6Bytes[1] & 15) << 4 | (v6Bytes[2] & 240) >> 4, (v6Bytes[2] & 15) << 4 | (v6Bytes[3] & 240) >> 4, 16 | (v6Bytes[0] & 240) >> 4, (v6Bytes[0] & 15) << 4 | (v6Bytes[1] & 240) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v7.js -var require_v7 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _rng = _interopRequireDefault(require_rng()); - var _stringify2 = require_stringify(); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - var _seqLow = null; - var _seqHigh = null; - var _msecs = 0; - function v73(options, buf, offset) { - options = options || {}; - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - const rnds = options.random || (options.rng || _rng.default)(); - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - let seq = options.seq !== undefined ? options.seq : null; - let seqHigh = _seqHigh; - let seqLow = _seqLow; - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - if (seq !== null) { - seqHigh = null; - seqLow = null; + if (!this._cache) { + this._cache = new Set(this._def.values); } - } - if (seq !== null) { - if (seq > 2147483647) { - seq = 2147483647; + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID; } - seqHigh = seq >>> 19 & 4095; - seqLow = seq & 524287; + return OK(input.data); } - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 127; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 63; - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; + get options() { + return this._def.values; } - if (msecs + 1e4 > _msecs && seq === null) { - if (++seqLow > 524287) { - seqLow = 0; - if (++seqHigh > 4095) { - seqHigh = 0; - _msecs++; - } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - } else { - _msecs = msecs; + return enumValues; } - _seqHigh = seqHigh; - _seqLow = seqLow; - b[i++] = _msecs / 1099511627776 & 255; - b[i++] = _msecs / 4294967296 & 255; - b[i++] = _msecs / 16777216 & 255; - b[i++] = _msecs / 65536 & 255; - b[i++] = _msecs / 256 & 255; - b[i++] = _msecs & 255; - b[i++] = seqHigh >>> 4 & 15 | 112; - b[i++] = seqHigh & 255; - b[i++] = seqLow >>> 13 & 63 | 128; - b[i++] = seqLow >>> 5 & 255; - b[i++] = seqLow << 3 & 255 | rnds[10] & 7; - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify2.unsafeStringify)(b); - } - var _default3 = exports.default = v73; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/version.js -var require_version = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } - function version3(uuid3) { - if (!(0, _validate.default)(uuid3)) { - throw TypeError("Invalid UUID"); + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - return parseInt(uuid3.slice(14, 15), 16); - } - var _default3 = exports.default = version3; -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/index.js -var require_dist2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - Object.defineProperty(exports, "MAX", { - enumerable: true, - get: function() { - return _max.default; + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - }); - Object.defineProperty(exports, "NIL", { - enumerable: true, - get: function() { - return _nil.default; + extract(values, newDef = this._def) { + return ZodEnum2.create(values, { + ...this._def, + ...newDef + }); } - }); - Object.defineProperty(exports, "parse", { - enumerable: true, - get: function() { - return _parse2.default; + exclude(values, newDef = this._def) { + return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return _stringify2.default; + }; + ZodEnum2.create = createZodEnum; + ZodNativeEnum = class ZodNativeEnum extends ZodType2 { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); } - }); - Object.defineProperty(exports, "v1", { - enumerable: true, - get: function() { - return _v.default; + get enum() { + return this._def.values; } - }); - Object.defineProperty(exports, "v1ToV6", { - enumerable: true, - get: function() { - return _v1ToV.default; + }; + ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, + ...processCreateParams(params) + }); + }; + ZodPromise2 = class ZodPromise2 extends ZodType2 { + unwrap() { + return this._def.type; } - }); - Object.defineProperty(exports, "v3", { - enumerable: true, - get: function() { - return _v2.default; + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); } - }); - Object.defineProperty(exports, "v4", { - enumerable: true, - get: function() { - return _v3.default; + }; + ZodPromise2.create = (schema, params) => { + return new ZodPromise2({ + type: schema, + typeName: ZodFirstPartyTypeKind2.ZodPromise, + ...processCreateParams(params) + }); + }; + ZodEffects = class ZodEffects extends ZodType2 { + innerType() { + return this._def.schema; } - }); - Object.defineProperty(exports, "v5", { - enumerable: true, - get: function() { - return _v43.default; - } - }); - Object.defineProperty(exports, "v6", { - enumerable: true, - get: function() { - return _v5.default; - } - }); - Object.defineProperty(exports, "v6ToV1", { - enumerable: true, - get: function() { - return _v6ToV.default; + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } - }); - Object.defineProperty(exports, "v7", { - enumerable: true, - get: function() { - return _v6.default; + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); } - }); - Object.defineProperty(exports, "validate", { - enumerable: true, - get: function() { - return _validate.default; + }; + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect, + ...processCreateParams(params) + }); + }; + ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess2 }, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + ...processCreateParams(params) + }); + }; + ZodOptional2 = class ZodOptional2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); } - }); - Object.defineProperty(exports, "version", { - enumerable: true, - get: function() { - return _version.default; + unwrap() { + return this._def.innerType; } - }); - var _max = _interopRequireDefault(require_max()); - var _nil = _interopRequireDefault(require_nil()); - var _parse2 = _interopRequireDefault(require_parse()); - var _stringify2 = _interopRequireDefault(require_stringify()); - var _v = _interopRequireDefault(require_v1()); - var _v1ToV = _interopRequireDefault(require_v1ToV6()); - var _v2 = _interopRequireDefault(require_v3()); - var _v3 = _interopRequireDefault(require_v4()); - var _v43 = _interopRequireDefault(require_v5()); - var _v5 = _interopRequireDefault(require_v6()); - var _v6ToV = _interopRequireDefault(require_v6ToV1()); - var _v6 = _interopRequireDefault(require_v7()); - var _validate = _interopRequireDefault(require_validate()); - var _version = _interopRequireDefault(require_version()); - function _interopRequireDefault(e) { - return e && e.__esModule ? e : { default: e }; - } -}); - -// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/wrapper.mjs -var import_dist, v12, v1ToV6, v3, v43, v54, v6, v6ToV1, v73, NIL, MAX, version3, validate7, stringify2, parse8; -var init_wrapper = __esm(() => { - import_dist = __toESM(require_dist2(), 1); - v12 = import_dist.default.v1; - v1ToV6 = import_dist.default.v1ToV6; - v3 = import_dist.default.v3; - v43 = import_dist.default.v4; - v54 = import_dist.default.v5; - v6 = import_dist.default.v6; - v6ToV1 = import_dist.default.v6ToV1; - v73 = import_dist.default.v7; - NIL = import_dist.default.NIL; - MAX = import_dist.default.MAX; - version3 = import_dist.default.version; - validate7 = import_dist.default.validate; - stringify2 = import_dist.default.stringify; - parse8 = import_dist.default.parse; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/id.js -function uuid62(clockseq) { - return v6({ clockseq }); -} -function uuid5(name, namespace) { - const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); - return v54(name, new Uint8Array(namespaceBytes)); -} -var init_id2 = __esm(() => { - init_wrapper(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js -var TASKS2 = "__pregel_tasks", ERROR3 = "__error__", SCHEDULED = "__scheduled__", INTERRUPT2 = "__interrupt__", RESUME2 = "__resume__"; -var init_types5 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js -function defaultOptions3() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER }; -} -function stringify3(obj, replacer, spacer, options) { - if (typeof options === "undefined") - options = defaultOptions3(); - decirc2(obj, "", 0, [], undefined, 0, options); - var res; - try { - if (replacerStack2.length === 0) - res = JSON.stringify(obj, replacer, spacer); - else - res = JSON.stringify(obj, replaceGetterValues2(replacer), spacer); - } catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } finally { - while (arr2.length !== 0) { - var part = arr2.pop(); - if (part.length === 4) - Object.defineProperty(part[0], part[1], part[3]); - else - part[0][part[1]] = part[2]; - } - } - return res; -} -function setReplace2(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr2.push([ - parent, - k, - val, - propertyDescriptor - ]); - } else - replacerStack2.push([ - val, - k, - replace - ]); - else { - parent[k] = replace; - arr2.push([ - parent, - k, - val - ]); - } -} -function decirc2(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0;i < stack.length; i++) - if (stack[i] === val) { - setReplace2(CIRCULAR_REPLACE_NODE2, val, k, parent); - return; + ZodOptional2.create = (type, params) => { + return new ZodOptional2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodOptional, + ...processCreateParams(params) + }); + }; + ZodNullable2 = class ZodNullable2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 === ZodParsedType.null) { + return OK(null); } - if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { - setReplace2(LIMIT_REPLACE_NODE2, val, k, parent); - return; + return this._def.innerType._parse(input); } - if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { - setReplace2(LIMIT_REPLACE_NODE2, val, k, parent); - return; + unwrap() { + return this._def.innerType; } - stack.push(val); - if (Array.isArray(val)) - for (i = 0;i < val.length; i++) - decirc2(val[i], i, i, stack, val, depth, options); - else { - var keys = Object.keys(val); - for (i = 0;i < keys.length; i++) { - var key = keys[i]; - decirc2(val[key], key, i, stack, val, depth, options); + }; + ZodNullable2.create = (type, params) => { + return new ZodNullable2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodNullable, + ...processCreateParams(params) + }); + }; + ZodDefault2 = class ZodDefault2 extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; } - stack.pop(); - } -} -function replaceGetterValues2(replacer) { - replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { - return v; }; - return function(key, val) { - if (replacerStack2.length > 0) - for (var i = 0;i < replacerStack2.length; i++) { - var part = replacerStack2[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack2.splice(i, 1); - break; + ZodDefault2.create = (type, params) => { + return new ZodDefault2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); + }; + ZodCatch2 = class ZodCatch2 extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; } - return replacer.call(this, key, val); - }; -} -var LIMIT_REPLACE_NODE2 = "[...]", CIRCULAR_REPLACE_NODE2 = "[Circular]", arr2, replacerStack2; -var init_fast_safe_stringify2 = __esm(() => { - arr2 = []; - replacerStack2 = []; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/import_constants.js -var optionalImportEntrypoints; -var init_import_constants = __esm(() => { - optionalImportEntrypoints = []; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/index.js -var src_exports; -var init_dist2 = __esm(() => { - init_runtime2(); - src_exports = /* @__PURE__ */ __exportAll({}); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/agents.js -var agents_exports; -var init_agents = __esm(() => { - init_runtime2(); - agents_exports = /* @__PURE__ */ __exportAll({}); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/chat_history.js -var chat_history_exports, BaseChatMessageHistory, BaseListChatMessageHistory, InMemoryChatMessageHistory; -var init_chat_history = __esm(() => { - init_runtime2(); - init_serializable(); - init_ai(); - init_human(); - init_messages(); - chat_history_exports = /* @__PURE__ */ __exportAll({ - BaseChatMessageHistory: () => BaseChatMessageHistory, - BaseListChatMessageHistory: () => BaseListChatMessageHistory, - InMemoryChatMessageHistory: () => InMemoryChatMessageHistory - }); - BaseChatMessageHistory = class extends Serializable { - async addMessages(messages) { - for (const message of messages) - await this.addMessage(message); } - }; - BaseListChatMessageHistory = class extends Serializable { - addUserMessage(message) { - return this.addMessage(new HumanMessage(message)); + removeCatch() { + return this._def.innerType; } - addAIMessage(message) { - return this.addMessage(new AIMessage(message)); + }; + ZodCatch2.create = (type, params) => { + return new ZodCatch2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); + }; + ZodNaN2 = class ZodNaN2 extends ZodType2 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; } - async addMessages(messages) { - for (const message of messages) - await this.addMessage(message); + }; + ZodNaN2.create = (params) => { + return new ZodNaN2({ + typeName: ZodFirstPartyTypeKind2.ZodNaN, + ...processCreateParams(params) + }); + }; + BRAND = Symbol("zod_brand"); + ZodBranded = class ZodBranded extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); } - clear() { - throw new Error("Not implemented."); + unwrap() { + return this._def.type; } }; - InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain", - "stores", - "message", - "in_memory" - ]; - messages = []; - constructor(messages) { - super(...arguments); - this.messages = messages ?? []; + ZodPipeline = class ZodPipeline extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } } - async getMessages() { - return this.messages; + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind2.ZodPipeline + }); } - async addMessage(message) { - this.messages.push(message); + }; + ZodReadonly2 = class ZodReadonly2 extends ZodType2 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } - async clear() { - this.messages = []; + unwrap() { + return this._def.innerType; } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/documents/document.js -var Document = class { - pageContent; - metadata; - id; - constructor(fields) { - this.pageContent = fields.pageContent !== undefined ? fields.pageContent.toString() : ""; - this.metadata = fields.metadata ?? {}; - this.id = fields.id; - } -}; -var init_document = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/documents/transformers.js -var BaseDocumentTransformer, MappingDocumentTransformer; -var init_transformers2 = __esm(() => { - init_base4(); - BaseDocumentTransformer = class extends Runnable { - lc_namespace = [ - "langchain_core", - "documents", - "transformers" - ]; - invoke(input, _options) { - return this.transformDocuments(input); - } + ZodReadonly2.create = (type, params) => { + return new ZodReadonly2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodReadonly, + ...processCreateParams(params) + }); }; - MappingDocumentTransformer = class extends BaseDocumentTransformer { - async transformDocuments(documents) { - const newDocuments = []; - for (const document2 of documents) { - const transformedDocument = await this._transformDocument(document2); - newDocuments.push(transformedDocument); - } - return newDocuments; - } + late = { + object: ZodObject2.lazycreate + }; + (function(ZodFirstPartyTypeKind3) { + ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); + stringType = ZodString2.create; + numberType = ZodNumber2.create; + nanType = ZodNaN2.create; + bigIntType = ZodBigInt2.create; + booleanType = ZodBoolean2.create; + dateType = ZodDate2.create; + symbolType = ZodSymbol2.create; + undefinedType = ZodUndefined2.create; + nullType = ZodNull2.create; + anyType = ZodAny2.create; + unknownType = ZodUnknown2.create; + neverType = ZodNever2.create; + voidType = ZodVoid2.create; + arrayType = ZodArray2.create; + objectType = ZodObject2.create; + strictObjectType = ZodObject2.strictCreate; + unionType = ZodUnion2.create; + discriminatedUnionType = ZodDiscriminatedUnion2.create; + intersectionType = ZodIntersection2.create; + tupleType = ZodTuple2.create; + recordType = ZodRecord2.create; + mapType = ZodMap2.create; + setType = ZodSet2.create; + functionType = ZodFunction2.create; + lazyType = ZodLazy2.create; + literalType = ZodLiteral2.create; + enumType = ZodEnum2.create; + nativeEnumType = ZodNativeEnum.create; + promiseType = ZodPromise2.create; + effectsType = ZodEffects.create; + optionalType = ZodOptional2.create; + nullableType = ZodNullable2.create; + preprocessType = ZodEffects.createWithPreprocess; + pipelineType = ZodPipeline.create; + coerce = { + string: (arg) => ZodString2.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber2.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean2.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt2.create({ ...arg, coerce: true }), + date: (arg) => ZodDate2.create({ ...arg, coerce: true }) }; + NEVER3 = INVALID; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/documents/index.js -var documents_exports; -var init_documents = __esm(() => { - init_runtime2(); - init_document(); - init_transformers2(); - documents_exports = /* @__PURE__ */ __exportAll({ - BaseDocumentTransformer: () => BaseDocumentTransformer, - Document: () => Document, - MappingDocumentTransformer: () => MappingDocumentTransformer - }); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js +var exports_external2 = {}; +__export(exports_external2, { + void: () => voidType, + util: () => util, + unknown: () => unknownType, + union: () => unionType, + undefined: () => undefinedType, + tuple: () => tupleType, + transformer: () => effectsType, + symbol: () => symbolType, + string: () => stringType, + strictObject: () => strictObjectType, + setErrorMap: () => setErrorMap2, + set: () => setType, + record: () => recordType, + quotelessJson: () => quotelessJson, + promise: () => promiseType, + preprocess: () => preprocessType, + pipeline: () => pipelineType, + ostring: () => ostring, + optional: () => optionalType, + onumber: () => onumber, + oboolean: () => oboolean, + objectUtil: () => objectUtil, + object: () => objectType, + number: () => numberType, + nullable: () => nullableType, + null: () => nullType, + never: () => neverType, + nativeEnum: () => nativeEnumType, + nan: () => nanType, + map: () => mapType, + makeIssue: () => makeIssue, + literal: () => literalType, + lazy: () => lazyType, + late: () => late, + isValid: () => isValid, + isDirty: () => isDirty, + isAsync: () => isAsync, + isAborted: () => isAborted, + intersection: () => intersectionType, + instanceof: () => instanceOfType, + getParsedType: () => getParsedType3, + getErrorMap: () => getErrorMap2, + function: () => functionType, + enum: () => enumType, + effect: () => effectsType, + discriminatedUnion: () => discriminatedUnionType, + defaultErrorMap: () => en_default3, + datetimeRegex: () => datetimeRegex, + date: () => dateType, + custom: () => custom2, + coerce: () => coerce, + boolean: () => booleanType, + bigint: () => bigIntType, + array: () => arrayType, + any: () => anyType, + addIssueToContext: () => addIssueToContext, + ZodVoid: () => ZodVoid2, + ZodUnknown: () => ZodUnknown2, + ZodUnion: () => ZodUnion2, + ZodUndefined: () => ZodUndefined2, + ZodType: () => ZodType2, + ZodTuple: () => ZodTuple2, + ZodTransformer: () => ZodEffects, + ZodSymbol: () => ZodSymbol2, + ZodString: () => ZodString2, + ZodSet: () => ZodSet2, + ZodSchema: () => ZodType2, + ZodRecord: () => ZodRecord2, + ZodReadonly: () => ZodReadonly2, + ZodPromise: () => ZodPromise2, + ZodPipeline: () => ZodPipeline, + ZodParsedType: () => ZodParsedType, + ZodOptional: () => ZodOptional2, + ZodObject: () => ZodObject2, + ZodNumber: () => ZodNumber2, + ZodNullable: () => ZodNullable2, + ZodNull: () => ZodNull2, + ZodNever: () => ZodNever2, + ZodNativeEnum: () => ZodNativeEnum, + ZodNaN: () => ZodNaN2, + ZodMap: () => ZodMap2, + ZodLiteral: () => ZodLiteral2, + ZodLazy: () => ZodLazy2, + ZodIssueCode: () => ZodIssueCode2, + ZodIntersection: () => ZodIntersection2, + ZodFunction: () => ZodFunction2, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2, + ZodError: () => ZodError2, + ZodEnum: () => ZodEnum2, + ZodEffects: () => ZodEffects, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodDefault: () => ZodDefault2, + ZodDate: () => ZodDate2, + ZodCatch: () => ZodCatch2, + ZodBranded: () => ZodBranded, + ZodBoolean: () => ZodBoolean2, + ZodBigInt: () => ZodBigInt2, + ZodArray: () => ZodArray2, + ZodAny: () => ZodAny2, + Schema: () => ZodType2, + ParseStatus: () => ParseStatus, + OK: () => OK, + NEVER: () => NEVER3, + INVALID: () => INVALID, + EMPTY_PATH: () => EMPTY_PATH, + DIRTY: () => DIRTY, + BRAND: () => BRAND }); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/document_loaders/base.js -var base_exports4, BaseDocumentLoader = class { -}; -var init_base7 = __esm(() => { - init_runtime2(); - base_exports4 = /* @__PURE__ */ __exportAll({ BaseDocumentLoader: () => BaseDocumentLoader }); +var init_external2 = __esm(() => { + init_errors5(); + init_parseUtil(); + init_typeAliases(); + init_util3(); + init_types(); + init_ZodError(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/document_loaders/langsmith.js -function _stringify2(x) { - if (typeof x === "string") - return x; - else - try { - return JSON.stringify(x, null, 2); - } catch { - return String(x); - } -} -var langsmith_exports, LangSmithLoader; -var init_langsmith2 = __esm(() => { - init_runtime2(); - init_base7(); - init_langsmith(); - langsmith_exports = /* @__PURE__ */ __exportAll({ LangSmithLoader: () => LangSmithLoader }); - LangSmithLoader = class extends BaseDocumentLoader { - datasetId; - datasetName; - exampleIds; - asOf; - splits; - inlineS3Urls; - offset; - limit; - metadata; - filter; - contentKey; - formatContent; - client; - constructor(fields) { - super(); - if (fields.client && fields.clientConfig) - throw new Error("client and clientConfig cannot both be provided."); - this.client = fields.client ?? new Client(fields?.clientConfig); - this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; - this.formatContent = fields.formatContent ?? _stringify2; - this.datasetId = fields.datasetId; - this.datasetName = fields.datasetName; - this.exampleIds = fields.exampleIds; - this.asOf = fields.asOf; - this.splits = fields.splits; - this.inlineS3Urls = fields.inlineS3Urls; - this.offset = fields.offset; - this.limit = fields.limit; - this.metadata = fields.metadata; - this.filter = fields.filter; - } - async load() { - const documents = []; - for await (const example of this.client.listExamples({ - datasetId: this.datasetId, - datasetName: this.datasetName, - exampleIds: this.exampleIds, - asOf: this.asOf, - splits: this.splits, - inlineS3Urls: this.inlineS3Urls, - offset: this.offset, - limit: this.limit, - metadata: this.metadata, - filter: this.filter - })) { - let content = example.inputs; - for (const key of this.contentKey) - content = content[key]; - const contentStr = this.formatContent(content); - const metadata = example; - ["created_at", "modified_at"].forEach((k) => { - if (k in metadata) { - if (typeof metadata[k] === "object") - metadata[k] = metadata[k].toString(); - } - }); - documents.push({ - pageContent: contentStr, - metadata - }); - } - return documents; - } - }; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/index.js +var init_v3 = __esm(() => { + init_external2(); + init_external2(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/embeddings.js -var embeddings_exports, Embeddings = class { - caller; - constructor(params) { - this.caller = new AsyncCaller2(params ?? {}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js +function parseArrayDef(def, refs) { + const res = { type: "array" }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + if (def.minLength) + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + if (def.maxLength) + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } -}; -var init_embeddings = __esm(() => { - init_runtime2(); - init_async_caller2(); - embeddings_exports = /* @__PURE__ */ __exportAll({ Embeddings: () => Embeddings }); + return res; +} +var init_array = __esm(() => { + init_errorMessages(); + init_parseDef(); + init_v3(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/example_selectors/base.js -var BaseExampleSelector; -var init_base8 = __esm(() => { - init_serializable(); - BaseExampleSelector = class extends Serializable { - lc_namespace = [ - "langchain_core", - "example_selectors", - "base" - ]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64" }; + if (!def.checks) + return res; + for (const check2 of def.checks) + switch (check2.kind) { + case "min": + if (refs.target === "jsonSchema7") + if (check2.inclusive) + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + else + setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); + else { + if (!check2.inclusive) + res.exclusiveMinimum = true; + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") + if (check2.inclusive) + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + else + setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); + else { + if (!check2.inclusive) + res.exclusiveMaximum = true; + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); + break; + } + return res; +} +var init_bigint = __esm(() => { + init_errorMessages(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/example_selectors/conditional.js -function isLLM(llm) { - return llm._modelType() === "base_llm"; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js +function parseBooleanDef() { + return { type: "boolean" }; } -function isChatModel(llm) { - return llm._modelType() === "base_chat_model"; +var init_boolean = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); } -var BasePromptSelector = class { - async getPromptAsync(llm, options) { - return this.getPrompt(llm).partial(options?.partialVariables ?? {}); - } -}, ConditionalPromptSelector; -var init_conditional = __esm(() => { - ConditionalPromptSelector = class extends BasePromptSelector { - defaultPrompt; - conditionals; - constructor(default_prompt, conditionals = []) { - super(); - this.defaultPrompt = default_prompt; - this.conditionals = conditionals; - } - getPrompt(llm) { - for (const [condition, prompt] of this.conditionals) - if (condition(llm)) - return prompt; - return this.defaultPrompt; - } - }; +var init_branded = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/example_selectors/length_based.js -function getLengthBased(text) { - return text.split(/\n| /).length; -} -var LengthBasedExampleSelector; -var init_length_based = __esm(() => { - init_base8(); - LengthBasedExampleSelector = class LengthBasedExampleSelector2 extends BaseExampleSelector { - examples = []; - examplePrompt; - getTextLength = getLengthBased; - maxLength = 2048; - exampleTextLengths = []; - constructor(data) { - super(data); - this.examplePrompt = data.examplePrompt; - this.maxLength = data.maxLength ?? 2048; - this.getTextLength = data.getTextLength ?? getLengthBased; - } - async addExample(example) { - this.examples.push(example); - const stringExample = await this.examplePrompt.format(example); - this.exampleTextLengths.push(this.getTextLength(stringExample)); - } - async calculateExampleTextLengths(v, values) { - if (v.length > 0) - return v; - const { examples, examplePrompt } = values; - return (await Promise.all(examples.map((eg) => examplePrompt.format(eg)))).map((eg) => this.getTextLength(eg)); - } - async selectExamples(inputVariables) { - const inputs = Object.values(inputVariables).join(" "); - let remainingLength = this.maxLength - this.getTextLength(inputs); - let i = 0; - const examples = []; - while (remainingLength > 0 && i < this.examples.length) { - const newLength = remainingLength - this.exampleTextLengths[i]; - if (newLength < 0) - break; - else { - examples.push(this.examples[i]); - remainingLength = newLength; - } - i += 1; - } - return examples; - } - static async fromExamples(examples, args) { - const selector = new LengthBasedExampleSelector2(args); - await Promise.all(examples.map((eg) => selector.addExample(eg))); - return selector; - } - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js +var parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +var init_catch = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js -function sortedValues(values) { - return Object.keys(values).sort().map((key) => values[key]); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) + return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser(def, refs); + } } -var SemanticSimilarityExampleSelector; -var init_semantic_similarity = __esm(() => { - init_document(); - init_base8(); - SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector2 extends BaseExampleSelector { - vectorStoreRetriever; - exampleKeys; - inputKeys; - constructor(data) { - super(data); - this.exampleKeys = data.exampleKeys; - this.inputKeys = data.inputKeys; - if (data.vectorStore !== undefined) - this.vectorStoreRetriever = data.vectorStore.asRetriever({ - k: data.k ?? 4, - filter: data.filter - }); - else if (data.vectorStoreRetriever) - this.vectorStoreRetriever = data.vectorStoreRetriever; - else - throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); - } - async addExample(example) { - const stringExample = sortedValues((this.inputKeys ?? Object.keys(example)).reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})).join(" "); - await this.vectorStoreRetriever.addDocuments([new Document({ - pageContent: stringExample, - metadata: example - })]); - } - async selectExamples(inputVariables) { - const query3 = sortedValues((this.inputKeys ?? Object.keys(inputVariables)).reduce((acc, key) => ({ - ...acc, - [key]: inputVariables[key] - }), {})).join(" "); - const examples = (await this.vectorStoreRetriever.invoke(query3)).map((doc2) => doc2.metadata); - if (this.exampleKeys) - return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})); - return examples; - } - static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { - const inputKeys = options.inputKeys ?? null; - const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {}) : example).join(" ")); - return new SemanticSimilarityExampleSelector2({ - vectorStore: await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options), - k: options.k ?? 4, - exampleKeys: options.exampleKeys, - inputKeys: options.inputKeys - }); +var integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") + return res; + for (const check2 of def.checks) + switch (check2.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + break; } + return res; +}; +var init_date = __esm(() => { + init_errorMessages(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() }; +} +var init_default = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/example_selectors/index.js -var example_selectors_exports; -var init_example_selectors = __esm(() => { - init_runtime2(); - init_base8(); - init_conditional(); - init_length_based(); - init_semantic_similarity(); - example_selectors_exports = /* @__PURE__ */ __exportAll({ - BaseExampleSelector: () => BaseExampleSelector, - BasePromptSelector: () => BasePromptSelector, - ConditionalPromptSelector: () => ConditionalPromptSelector, - LengthBasedExampleSelector: () => LengthBasedExampleSelector, - SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, - isChatModel: () => isChatModel, - isLLM: () => isLLM - }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} +var init_effects = __esm(() => { + init_any(); + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/indexing/record_manager.js -var UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a", RecordManager; -var init_record_manager = __esm(() => { - init_serializable(); - RecordManager = class extends Serializable { - lc_namespace = ["langchain", "recordmanagers"]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) }; -}); +} +var init_enum = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/indexing/base.js -function _batch(size, iterable) { - const batches = []; - let currentBatch = []; - iterable.forEach((item) => { - currentBatch.push(item); - if (currentBatch.length >= size) { - batches.push(currentBatch); - currentBatch = []; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js +function parseIntersectionDef(def, refs) { + const allOf = [parseDef(def.left._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }), parseDef(def.right._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "1" + ] + })].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) + unevaluatedProperties = undefined; + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else + unevaluatedProperties = undefined; + mergedAllOf.push(nestedSchema); } }); - if (currentBatch.length > 0) - batches.push(currentBatch); - return batches; + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : undefined; } -function _deduplicateInOrder(hashedDocuments) { - const seen = /* @__PURE__ */ new Set; - const deduplicated = []; - for (const hashedDoc of hashedDocuments) { - if (!hashedDoc.hash_) - throw new Error("Hashed document does not have a hash"); - if (!seen.has(hashedDoc.hash_)) { - seen.add(hashedDoc.hash_); - deduplicated.push(hashedDoc); - } - } - return deduplicated; +var isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; +}; +var init_intersection = __esm(() => { + init_parseDef(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js +function parseLiteralDef(def, refs) { + const parsedType5 = typeof def.value; + if (parsedType5 !== "bigint" && parsedType5 !== "number" && parsedType5 !== "boolean" && parsedType5 !== "string") + return { type: Array.isArray(def.value) ? "array" : "object" }; + if (refs.target === "openApi3") + return { + type: parsedType5 === "bigint" ? "integer" : parsedType5, + enum: [def.value] + }; + return { + type: parsedType5 === "bigint" ? "integer" : parsedType5, + const: def.value + }; } -function _getSourceIdAssigner(sourceIdKey) { - if (sourceIdKey === null) - return (_doc) => null; - else if (typeof sourceIdKey === "string") - return (doc2) => doc2.metadata[sourceIdKey]; - else if (typeof sourceIdKey === "function") - return sourceIdKey; - else - throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); +var init_literal = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js +function parseStringDef(def, refs) { + const res = { type: "string" }; + if (def.checks) + for (const check2 of def.checks) + switch (check2.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check2.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check2.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check2.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check2.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check2.message, refs); + break; + case "regex": + addPattern(res, check2.regex, check2.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check2.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check2.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check2.message, refs); + break; + case "date": + addFormat(res, "date", check2.message, refs); + break; + case "time": + addFormat(res, "time", check2.message, refs); + break; + case "duration": + addFormat(res, "duration", check2.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); + break; + case "includes": + addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); + break; + case "ip": + if (check2.version !== "v6") + addFormat(res, "ipv4", check2.message, refs); + if (check2.version !== "v4") + addFormat(res, "ipv6", check2.message, refs); + break; + case "base64url": + addPattern(res, zodPatterns.base64url, check2.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check2.message, refs); + break; + case "cidr": + if (check2.version !== "v6") + addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); + if (check2.version !== "v4") + addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); + break; + case "emoji": + addPattern(res, zodPatterns.emoji(), check2.message, refs); + break; + case "ulid": + addPattern(res, zodPatterns.ulid, check2.message, refs); + break; + case "base64": + switch (refs.base64Strategy) { + case "format:binary": + addFormat(res, "binary", check2.message, refs); + break; + case "contentEncoding:base64": + setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.base64, check2.message, refs); + break; + } + break; + case "nanoid": + addPattern(res, zodPatterns.nanoid, check2.message, refs); + break; + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + ((_) => {})(check2); + } + return res; } -async function index(args) { - const { docsSource, recordManager, vectorStore, options } = args; - const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1000, forceUpdate = false } = options ?? {}; - if (cleanup === "incremental" && !sourceIdKey) - throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); - const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; - const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); - const indexStartDt = await recordManager.getTime(); - let numAdded = 0; - let numDeleted = 0; - let numUpdated = 0; - let numSkipped = 0; - const batches = _batch(batchSize ?? 100, docs); - for (const batch of batches) { - const hashedDocs = _deduplicateInOrder(batch.map((doc2) => _HashedDocument.fromDocument(doc2))); - const sourceIds = hashedDocs.map((doc2) => sourceIdAssigner(doc2)); - if (cleanup === "incremental") - hashedDocs.forEach((_hashedDoc, index2) => { - if (sourceIds[index2] === null) - throw new Error("sourceIdKey must be provided when cleanup is incremental"); +function escapeLiteralCheckValue(literal2, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; +} +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0;i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) + result += "\\"; + result += source[i]; + } + return result; +} +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) + schema.anyOf = []; + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } }); - const batchExists = await recordManager.exists(hashedDocs.map((doc2) => doc2.uid)); - const uids = []; - const docsToIndex = []; - const docsToUpdate = []; - const seenDocs = /* @__PURE__ */ new Set; - hashedDocs.forEach((hashedDoc, i) => { - if (batchExists[i]) - if (forceUpdate) - seenDocs.add(hashedDoc.uid); - else { - docsToUpdate.push(hashedDoc.uid); - return; - } - uids.push(hashedDoc.uid); - docsToIndex.push(hashedDoc.toDocument()); - }); - if (docsToUpdate.length > 0) { - await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); - numSkipped += docsToUpdate.length; - } - if (docsToIndex.length > 0) { - await vectorStore.addDocuments(docsToIndex, { ids: uids }); - numAdded += docsToIndex.length - seenDocs.size; - numUpdated += seenDocs.size; + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) + delete schema.errorMessage; + } } - await recordManager.update(hashedDocs.map((doc2) => doc2.uid), { - timeAtLeast: indexStartDt, - groupIds: sourceIds + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } }); - if (cleanup === "incremental") { - sourceIds.forEach((sourceId) => { - if (!sourceId) - throw new Error("Source id cannot be null"); - }); - const uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - groupIds: sourceIds + } else + setResponseValueAndErrors(schema, "format", value, message, refs); +} +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) + schema.allOf = []; + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } }); - if (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) + delete schema.errorMessage; } } - } - if (cleanup === "full") { - let uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } }); - while (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; - uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize - }); + } else + setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); +} +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) + return regex.source; + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0;i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else + pattern += `${source[i]}${source[i].toUpperCase()}`; + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r +` : `[${source[i]}\r +]`; + continue; } + pattern += source[i]; + if (source[i] === "\\") + isEscaped = true; + else if (inCharGroup && source[i] === "]") + inCharGroup = false; + else if (!inCharGroup && source[i] === "[") + inCharGroup = true; + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} +var emojiRegex2 = undefined, zodPatterns, ALPHA_NUMERIC; +var init_string = __esm(() => { + init_errorMessages(); + zodPatterns = { + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + emoji: () => { + if (emojiRegex2 === undefined) + emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + return emojiRegex2; + }, + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ + }; + ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js +function parseRecordDef(def, refs) { + if (refs.target === "openAi") + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + key + ] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") + return schema; + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) + return { + ...schema, + propertyNames: { enum: def.keyType._def.values } + }; + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; } + return schema; +} +var init_record = __esm(() => { + init_any(); + init_branded(); + init_string(); + init_parseDef(); + init_v3(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") + return parseRecordDef(def, refs); return { - numAdded, - numDeleted, - numUpdated, - numSkipped + type: "array", + maxItems: 125, + items: { + type: "array", + items: [parseDef(def.keyType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "0" + ] + }) || parseAnyDef(refs), parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "1" + ] + }) || parseAnyDef(refs)], + minItems: 2, + maxItems: 2 + } }; } -var _HashedDocument = class { - uid; - hash_; - contentHash; - metadataHash; - pageContent; - metadata; - keyEncoder = sha256; - constructor(fields) { - this.uid = fields.uid; - this.pageContent = fields.pageContent; - this.metadata = fields.metadata; - } - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } - calculateHashes() { - const forbiddenKeys = [ - "hash_", - "content_hash", - "metadata_hash" - ]; - for (const key of forbiddenKeys) - if (key in this.metadata) - throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); - const contentHash = this._hashStringToUUID(this.pageContent); - try { - const metadataHash = this._hashNestedDictToUUID(this.metadata); - this.contentHash = contentHash; - this.metadataHash = metadataHash; - } catch (e) { - throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); +var init_map = __esm(() => { + init_any(); + init_record(); + init_parseDef(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object2 = def.values; + const actualValues = Object.keys(def.values).filter((key) => { + return typeof object2[object2[key]] !== "number"; + }).map((key) => object2[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; +} +var init_nativeEnum = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js +function parseNeverDef(refs) { + return refs.target === "openAi" ? undefined : { not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) }; +} +var init_never = __esm(() => { + init_any(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { type: "null" }; +} +var init_null = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => (x._def.typeName in primitiveMappings) && (!x._def.checks || !x._def.checks.length))) { + const types2 = options.reduce((types3, x) => { + const type = primitiveMappings[x._def.typeName]; + return type && !types3.includes(type) ? [...types3, type] : types3; + }, []); + return { type: types2.length > 1 ? types2 : types2[0] }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types2 = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + return acc; + default: + return acc; + } + }, []); + if (types2.length === options.length) { + const uniqueTypes = types2.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; } - this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); - if (!this.uid) - this.uid = this.hash_; + } else if (options.every((x) => x._def.typeName === "ZodEnum")) + return { + type: "string", + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], []) + }; + return asAnyOf(def, refs); +} +var primitiveMappings, asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + `${i}` + ] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : undefined; +}; +var init_union = __esm(() => { + init_parseDef(); + primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js +function parseNullableDef(def, refs) { + if ([ + "ZodString", + "ZodNumber", + "ZodBigInt", + "ZodBoolean", + "ZodNull" + ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; } - toDocument() { - return new Document({ - pageContent: this.pageContent, - metadata: this.metadata + if (refs.target === "openApi3") { + const base2 = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] }); + if (base2 && "$ref" in base2) + return { + allOf: [base2], + nullable: true + }; + return base2 && { + ...base2, + nullable: true + }; } - static fromDocument(document2, uid) { - const doc2 = new this({ - pageContent: document2.pageContent, - metadata: document2.metadata, - uid: uid || document2.uid + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "0" + ] + }); + return base && { anyOf: [base, { type: "null" }] }; +} +var init_nullable = __esm(() => { + init_union(); + init_parseDef(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js +function parseNumberDef(def, refs) { + const res = { type: "number" }; + if (!def.checks) + return res; + for (const check2 of def.checks) + switch (check2.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check2.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") + if (check2.inclusive) + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + else + setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); + else { + if (!check2.inclusive) + res.exclusiveMinimum = true; + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") + if (check2.inclusive) + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + else + setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); + else { + if (!check2.inclusive) + res.exclusiveMaximum = true; + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); + break; + } + return res; +} +var init_number = __esm(() => { + init_errorMessages(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required3 = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === undefined || propDef._def === undefined) + continue; + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") + propDef = propDef._def.innerType; + if (!propDef.isNullable()) + propDef = propDef.nullable(); + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + propName + ], + propertyPath: [ + ...refs.currentPath, + "properties", + propName + ] }); - doc2.calculateHashes(); - return doc2; - } - _hashStringToUUID(inputString) { - return v52(this.keyEncoder(inputString), UUIDV5_NAMESPACE); + if (parsedDef === undefined) + continue; + result.properties[propName] = parsedDef; + if (!propOptional) + required3.push(propName); } - _hashNestedDictToUUID(data) { - const serialized_data = JSON.stringify(data, Object.keys(data).sort()); - return v52(this.keyEncoder(serialized_data), UUIDV5_NAMESPACE); + if (required3.length) + result.required = required3; + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== undefined) + result.additionalProperties = additionalProperties; + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; } -}, _isBaseDocumentLoader = (arg) => { - if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } catch { return true; - return false; -}; -var init_base9 = __esm(() => { - init_hash(); - init_hash2(); - init_v5(); - init_uuid(); - init_document(); - init_record_manager(); + } +} +var init_object = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/indexing/index.js -var indexing_exports; -var init_indexing = __esm(() => { - init_runtime2(); - init_record_manager(); - init_base9(); - indexing_exports = /* @__PURE__ */ __exportAll({ - RecordManager: () => RecordManager, - UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, - _HashedDocument: () => _HashedDocument, - _batch: () => _batch, - _deduplicateInOrder: () => _deduplicateInOrder, - _getSourceIdAssigner: () => _getSourceIdAssigner, - _isBaseDocumentLoader: () => _isBaseDocumentLoader, - index: () => index +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js +var parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) + return parseDef(def.innerType._def, refs); + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "1" + ] }); + return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); +}; +var init_optional = __esm(() => { + init_any(); + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/event.js -var event_exports; -var init_event = __esm(() => { - init_runtime2(); - event_exports = /* @__PURE__ */ __exportAll({}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js +var parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") + return parseDef(def.in._def, refs); + else if (refs.pipeStrategy === "output") + return parseDef(def.out._def, refs); + const a = parseDef(def.in._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }); + return { allOf: [a, parseDef(def.out._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + a ? "1" : "0" + ] + })].filter((x) => x !== undefined) }; +}; +var init_pipeline = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/llms.js -var llms_exports, BaseLLM, LLM; -var init_llms = __esm(() => { - init_runtime2(); - init_base2(); - init_manager(); - init_stream(); - init_outputs(); - init_base5(); - llms_exports = /* @__PURE__ */ __exportAll({ - BaseLLM: () => BaseLLM, - LLM: () => LLM - }); - BaseLLM = class BaseLLM2 extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "llms", - this._llmType() - ]; - async invoke(input, options) { - const promptValue = BaseLLM2._convertInputToPromptValue(input); - return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].text; - } - async* _streamResponseChunks(_input, _options, _runManager) { - throw new Error("Not implemented."); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - async* _streamIterator(input, options) { - if (this._streamResponseChunks === BaseLLM2.prototype._streamResponseChunks) - yield this.invoke(input, options); - else { - const prompt = BaseLLM2._convertInputToPromptValue(input); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const invocationParams = this.invocationParams(callOptions); - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) - }); - const extra = { - options: callOptions, - invocation_params: invocationParams, - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); - let generation = new GenerationChunk({ text: "" }); - try { - for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { - if (!generation) - generation = chunk; - else - generation = generation.concat(chunk); - if (typeof chunk.text === "string") - yield chunk.text; - } - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); - } - } - async generatePrompt(promptValues, options, callbacks) { - const prompts = promptValues.map((promptValue) => promptValue.toString()); - return this.generate(prompts, options, callbacks); - } - invocationParams(_options) { - return {}; - } - _flattenLLMResult(llmResult) { - const llmResults = []; - for (let i = 0;i < llmResult.generations.length; i += 1) { - const genList = llmResult.generations[i]; - if (i === 0) - llmResults.push({ - generations: [genList], - llmOutput: llmResult.llmOutput - }); - else { - const llmOutput = llmResult.llmOutput ? { - ...llmResult.llmOutput, - tokenUsage: {} - } : undefined; - llmResults.push({ - generations: [genList], - llmOutput - }); - } - } - return llmResults; - } - async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { - let runManagers; - if (startedRunManagers !== undefined && startedRunManagers.length === prompts.length) - runManagers = startedRunManagers; - else { - const invocationParams = this.invocationParams(parsedOptions); - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) - }); - const extra = { - options: parsedOptions, - invocation_params: invocationParams, - batch_size: prompts.length - }; - runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, undefined, extra, undefined, undefined, handledOptions?.runName); - } - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - let output; - if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM2.prototype._streamResponseChunks) - try { - const stream2 = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); - let aggregated; - for await (const chunk of stream2) - if (aggregated === undefined) - aggregated = chunk; - else - aggregated = concat(aggregated, chunk); - if (aggregated === undefined) - throw new Error("Received empty response from chat model call."); - output = { - generations: [[aggregated]], - llmOutput: {} - }; - await runManagers?.[0].handleLLMEnd(output); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - try { - output = await this._generate(prompts, parsedOptions, runManagers?.[0]); - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - const flattenedOutputs = this._flattenLLMResult(output); - await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); - } - const runIds = runManagers?.map((manager) => manager.runId) || undefined; - Object.defineProperty(output, RUN_KEY, { - value: runIds ? { runIds } : undefined, - configurable: true - }); - return output; - } - async _generateCached({ prompts, cache: cache2, llmStringKey, parsedOptions, handledOptions, runId }) { - const invocationParams = this.invocationParams(parsedOptions); - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { - verbose: this.verbose, - tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) - }); - const extra = { - options: parsedOptions, - invocation_params: invocationParams, - batch_size: prompts.length - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, undefined, extra, undefined, undefined, handledOptions?.runName); - const missingPromptIndices = []; - const cachedResults = (await Promise.allSettled(prompts.map(async (prompt, index2) => { - const result = await cache2.lookup(prompt, llmStringKey); - if (result == null) - missingPromptIndices.push(index2); - return result; - }))).map((result, index2) => ({ - result, - runManager: runManagers?.[index2] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result2) => { - result2.generationInfo = { - ...result2.generationInfo, - tokenUsage: {} - }; - return result2; - }); - if (result.length) - await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, undefined, undefined, undefined, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, - configurable: true - }); - return output; - } - async generate(prompts, options, callbacks) { - if (!Array.isArray(prompts)) - throw new Error("Argument 'prompts' is expected to be a string[]"); - let parsedOptions; - if (Array.isArray(options)) - parsedOptions = { stop: options }; - else - parsedOptions = options; - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) - return this._generateUncached(prompts, callOptions, runnableConfig); - const { cache: cache2 } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - prompts, - cache: cache2, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig, - runId: runnableConfig.runId - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== undefined ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : undefined); - await Promise.all(results.generations.map(async (generation, index2) => { - const promptIndex = missingPromptIndices[index2]; - generations[promptIndex] = generation; - return cache2.update(prompts[promptIndex], llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; - } - _identifyingParams() { - return {}; - } - _modelType() { - return "base_llm"; - } - }; - LLM = class extends BaseLLM { - async _generate(prompts, options, runManager) { - return { generations: await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { - ...options, - promptIndex - }, runManager).then((text) => [{ text }]))) }; - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} +var init_promise = __esm(() => { + init_parseDef(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js +function parseSetDef(def, refs) { + const schema = { + type: "array", + uniqueItems: true, + items: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }) }; + if (def.minSize) + setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + if (def.maxSize) + setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + return schema; +} +var init_set = __esm(() => { + init_errorMessages(); + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/language_models/profile.js -var profile_exports; -var init_profile = __esm(() => { - init_runtime2(); - profile_exports = /* @__PURE__ */ __exportAll({}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + else + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []) + }; +} +var init_tuple = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/memory.js -function getPromptInputKey(inputs, memoryVariables) { - const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); - if (promptInputKeys.length !== 1) - throw new Error(`One input key expected, but got ${promptInputKeys.length}`); - return promptInputKeys[0]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js +function parseUndefinedDef(refs) { + return { not: parseAnyDef(refs) }; } -var memory_exports, BaseMemory = class { -}, getValue = (values, key) => { - if (key !== undefined) - return values[key]; - const keys = Object.keys(values); - if (keys.length === 1) - return values[keys[0]]; -}, getInputValue = (inputValues, inputKey) => { - const value = getValue(inputValues, inputKey); - if (!value) - throw new Error(`input values have ${Object.keys(inputValues).length} keys, you must specify an input key or pass only 1 key as input`); - return value; -}, getOutputValue = (outputValues, outputKey) => { - const value = getValue(outputValues, outputKey); - if (!value && value !== "") - throw new Error(`output values have ${Object.keys(outputValues).length} keys, you must specify an output key or pass only 1 key as output`); - return value; -}; -var init_memory = __esm(() => { - init_runtime2(); - memory_exports = /* @__PURE__ */ __exportAll({ - BaseMemory: () => BaseMemory, - getInputValue: () => getInputValue, - getOutputValue: () => getOutputValue, - getPromptInputKey: () => getPromptInputKey - }); +var init_undefined = __esm(() => { + init_any(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js -var OutputFunctionsParser, JsonOutputFunctionsParser, JsonKeyOutputFunctionsParser; -var init_json_output_functions_parsers = __esm(() => { - init_json(); - init_duplex(); - init_base6(); - init_transform(); - init_json_patch(); - init_json2(); - OutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "OutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - argsOnly = true; - constructor(config2) { - super(); - this.argsOnly = config2?.argsOnly ?? this.argsOnly; - } - async parseResult(generations) { - if ("message" in generations[0]) { - const functionCall = generations[0].message.additional_kwargs.function_call; - if (!functionCall) - throw new Error(`No function_call in message ${JSON.stringify(generations)}`); - if (!functionCall.arguments) - throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); - if (this.argsOnly) - return functionCall.arguments; - return JSON.stringify(functionCall); - } else - throw new Error(`No message in generations ${JSON.stringify(generations)}`); - } - }; - JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser; - argsOnly = true; - constructor(config2) { - super(config2); - this.argsOnly = config2?.argsOnly ?? this.argsOnly; - this.outputParser = new OutputFunctionsParser(config2); - } - _diff(prev, next) { - if (!next) - return; - return compare(prev ?? {}, next); - } - async parsePartialResult(generations) { - const generation = generations[0]; - if (!generation.message) - return; - const { message } = generation; - const functionCall = message.additional_kwargs.function_call; - if (!functionCall) - return; - if (this.argsOnly) - return parsePartialJson(functionCall.arguments); - return { - ...functionCall, - arguments: parsePartialJson(functionCall.arguments) - }; - } - async parseResult(generations) { - const result = await this.outputParser.parseResult(generations); - if (!result) - throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); - return this.parse(result); - } - async parse(text) { - const parsedResult = JSON.parse(text); - if (this.argsOnly) - return parsedResult; - parsedResult.arguments = JSON.parse(parsedResult.arguments); - return parsedResult; - } - getFormatInstructions() { - return ""; - } - }; - JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "JsonKeyOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser = new JsonOutputFunctionsParser; - attrName; - get lc_aliases() { - return { attrName: "key_name" }; - } - constructor(fields) { - super(fields); - this.attrName = fields.attrName; - } - async parseResult(generations) { - return (await this.outputParser.parseResult(generations))[this.attrName]; - } - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} +var init_unknown = __esm(() => { + init_any(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js -var openai_functions_exports; -var init_openai_functions = __esm(() => { - init_runtime2(); - init_json_output_functions_parsers(); - openai_functions_exports = /* @__PURE__ */ __exportAll({ - JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, - JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, - OutputFunctionsParser: () => OutputFunctionsParser - }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js +var parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +var init_readonly = __esm(() => { + init_parseDef(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js -var openai_tools_exports; -var init_openai_tools = __esm(() => { - init_runtime2(); - init_json_output_tools_parsers(); - openai_tools_exports = /* @__PURE__ */ __exportAll({ - JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, - JsonOutputToolsParser: () => JsonOutputToolsParser, - convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, - makeInvalidToolCall: () => makeInvalidToolCall, - parseToolCall: () => parseToolCall - }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js +var selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind2.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind2.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind2.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind2.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind2.ZodUndefined: + return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind2.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind2.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind2.ZodUnion: + case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind2.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind2.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind2.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind2.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind2.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind2.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind2.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind2.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind2.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind2.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind2.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind2.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind2.ZodNaN: + case ZodFirstPartyTypeKind2.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind2.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind2.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind2.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind2.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind2.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind2.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind2.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind2.ZodFunction: + case ZodFirstPartyTypeKind2.ZodVoid: + case ZodFirstPartyTypeKind2.ZodSymbol: + return; + default: + return ((_) => { + return; + })(typeName); + } +}; +var init_selectParser = __esm(() => { + init_any(); + init_array(); + init_bigint(); + init_boolean(); + init_branded(); + init_catch(); + init_date(); + init_default(); + init_effects(); + init_enum(); + init_intersection(); + init_literal(); + init_string(); + init_record(); + init_map(); + init_nativeEnum(); + init_never(); + init_null(); + init_union(); + init_nullable(); + init_number(); + init_object(); + init_optional(); + init_pipeline(); + init_promise(); + init_set(); + init_tuple(); + init_undefined(); + init_unknown(); + init_readonly(); + init_v3(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/base.js -var BasePromptTemplate; -var init_base10 = __esm(() => { - init_base4(); - BasePromptTemplate = class extends Runnable { - lc_serializable = true; - lc_namespace = [ - "langchain_core", - "prompts", - this._getPromptType() - ]; - get lc_attributes() { - return { partialVariables: undefined }; - } - inputVariables; - outputParser; - partialVariables; - metadata; - tags; - constructor(input) { - super(input); - const { inputVariables } = input; - if (inputVariables.includes("stop")) - throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); - Object.assign(this, input); - } - async mergePartialAndUserVariables(userVariables) { - const partialVariables = this.partialVariables ?? {}; - const partialValues = {}; - for (const [key, value] of Object.entries(partialVariables)) - if (typeof value === "string") - partialValues[key] = value; - else - partialValues[key] = await value(); - return { - ...partialValues, - ...userVariables - }; - } - async invoke(input, options) { - const metadata = { - ...this.metadata, - ...options?.metadata - }; - const tags = [...this.tags ?? [], ...options?.tags ?? []]; - return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { - ...options, - tags, - metadata, - runType: "prompt" - }); - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) + return overrideResult; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) + return seenSchema; + } + const newItem = { + def, + path: refs.currentPath, + jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) + addMeta(def, refs, jsonSchema); + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +var get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": + if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; + } +}, addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) + jsonSchema.markdownDescription = def.description; + } + return jsonSchema; +}; +var init_parseDef = __esm(() => { + init_Options(); + init_getRelativePath(); + init_any(); + init_selectParser(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/string.js -var BaseStringPromptTemplate; -var init_string3 = __esm(() => { - init_prompt_values(); - init_base10(); - BaseStringPromptTemplate = class extends BasePromptTemplate { - async formatPromptValue(values) { - return new StringPromptValue(await this.format(values)); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js +var zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ + ...acc, + [name2]: parseDef(schema2._def, { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name2 + ] + }, true) ?? parseAnyDef(refs) + }), {}) : undefined; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name; + const main = parseDef(schema._def, name === undefined ? refs : { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name + ] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined; + if (title !== undefined) + main.title = title; + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) + definitions = {}; + if (!definitions[refs.openAiAnyTypeName]) + definitions[refs.openAiAnyTypeName] = { + type: [ + "string", + "number", + "integer", + "boolean", + "array", + "null" + ], + items: { $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") } + }; + } + const combined = name === undefined ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main } }; + if (refs.target === "jsonSchema7") + combined.$schema = "http://json-schema.org/draft-07/schema#"; + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + if (refs.target === "openAi" && (("anyOf" in combined) || ("oneOf" in combined) || ("allOf" in combined) || ("type" in combined) && Array.isArray(combined.type))) + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + return combined; +}; +var init_zodToJsonSchema = __esm(() => { + init_Refs(); + init_any(); + init_parseDef(); }); -// ../../node_modules/.pnpm/mustache@4.2.0/node_modules/mustache/mustache.mjs -function isFunction(object2) { - return typeof object2 === "function"; -} -function typeStr(obj) { - return isArray(obj) ? "array" : typeof obj; -} -function escapeRegExp(string4) { - return string4.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -} -function hasProperty(obj, propName) { - return obj != null && typeof obj === "object" && propName in obj; -} -function primitiveHasOwnProperty(primitive, propName) { - return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); -} -function testRegExp(re, string4) { - return regExpTest.call(re, string4); -} -function isWhitespace(string4) { - return !testRegExp(nonSpaceRe, string4); -} -function escapeHtml(string4) { - return String(string4).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) { - return entityMap[s]; - }); -} -function parseTemplate(template, tags) { - if (!template) - return []; - var lineHasNonSpace = false; - var sections = []; - var tokens = []; - var spaces = []; - var hasTag = false; - var nonSpace = false; - var indentation = ""; - var tagIndex = 0; - function stripSpace() { - if (hasTag && !nonSpace) { - while (spaces.length) - delete tokens[spaces.pop()]; - } else { - spaces = []; - } - hasTag = false; - nonSpace = false; - } - var openingTagRe, closingTagRe, closingCurlyRe; - function compileTags(tagsToCompile) { - if (typeof tagsToCompile === "string") - tagsToCompile = tagsToCompile.split(spaceRe, 2); - if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) - throw new Error("Invalid tags: " + tagsToCompile); - openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); - closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); - closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js +var init_zod_to_json_schema = __esm(() => { + init_Options(); + init_Refs(); + init_errorMessages(); + init_getRelativePath(); + init_any(); + init_array(); + init_bigint(); + init_boolean(); + init_branded(); + init_catch(); + init_date(); + init_default(); + init_effects(); + init_enum(); + init_intersection(); + init_literal(); + init_string(); + init_record(); + init_map(); + init_nativeEnum(); + init_never(); + init_null(); + init_union(); + init_nullable(); + init_number(); + init_object(); + init_optional(); + init_pipeline(); + init_promise(); + init_set(); + init_tuple(); + init_undefined(); + init_unknown(); + init_readonly(); + init_selectParser(); + init_parseDef(); + init_zodToJsonSchema(); +}); + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; } - compileTags(tags || mustache.tags); - var scanner = new Scanner(template); - var start, type, value, chr, token, openSection; - while (!scanner.eos()) { - start = scanner.pos; - value = scanner.scanUntil(openingTagRe); - if (value) { - for (var i = 0, valueLength = value.length;i < valueLength; ++i) { - chr = value.charAt(i); - if (isWhitespace(chr)) { - spaces.push(tokens.length); - indentation += chr; - } else { - nonSpace = true; - lineHasNonSpace = true; - indentation += " "; - } - tokens.push(["text", chr, start, start + 1]); - start += 1; - if (chr === ` -`) { - stripSpace(); - indentation = ""; - tagIndex = 0; - lineHasNonSpace = false; - } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0;i < length; i++) { + if (!deepCompareStrict(a[i], b[i])) { + return false; } } - if (!scanner.scan(openingTagRe)) - break; - hasTag = true; - type = scanner.scan(tagRe) || "name"; - scanner.scan(whiteRe); - if (type === "=") { - value = scanner.scanUntil(equalsRe); - scanner.scan(equalsRe); - scanner.scanUntil(closingTagRe); - } else if (type === "{") { - value = scanner.scanUntil(closingCurlyRe); - scanner.scan(curlyRe); - scanner.scanUntil(closingTagRe); - type = "&"; - } else { - value = scanner.scanUntil(closingTagRe); + return true; + } + if (typeofa === "object") { + if (!a || !b) { + return a === b; } - if (!scanner.scan(closingTagRe)) - throw new Error("Unclosed tag at " + scanner.pos); - if (type == ">") { - token = [type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace]; - } else { - token = [type, value, start, scanner.pos]; + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; } - tagIndex++; - tokens.push(token); - if (type === "#" || type === "^") { - sections.push(token); - } else if (type === "/") { - openSection = sections.pop(); - if (!openSection) - throw new Error('Unopened section "' + value + '" at ' + start); - if (openSection[1] !== value) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); - } else if (type === "name" || type === "{" || type === "&") { - nonSpace = true; - } else if (type === "=") { - compileTags(value); + for (const k of aKeys) { + if (!deepCompareStrict(a[k], b[k])) { + return false; + } } + return true; } - stripSpace(); - openSection = sections.pop(); - if (openSection) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); - return nestTokens(squashTokens(tokens)); + return a === b; } -function squashTokens(tokens) { - var squashedTokens = []; - var token, lastToken; - for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { - token = tokens[i]; - if (token) { - if (token[0] === "text" && lastToken && lastToken[0] === "text") { - lastToken[1] += token[1]; - lastToken[3] = token[3]; + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js +function encodePointer(p) { + return encodeURI(escapePointer(p)); +} +function escapePointer(p) { + return p.replace(/~/g, "~0").replace(/\//g, "~1"); +} + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js +function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = "") { + if (schema && typeof schema === "object" && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url2 = new URL(id, baseURI.href); + if (url2.hash.length > 1) { + lookup[url2.href] = schema; } else { - squashedTokens.push(token); - lastToken = token; + url2.hash = ""; + if (basePointer === "") { + baseURI = url2; + } else { + dereference(schema, lookup, baseURI); + } } } + } else if (schema !== true && schema !== false) { + return lookup; } - return squashedTokens; -} -function nestTokens(tokens) { - var nestedTokens = []; - var collector = nestedTokens; - var sections = []; - var token, section; - for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { - token = tokens[i]; - switch (token[0]) { - case "#": - case "^": - collector.push(token); - sections.push(token); - collector = token[4] = []; - break; - case "/": - section = sections.pop(); - section[5] = token[2]; - collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; - break; - default: - collector.push(token); - } - } - return nestedTokens; -} -function Scanner(string4) { - this.string = string4; - this.tail = string4; - this.pos = 0; -} -function Context2(view, parentContext) { - this.view = view; - this.cache = { ".": this.view }; - this.parent = parentContext; -} -function Writer() { - this.templateCache = { - _cache: {}, - set: function set2(key, value) { - this._cache[key] = value; - }, - get: function get(key) { - return this._cache[key]; - }, - clear: function clear() { - this._cache = {}; - } - }; -} -var objectToString3, isArray, regExpTest, nonSpaceRe, entityMap, whiteRe, spaceRe, equalsRe, curlyRe, tagRe, mustache, defaultWriter, mustache_default; -var init_mustache = __esm(() => { - /*! - * mustache.js - Logic-less {{mustache}} templates with JavaScript - * http://github.com/janl/mustache.js - */ - objectToString3 = Object.prototype.toString; - isArray = Array.isArray || function isArrayPolyfill(object2) { - return objectToString3.call(object2) === "[object Array]"; - }; - regExpTest = RegExp.prototype.test; - nonSpaceRe = /\S/; - entityMap = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "/": "/", - "`": "`", - "=": "=" - }; - whiteRe = /\s*/; - spaceRe = /\s+/; - equalsRe = /\s*=/; - curlyRe = /\s*\}/; - tagRe = /#|\^|\/|>|\{|&|=|!/; - Scanner.prototype.eos = function eos() { - return this.tail === ""; - }; - Scanner.prototype.scan = function scan(re) { - var match2 = this.tail.match(re); - if (!match2 || match2.index !== 0) - return ""; - var string4 = match2[0]; - this.tail = this.tail.substring(string4.length); - this.pos += string4.length; - return string4; - }; - Scanner.prototype.scanUntil = function scanUntil(re) { - var index2 = this.tail.search(re), match2; - switch (index2) { - case -1: - match2 = this.tail; - this.tail = ""; - break; - case 0: - match2 = ""; - break; - default: - match2 = this.tail.substring(0, index2); - this.tail = this.tail.substring(index2); + const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : ""); + if (lookup[schemaURI] !== undefined) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); + } + lookup[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup; + } + if (schema.__absolute_uri__ === undefined) { + Object.defineProperty(schema, "__absolute_uri__", { + enumerable: false, + value: schemaURI + }); + } + if (schema.$ref && schema.__absolute_ref__ === undefined) { + const url2 = new URL(schema.$ref, baseURI.href); + url2.hash = url2.hash; + Object.defineProperty(schema, "__absolute_ref__", { + enumerable: false, + value: url2.href + }); + } + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { + const url2 = new URL(schema.$recursiveRef, baseURI.href); + url2.hash = url2.hash; + Object.defineProperty(schema, "__absolute_recursive_ref__", { + enumerable: false, + value: url2.href + }); + } + if (schema.$anchor) { + const url2 = new URL("#" + schema.$anchor, baseURI.href); + lookup[url2.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; } - this.pos += match2.length; - return match2; - }; - Context2.prototype.push = function push(view) { - return new Context2(view, this); - }; - Context2.prototype.lookup = function lookup(name) { - var cache2 = this.cache; - var value; - if (cache2.hasOwnProperty(name)) { - value = cache2[name]; - } else { - var context = this, intermediateValue, names, index2, lookupHit = false; - while (context) { - if (name.indexOf(".") > 0) { - intermediateValue = context.view; - names = name.split("."); - index2 = 0; - while (intermediateValue != null && index2 < names.length) { - if (index2 === names.length - 1) - lookupHit = hasProperty(intermediateValue, names[index2]) || primitiveHasOwnProperty(intermediateValue, names[index2]); - intermediateValue = intermediateValue[names[index2++]]; - } - } else { - intermediateValue = context.view[name]; - lookupHit = hasProperty(context.view, name); - } - if (lookupHit) { - value = intermediateValue; - break; + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0;i < length; i++) { + dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); } - context = context.parent; } - cache2[name] = value; - } - if (isFunction(value)) - value = value.call(this.view); - return value; - }; - Writer.prototype.clearCache = function clearCache() { - if (typeof this.templateCache !== "undefined") { - this.templateCache.clear(); + } else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } + } else { + dereference(subSchema, lookup, baseURI, keyBase); } + } + return lookup; +} +var schemaArrayKeyword, schemaMapKeyword, ignoredKeyword, initialBaseURI; +var init_dereference = __esm(() => { + schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true }; - Writer.prototype.parse = function parse9(template, tags) { - var cache2 = this.templateCache; - var cacheKey2 = template + ":" + (tags || mustache.tags).join(":"); - var isCacheEnabled = typeof cache2 !== "undefined"; - var tokens = isCacheEnabled ? cache2.get(cacheKey2) : undefined; - if (tokens == undefined) { - tokens = parseTemplate(template, tags); - isCacheEnabled && cache2.set(cacheKey2, tokens); - } - return tokens; + schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true }; - Writer.prototype.render = function render(template, view, partials, config2) { - var tags = this.getConfigTags(config2); - var tokens = this.parse(template, tags); - var context = view instanceof Context2 ? view : new Context2(view, undefined); - return this.renderTokens(tokens, context, partials, template, config2); + ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true }; - Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config2) { - var buffer = ""; - var token, symbol2, value; - for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { - value = undefined; - token = tokens[i]; - symbol2 = token[0]; - if (symbol2 === "#") - value = this.renderSection(token, context, partials, originalTemplate, config2); - else if (symbol2 === "^") - value = this.renderInverted(token, context, partials, originalTemplate, config2); - else if (symbol2 === ">") - value = this.renderPartial(token, context, partials, config2); - else if (symbol2 === "&") - value = this.unescapedValue(token, context); - else if (symbol2 === "name") - value = this.escapedValue(token, context, config2); - else if (symbol2 === "text") - value = this.rawValue(token); - if (value !== undefined) - buffer += value; - } - return buffer; + initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); +}); + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js +function bind(r) { + return r.test.bind(r); +} +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function date6(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); +} +function time4(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); +} +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date6(dateTime[0]) && time4(true, dateTime[1]); +} +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, "u"); + return true; + } catch (e) { + return false; + } +} +var DATE, DAYS, TIME, HOSTNAME, URIREF, URITEMPLATE, URL_, UUID, JSON_POINTER, JSON_POINTER_URI_FRAGMENT, RELATIVE_JSON_POINTER, EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split("@"); + if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) + return false; + if (name[0] === "." || name.endsWith(".") || name.includes("..")) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}, IPV4, IPV6, DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)), format, DATE_TIME_SEPARATOR, NOT_URI_FRAGMENT, URI_PATTERN, Z_ANCHOR; +var init_format2 = __esm(() => { + DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; + HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; + URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; + URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; + UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; + JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; + JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; + RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; + IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; + format = { + date: date6, + time: time4.bind(undefined, false), + "date-time": date_time, + duration: DURATION, + uri, + "uri-reference": bind(URIREF), + "uri-template": bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex, + uuid: bind(UUID), + "json-pointer": bind(JSON_POINTER), + "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), + "relative-json-pointer": bind(RELATIVE_JSON_POINTER) }; - Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config2) { - var self2 = this; - var buffer = ""; - var value = context.lookup(token[1]); - function subRender(template) { - return self2.render(template, context, partials, config2); - } - if (!value) - return; - if (isArray(value)) { - for (var j = 0, valueLength = value.length;j < valueLength; ++j) { - buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config2); + DATE_TIME_SEPARATOR = /t|\s/i; + NOT_URI_FRAGMENT = /\/|:/; + URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + Z_ANCHOR = /[^\\]\\Z/; +}); + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/types.js +var OutputFormat; +var init_types2 = __esm(() => { + (function(OutputFormat2) { + OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag"; + OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic"; + OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed"; + })(OutputFormat || (OutputFormat = {})); +}); + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js +function ucs2length(s) { + let result = 0; + let length = s.length; + let index = 0; + let charCode; + while (index < length) { + result++; + charCode = s.charCodeAt(index++); + if (charCode >= 55296 && charCode <= 56319 && index < length) { + charCode = s.charCodeAt(index); + if ((charCode & 64512) == 56320) { + index++; } - } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") { - buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config2); - } else if (isFunction(value)) { - if (typeof originalTemplate !== "string") - throw new Error("Cannot use higher-order sections without the original template"); - value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); - if (value != null) - buffer += value; - } else { - buffer += this.renderTokens(token[4], context, partials, originalTemplate, config2); } - return buffer; - }; - Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config2) { - var value = context.lookup(token[1]); - if (!value || isArray(value) && value.length === 0) - return this.renderTokens(token[4], context, partials, originalTemplate, config2); - }; - Writer.prototype.indentPartial = function indentPartial(partial2, indentation, lineHasNonSpace) { - var filteredIndentation = indentation.replace(/[^ \t]/g, ""); - var partialByNl = partial2.split(` -`); - for (var i = 0;i < partialByNl.length; i++) { - if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { - partialByNl[i] = filteredIndentation + partialByNl[i]; + } + return result; +} + +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js +function validate5(instance, schema, draft = "2019-09", lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: "false", + keywordLocation: instanceLocation, + error: "False boolean schema." + } + ] + }; + } + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case "boolean": + case "number": + case "string": + instanceType = rawInstanceType; + break; + case "object": + if (instance === null) { + instanceType = "null"; + } else if (Array.isArray(instance)) { + instanceType = "array"; + } else { + instanceType = "object"; } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + } + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors5 = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; + } + if ($recursiveRef === "#") { + const refSchema = recursiveAnchor === null ? lookup[__absolute_recursive_ref__] : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate5(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "$recursiveRef", + keywordLocation, + error: "A subschema had errors." + }, ...result.errors); } - return partialByNl.join(` -`); - }; - Writer.prototype.renderPartial = function renderPartial(token, context, partials, config2) { - if (!partials) - return; - var tags = this.getConfigTags(config2); - var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; - if (value != null) { - var lineHasNonSpace = token[6]; - var tagIndex = token[5]; - var indentation = token[4]; - var indentedValue = value; - if (tagIndex == 0 && indentation) { - indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); + } + if ($ref !== undefined) { + const uri2 = __absolute_ref__ || $ref; + const refSchema = lookup[uri2]; + if (refSchema === undefined) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; } - var tokens = this.parse(indentedValue, tags); - return this.renderTokens(tokens, context, partials, indentedValue, config2); - } - }; - Writer.prototype.unescapedValue = function unescapedValue(token, context) { - var value = context.lookup(token[1]); - if (value != null) - return value; - }; - Writer.prototype.escapedValue = function escapedValue(token, context, config2) { - var escape = this.getConfigEscape(config2) || mustache.escape; - var value = context.lookup(token[1]); - if (value != null) - return typeof value === "number" && escape === mustache.escape ? String(value) : escape(value); - }; - Writer.prototype.rawValue = function rawValue(token) { - return token[1]; - }; - Writer.prototype.getConfigTags = function getConfigTags(config2) { - if (isArray(config2)) { - return config2; - } else if (config2 && typeof config2 === "object") { - return config2.tags; - } else { - return; + message += ` +Known schemas: +- ${Object.keys(lookup).join(` +- `)}`; + throw new Error(message); } - }; - Writer.prototype.getConfigEscape = function getConfigEscape(config2) { - if (config2 && typeof config2 === "object" && !isArray(config2)) { - return config2.escape; - } else { - return; + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate5(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "$ref", + keywordLocation, + error: "A subschema had errors." + }, ...result.errors); } - }; - mustache = { - name: "mustache.js", - version: "4.2.0", - tags: ["{{", "}}"], - clearCache: undefined, - escape: undefined, - parse: undefined, - render: undefined, - Scanner: undefined, - Context: undefined, - Writer: undefined, - set templateCache(cache2) { - defaultWriter.templateCache = cache2; - }, - get templateCache() { - return defaultWriter.templateCache; + if (draft === "4" || draft === "7") { + return { valid: errors5.length === 0, errors: errors5 }; } - }; - defaultWriter = new Writer; - mustache.clearCache = function clearCache2() { - return defaultWriter.clearCache(); - }; - mustache.parse = function parse10(template, tags) { - return defaultWriter.parse(template, tags); - }; - mustache.render = function render2(template, view, partials, config2) { - if (typeof template !== "string") { - throw new TypeError('Invalid template! Template should be a "string" ' + 'but "' + typeStr(template) + '" was given as the first ' + "argument for mustache#render(template, view, partials)"); + } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0;i < length; i++) { + if (instanceType === $type[i] || $type[i] === "integer" && instanceType === "number" && instance % 1 === 0 && instance === instance) { + valid = true; + break; + } } - return defaultWriter.render(template, view, partials, config2); - }; - mustache.escape = escapeHtml; - mustache.Scanner = Scanner; - mustache.Context = Context2; - mustache.Writer = Writer; - mustache_default = mustache; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/template.js -function configureMustache() { - mustache_default.escape = (text) => text; -} -var parseFString = (template) => { - const chars = template.split(""); - const nodes = []; - const nextBracket = (bracket, start) => { - for (let i2 = start;i2 < chars.length; i2 += 1) - if (bracket.includes(chars[i2])) - return i2; - return -1; - }; - let i = 0; - while (i < chars.length) - if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { - nodes.push({ - type: "literal", - text: "{" - }); - i += 2; - } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { - nodes.push({ - type: "literal", - text: "}" - }); - i += 2; - } else if (chars[i] === "{") { - const j = nextBracket("}", i); - if (j < 0) - throw new Error("Unclosed '{' in template."); - nodes.push({ - type: "variable", - name: chars.slice(i + 1, j).join("") - }); - i = j + 1; - } else if (chars[i] === "}") - throw new Error("Single '}' in template."); - else { - const next = nextBracket("{}", i); - const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); - nodes.push({ - type: "literal", - text + if (!valid) { + errors5.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` }); - i = next < 0 ? chars.length : next; } - return nodes; -}, mustacheTemplateToNodes = (template, context = []) => { - const nodes = []; - for (const temp of template) - if (temp[0] === "name") { - const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; - nodes.push({ - type: "variable", - name - }); - } else if ([ - "#", - "&", - "^", - ">" - ].includes(temp[0])) { - nodes.push({ - type: "variable", - name: temp[1] + } else if ($type === "integer") { + if (instanceType !== "number" || instance % 1 || instance !== instance) { + errors5.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` }); - if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { - const newContext = [...context, temp[1]]; - const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); - nodes.push(...nestedNodes); + } + } else if ($type !== undefined && instanceType !== $type) { + errors5.push({ + instanceLocation, + keyword: "type", + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + if ($const !== undefined) { + if (instanceType === "object" || instanceType === "array") { + if (!deepCompareStrict(instance, $const)) { + errors5.push({ + instanceLocation, + keyword: "const", + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); } - } else - nodes.push({ - type: "literal", - text: temp[1] + } else if (instance !== $const) { + errors5.push({ + instanceLocation, + keyword: "const", + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` }); - return nodes; -}, parseMustache = (template) => { - configureMustache(); - return mustacheTemplateToNodes(mustache_default.parse(template)); -}, interpolateFString = (template, values) => { - return parseFString(template).reduce((res, node) => { - if (node.type === "variable") { - if (node.name in values) - return res + (typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name])); - throw new Error(`(f-string) Missing value for input ${node.name}`); } - return res + node.text; - }, ""); -}, interpolateMustache = (template, values) => { - configureMustache(); - return mustache_default.render(template, values); -}, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate = (template, templateFormat, inputValues) => { - try { - return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); - } catch (e) { - throw addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); } -}, parseTemplate2 = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template), checkValidTemplate = (template, templateFormat, inputVariables) => { - if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) - throw new Error(`Invalid template format. Got \`${templateFormat}\`; - should be one of ${Object.keys(DEFAULT_FORMATTER_MAPPING)}`); - try { - const dummyInputs = Object.fromEntries(inputVariables.map((v) => [v, "foo"])); - if (Array.isArray(template)) - template.forEach((message) => { - if (message.type === "text" && "text" in message && typeof message.text === "string") - renderTemplate(message.text, templateFormat, dummyInputs); - else if (message.type === "image_url") { - if (typeof message.image_url === "string") - renderTemplate(message.image_url, templateFormat, dummyInputs); - else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { - const imageUrl = message.image_url.url; - renderTemplate(imageUrl, templateFormat, dummyInputs); - } - } else - throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); + if ($enum !== undefined) { + if (instanceType === "object" || instanceType === "array") { + if (!$enum.some((value) => deepCompareStrict(instance, value))) { + errors5.push({ + instanceLocation, + keyword: "enum", + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } else if (!$enum.some((value) => instance === value)) { + errors5.push({ + instanceLocation, + keyword: "enum", + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` }); - else - renderTemplate(template, templateFormat, dummyInputs); - } catch (e) { - throw new Error(`Invalid prompt schema: ${e.message}`); + } } -}; -var init_template = __esm(() => { - init_errors3(); - init_mustache(); - DEFAULT_FORMATTER_MAPPING = { - "f-string": interpolateFString, - mustache: interpolateMustache - }; - DEFAULT_PARSER_MAPPING = { - "f-string": parseFString, - mustache: parseMustache - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/prompt.js -var PromptTemplate; -var init_prompt = __esm(() => { - init_string3(); - init_template(); - PromptTemplate = class PromptTemplate2 extends BaseStringPromptTemplate { - static lc_name() { - return "PromptTemplate"; + if ($not !== undefined) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate5(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors5.push({ + instanceLocation, + keyword: "not", + keywordLocation, + error: 'Instance matched "not" schema.' + }); } - template; - templateFormat = "f-string"; - validateTemplate = true; - additionalContentFields; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === undefined) - this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - if (this.templateFormat === "mustache") - throw new Error("Mustache templates cannot be validated."); - let totalInputVariables = this.inputVariables; - if (this.partialVariables) - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.template, this.templateFormat, totalInputVariables); + } + let subEvaluateds = []; + if ($anyOf !== undefined) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors5.length; + let anyValid = false; + for (let i = 0;i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate5(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors5.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); } } - _getPromptType() { - return "prompt"; + if (anyValid) { + errors5.length = errorsLength; + } else { + errors5.splice(errorsLength, 0, { + instanceLocation, + keyword: "anyOf", + keywordLocation, + error: "Instance does not match any subschemas." + }); } - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - return renderTemplate(this.template, this.templateFormat, allValues); + } + if ($allOf !== undefined) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors5.length; + let allValid = true; + for (let i = 0;i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate5(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors5.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } } - static fromExamples(examples, suffix, inputVariables, exampleSeparator = ` - -`, prefix = "") { - return new PromptTemplate2({ - inputVariables, - template: [ - prefix, - ...examples, - suffix - ].join(exampleSeparator) + if (allValid) { + errors5.length = errorsLength; + } else { + errors5.splice(errorsLength, 0, { + instanceLocation, + keyword: "allOf", + keywordLocation, + error: `Instance does not match every subschema.` }); } - static fromTemplate(template, options) { - const { templateFormat = "f-string", ...rest } = options ?? {}; - const names = /* @__PURE__ */ new Set; - parseTemplate2(template, templateFormat).forEach((node) => { - if (node.type === "variable") - names.add(node.name); - }); - return new PromptTemplate2({ - inputVariables: [...names], - templateFormat, - template, - ...rest + } + if ($oneOf !== undefined) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors5.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate5(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors5.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + return result.valid; + }).length; + if (matches === 1) { + errors5.length = errorsLength; + } else { + errors5.splice(errorsLength, 0, { + instanceLocation, + keyword: "oneOf", + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` }); } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new PromptTemplate2({ - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }); + } + if (instanceType === "object" || instanceType === "array") { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== undefined) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate5(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== undefined) { + const thenResult = validate5(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors5.push({ + instanceLocation, + keyword: "if", + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } + } + } else if ($else !== undefined) { + const elseResult = validate5(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors5.push({ + instanceLocation, + keyword: "if", + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } } - serialize() { - if (this.outputParser !== undefined) - throw new Error("Cannot serialize a prompt template with an output parser"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - template: this.template, - template_format: this.templateFormat - }; + } + if (instanceType === "object") { + if ($required !== undefined) { + for (const key of $required) { + if (!(key in instance)) { + errors5.push({ + instanceLocation, + keyword: "required", + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } } - static async deserialize(data) { - if (!data.template) - throw new Error("Prompt template must have a template"); - return new PromptTemplate2({ - inputVariables: data.input_variables, - template: data.template, - templateFormat: data.template_format + const keys = Object.keys(instance); + if ($minProperties !== undefined && keys.length < $minProperties) { + errors5.push({ + instanceLocation, + keyword: "minProperties", + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/image.js -var ImagePromptTemplate; -var init_image = __esm(() => { - init_prompt_values(); - init_base10(); - init_template(); - ImagePromptTemplate = class ImagePromptTemplate2 extends BasePromptTemplate { - static lc_name() { - return "ImagePromptTemplate"; + if ($maxProperties !== undefined && keys.length > $maxProperties) { + errors5.push({ + instanceLocation, + keyword: "maxProperties", + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); } - lc_namespace = [ - "langchain_core", - "prompts", - "image" - ]; - template; - templateFormat = "f-string"; - validateTemplate = true; - additionalContentFields; - constructor(input) { - super(input); - this.template = input.template; - this.templateFormat = input.templateFormat ?? this.templateFormat; - this.validateTemplate = input.validateTemplate ?? this.validateTemplate; - this.additionalContentFields = input.additionalContentFields; - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate([{ - type: "image_url", - image_url: this.template - }], this.templateFormat, totalInputVariables); + if ($propertyNames !== undefined) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate5(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "propertyNames", + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } } } - _getPromptType() { - return "prompt"; + if ($dependentRequired !== undefined) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required3 = $dependentRequired[key]; + for (const dependantKey of required3) { + if (!(dependantKey in instance)) { + errors5.push({ + instanceLocation, + keyword: "dependentRequired", + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new ImagePromptTemplate2({ - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }); + if ($dependentSchemas !== undefined) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate5(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "dependentSchemas", + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } } - async format(values) { - const formatted = {}; - for (const [key, value] of Object.entries(this.template)) - if (typeof value === "string") - formatted[key] = renderTemplate(value, this.templateFormat, values); - else - formatted[key] = value; - const url2 = values.url || formatted.url; - const detail = values.detail || formatted.detail; - if (!url2) - throw new Error("Must provide either an image URL."); - if (typeof url2 !== "string") - throw new Error("url must be a string."); - const output = { url: url2 }; - if (detail) - output.detail = detail; - return output; + if ($dependencies !== undefined) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors5.push({ + instanceLocation, + keyword: "dependencies", + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } else { + const result = validate5(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "dependencies", + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } } - async formatPromptValue(values) { - return new ImagePromptValue(await this.format(values)); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/dict.js -function _getInputVariables(template, templateFormat) { - const inputVariables = []; - for (const v of Object.values(template)) - if (typeof v === "string") - parseTemplate2(v, templateFormat).forEach((t) => { - if (t.type === "variable") - inputVariables.push(t.name); - }); - else if (Array.isArray(v)) { - for (const x of v) - if (typeof x === "string") - parseTemplate2(x, templateFormat).forEach((t) => { - if (t.type === "variable") - inputVariables.push(t.name); - }); - else if (typeof x === "object") - inputVariables.push(..._getInputVariables(x, templateFormat)); - } else if (typeof v === "object" && v !== null) - inputVariables.push(..._getInputVariables(v, templateFormat)); - return Array.from(new Set(inputVariables)); -} -function _insertInputVariables(template, inputs, templateFormat) { - const formatted = {}; - for (const [k, v] of Object.entries(template)) - if (typeof v === "string") - formatted[k] = renderTemplate(v, templateFormat, inputs); - else if (Array.isArray(v)) { - const formattedV = []; - for (const x of v) - if (typeof x === "string") - formattedV.push(renderTemplate(x, templateFormat, inputs)); - else if (typeof x === "object") - formattedV.push(_insertInputVariables(x, inputs, templateFormat)); - formatted[k] = formattedV; - } else if (typeof v === "object" && v !== null) - formatted[k] = _insertInputVariables(v, inputs, templateFormat); - else - formatted[k] = v; - return formatted; -} -var DictPromptTemplate; -var init_dict = __esm(() => { - init_base4(); - init_template(); - DictPromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "dict" - ]; - lc_serializable = true; - template; - templateFormat; - inputVariables; - static lc_name() { - return "DictPromptTemplate"; - } - constructor(fields) { - const templateFormat = fields.templateFormat ?? "f-string"; - const inputVariables = _getInputVariables(fields.template, templateFormat); - super({ - inputVariables, - ...fields - }); - this.template = fields.template; - this.templateFormat = templateFormat; - this.inputVariables = inputVariables; - } - async format(values) { - return _insertInputVariables(this.template, values, this.templateFormat); - } - async invoke(values) { - return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/chat.js -function isTextTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) - return false; - return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; -} -function isImageTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) - return false; - return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && ("url" in param.image_url) && typeof param.image_url.url === "string"); -} -function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { - return typeof baseMessagePromptTemplateLike.formatMessages === "function"; -} -function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { - if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) - return messagePromptTemplateLike; - if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { - const messageContent = messagePromptTemplateLike[1]; - if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") - return new MessagesPlaceholder({ - variableName: messageContent.slice(2, -2), - optional: true - }); - else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") - return new MessagesPlaceholder({ - variableName: messageContent.slice(1, -1), - optional: true - }); - throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); - } - const message = coerceMessageLikeToMessage(messagePromptTemplateLike); - let templateData; - if (typeof message.content === "string") - templateData = message.content; - else - templateData = message.content.map((item) => { - if ("text" in item) - return { - ...item, - text: item.text - }; - else if ("image_url" in item) - return { - ...item, - image_url: item.image_url - }; - else - return item; - }); - if (message._getType() === "human") - return HumanMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "ai") - return AIMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "system") - return SystemMessagePromptTemplate.fromTemplate(templateData, extra); - else if (ChatMessage.isInstance(message)) - return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); - else - throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); -} -function isMessagesPlaceholder(x) { - return x.constructor.lc_name() === "MessagesPlaceholder"; -} -var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; -var init_chat2 = __esm(() => { - init_errors3(); - init_base(); - init_ai(); - init_chat(); - init_human(); - init_system(); - init_utils3(); - init_base4(); - init_messages(); - init_prompt_values(); - init_base10(); - init_string3(); - init_template(); - init_prompt(); - init_image(); - init_dict(); - BaseMessagePromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - async invoke(input, options) { - return this._callWithConfig((input2) => this.formatMessages(input2), input, { - ...options, - runType: "prompt" - }); - } - }; - MessagesPlaceholder = class extends BaseMessagePromptTemplate { - static lc_name() { - return "MessagesPlaceholder"; - } - variableName; - optional; - constructor(fields) { - if (typeof fields === "string") - fields = { variableName: fields }; - super(fields); - this.variableName = fields.variableName; - this.optional = fields.optional ?? false; + const thisEvaluated = Object.create(null); + let stop = false; + if ($properties !== undefined) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate5(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } else { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "properties", + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - get inputVariables() { - return [this.variableName]; + if (!stop && $patternProperties !== undefined) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex2 = new RegExp(pattern, "u"); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex2.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate5(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } else { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "patternProperties", + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); + } + } + } } - async formatMessages(values) { - const input = values[this.variableName]; - if (this.optional && !input) - return []; - else if (!input) { - const error51 = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); - error51.name = "InputFormatError"; - throw error51; + if (!stop && $additionalProperties !== undefined) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate5(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } else { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "additionalProperties", + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); + } } - let formattedMessages; - try { - if (Array.isArray(input)) - formattedMessages = input.map(coerceMessageLikeToMessage); - else - formattedMessages = [coerceMessageLikeToMessage(input)]; - } catch (e) { - const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); - const error51 = new Error([ - `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, - `Received value: ${readableInput}`, - `Additional message: ${e.message}` - ].join(` - -`)); - error51.name = "InputFormatError"; - error51.lc_error_code = e.lc_error_code; - throw error51; + } else if (!stop && $unevaluatedProperties !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate5(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } else { + errors5.push({ + instanceLocation, + keyword: "unevaluatedProperties", + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } } - return formattedMessages; - } - }; - BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { - prompt; - constructor(fields) { - if (!("prompt" in fields)) - fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - } - get inputVariables() { - return this.prompt.inputVariables; - } - async formatMessages(values) { - return [await this.format(values)]; - } - }; - BaseChatPromptTemplate = class extends BasePromptTemplate { - constructor(input) { - super(input); - } - async format(values) { - return (await this.formatPromptValue(values)).toString(); - } - async formatPromptValue(values) { - return new ChatPromptValue(await this.formatMessages(values)); - } - }; - ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { - static lc_name() { - return "ChatMessagePromptTemplate"; - } - role; - constructor(fields, role) { - if (!("prompt" in fields)) - fields = { - prompt: fields, - role - }; - super(fields); - this.role = fields.role; - } - async format(values) { - return new ChatMessage(await this.prompt.format(values), this.role); - } - static fromTemplate(template, role, options) { - return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); - } - }; - _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - inputVariables = []; - additionalOptions = {}; - prompt; - messageClass; - static _messageClass() { - throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); } - chatMessageClass; - constructor(fields, additionalOptions) { - if (!("prompt" in fields)) - fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - if (Array.isArray(this.prompt)) { - let inputVariables = []; - this.prompt.forEach((prompt) => { - if ("inputVariables" in prompt) - inputVariables = inputVariables.concat(prompt.inputVariables); - }); - this.inputVariables = inputVariables; - } else - this.inputVariables = this.prompt.inputVariables; - this.additionalOptions = additionalOptions ?? this.additionalOptions; + } else if (instanceType === "array") { + if ($maxItems !== undefined && instance.length > $maxItems) { + errors5.push({ + instanceLocation, + keyword: "maxItems", + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); } - createMessage(content) { - const constructor = this.constructor; - if (constructor._messageClass()) - return new (constructor._messageClass())({ content }); - else if (constructor.chatMessageClass) { - const MsgClass = constructor.chatMessageClass(); - return new MsgClass({ - content, - role: this.getRoleFromMessageClass(MsgClass.lc_name()) - }); - } else - throw new Error("No message class defined"); + if ($minItems !== undefined && instance.length < $minItems) { + errors5.push({ + instanceLocation, + keyword: "minItems", + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); } - getRoleFromMessageClass(name) { - switch (name) { - case "HumanMessage": - return "human"; - case "AIMessage": - return "ai"; - case "SystemMessage": - return "system"; - case "ChatMessage": - return "chat"; - default: - throw new Error("Invalid message class name"); + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== undefined) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (;i < length2; i++) { + const result = validate5(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "prefixItems", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } } } - static fromTemplate(template, additionalOptions) { - if (typeof template === "string") - return new this(PromptTemplate.fromTemplate(template, additionalOptions)); - const prompt = []; - for (const item of template) - if (typeof item === "string") - prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); - else if (item === null) {} else if (isTextTemplateParam(item)) { - let text = ""; - if (typeof item.text === "string") - text = item.text ?? ""; - const options = { - ...additionalOptions, - additionalContentFields: item - }; - prompt.push(PromptTemplate.fromTemplate(text, options)); - } else if (isImageTemplateParam(item)) { - let imgTemplate = item.image_url ?? ""; - let imgTemplateObject; - let inputVariables = []; - if (typeof imgTemplate === "string") { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") - parsedTemplate = parseMustache(imgTemplate); - else - parsedTemplate = parseFString(imgTemplate); - const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); - if ((variables?.length ?? 0) > 0) { - if (variables.length > 1) - throw new Error(`Only one format variable allowed per image template. -Got: ${variables} -From: ${imgTemplate}`); - inputVariables = [variables[0]]; - } else - inputVariables = []; - imgTemplate = { url: imgTemplate }; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else if (typeof imgTemplate === "object") { - if ("url" in imgTemplate) { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") - parsedTemplate = parseMustache(imgTemplate.url); - else - parsedTemplate = parseFString(imgTemplate.url); - inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); - } else - inputVariables = []; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else - throw new Error("Invalid image template"); - prompt.push(imgTemplateObject); - } else if (typeof item === "object") - prompt.push(new DictPromptTemplate({ - template: item, - templateFormat: additionalOptions?.templateFormat - })); - return new this({ - prompt, - additionalOptions - }); - } - async format(input) { - if (this.prompt instanceof BaseStringPromptTemplate) { - const text = await this.prompt.format(input); - return this.createMessage(text); + if ($items !== undefined) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (;i < length2; i++) { + const result = validate5(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "items", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } else { - const content = []; - for (const prompt of this.prompt) { - let inputs = {}; - if (!("inputVariables" in prompt)) - throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); - for (const item of prompt.inputVariables) { - if (!inputs) - inputs = { [item]: input[item] }; - inputs = { - ...inputs, - [item]: input[item] - }; + for (;i < length; i++) { + const result = validate5(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "items", + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; } - if (prompt instanceof BaseStringPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) - additionalContentFields = prompt.additionalContentFields; - if (formatted !== "") - content.push({ - ...additionalContentFields, - type: "text", - text: formatted - }); - } else if (prompt instanceof ImagePromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) - additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - type: "image_url", - image_url: formatted - }); - } else if (prompt instanceof DictPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) - additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - ...formatted - }); + } + } + if (!stop && $additionalItems !== undefined) { + const keywordLocation2 = `${schemaLocation}/additionalItems`; + for (;i < length; i++) { + const result = validate5(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation2); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors5.push({ + instanceLocation, + keyword: "additionalItems", + keywordLocation: keywordLocation2, + error: `Items did not match additional items schema.` + }, ...result.errors); } } - return this.createMessage(content); } } - async formatMessages(values) { - return [await this.format(values)]; - } - }; - HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return HumanMessage; - } - static lc_name() { - return "HumanMessagePromptTemplate"; - } - }; - AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return AIMessage; - } - static lc_name() { - return "AIMessagePromptTemplate"; - } - }; - SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return SystemMessage; - } - static lc_name() { - return "SystemMessagePromptTemplate"; - } - }; - ChatPromptTemplate = class ChatPromptTemplate2 extends BaseChatPromptTemplate { - static lc_name() { - return "ChatPromptTemplate"; - } - get lc_aliases() { - return { promptMessages: "messages" }; - } - promptMessages; - validateTemplate = true; - templateFormat = "f-string"; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === undefined) - this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - const inputVariablesMessages = /* @__PURE__ */ new Set; - for (const promptMessage of this.promptMessages) { - if (promptMessage instanceof BaseMessage) - continue; - for (const inputVariable of promptMessage.inputVariables) - inputVariablesMessages.add(inputVariable); + if ($contains !== undefined) { + if (length === 0 && $minContains === undefined) { + errors5.push({ + instanceLocation, + keyword: "contains", + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } else if ($minContains !== undefined && length < $minContains) { + errors5.push({ + instanceLocation, + keyword: "minContains", + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors5.length; + let contained = 0; + for (let j = 0;j < length; j++) { + const result = validate5(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; + } else { + errors5.push(...result.errors); + } + } + if (contained >= ($minContains || 0)) { + errors5.length = errorsLength; + } + if ($minContains === undefined && $maxContains === undefined && contained === 0) { + errors5.splice(errorsLength, 0, { + instanceLocation, + keyword: "contains", + keywordLocation, + error: `Array does not contain item matching schema.` + }); + } else if ($minContains !== undefined && contained < $minContains) { + errors5.push({ + instanceLocation, + keyword: "minContains", + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); + } else if ($maxContains !== undefined && contained > $maxContains) { + errors5.push({ + instanceLocation, + keyword: "maxContains", + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); } - const totalInputVariables = this.inputVariables; - const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); - const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); - if (difference.size > 0) - throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); - const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); - if (otherDifference.size > 0) - throw new Error(`Input variables \`${[...otherDifference]}\` are used in prompt messages but not in the prompt template.`); } } - _getPromptType() { - return "chat"; - } - async _parseImagePrompts(message, inputValues) { - if (typeof message.content === "string") - return message; - message.content = await Promise.all(message.content.map(async (item) => { - if (item.type !== "image_url") - return item; - let imageUrl = ""; - if (typeof item.image_url === "string") - imageUrl = item.image_url; - else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") - imageUrl = item.image_url.url; - const formattedUrl = await PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }).format(inputValues); - if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) - item.image_url.url = formattedUrl; - else - item.image_url = formattedUrl; - return item; - })); - return message; - } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let resultMessages = []; - for (const promptMessage of this.promptMessages) - if (promptMessage instanceof BaseMessage) - resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); - else { - let inputValues; - if (this.templateFormat === "mustache") - inputValues = { ...allValues }; - else - inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { - if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) - throw addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); - acc[inputVariable] = allValues[inputVariable]; - return acc; - }, {}); - const message = await promptMessage.formatMessages(inputValues); - resultMessages = resultMessages.concat(message); + if (!stop && $unevaluatedItems !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i;i < length; i++) { + if (evaluated[i]) { + continue; } - return resultMessages; - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new ChatPromptTemplate2({ - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }); - } - static fromTemplate(template, options) { - const humanTemplate = new HumanMessagePromptTemplate({ prompt: PromptTemplate.fromTemplate(template, options) }); - return this.fromMessages([humanTemplate]); + const result = validate5(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors5.push({ + instanceLocation, + keyword: "unevaluatedItems", + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } } - static fromMessages(promptMessages, extra) { - const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate2 ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); - const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate2 ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); - const inputVariables = /* @__PURE__ */ new Set; - for (const promptMessage of flattenedMessages) { - if (promptMessage instanceof BaseMessage) - continue; - for (const inputVariable of promptMessage.inputVariables) { - if (inputVariable in flattenedPartialVariables) + if ($uniqueItems) { + for (let j = 0;j < length; j++) { + const a = instance[j]; + const ao = typeof a === "object" && a !== null; + for (let k = 0;k < length; k++) { + if (j === k) { continue; - inputVariables.add(inputVariable); + } + const b = instance[k]; + const bo = typeof b === "object" && b !== null; + if (a === b || ao && bo && deepCompareStrict(a, b)) { + errors5.push({ + instanceLocation, + keyword: "uniqueItems", + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; + } } } - return new this({ - ...extra, - inputVariables: [...inputVariables], - promptMessages: flattenedMessages, - partialVariables: flattenedPartialVariables, - templateFormat: extra?.templateFormat - }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/few_shot.js -var FewShotPromptTemplate, FewShotChatMessagePromptTemplate; -var init_few_shot = __esm(() => { - init_string3(); - init_template(); - init_prompt(); - init_chat2(); - FewShotPromptTemplate = class FewShotPromptTemplate2 extends BaseStringPromptTemplate { - lc_serializable = false; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = ` - -`; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - constructor(input) { - super(input); - Object.assign(this, input); - if (this.examples !== undefined && this.exampleSelector !== undefined) - throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === undefined && this.exampleSelector === undefined) - throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } else if (instanceType === "number") { + if (draft === "4") { + if ($minimum !== undefined && ($exclusiveMinimum === true && instance <= $minimum || instance < $minimum)) { + errors5.push({ + instanceLocation, + keyword: "minimum", + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? "or equal to " : ""} ${$minimum}.` + }); + } + if ($maximum !== undefined && ($exclusiveMaximum === true && instance >= $maximum || instance > $maximum)) { + errors5.push({ + instanceLocation, + keyword: "maximum", + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? "or equal to " : ""} ${$maximum}.` + }); + } + } else { + if ($minimum !== undefined && instance < $minimum) { + errors5.push({ + instanceLocation, + keyword: "minimum", + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== undefined && instance > $maximum) { + errors5.push({ + instanceLocation, + keyword: "maximum", + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { + errors5.push({ + instanceLocation, + keyword: "exclusiveMinimum", + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { + errors5.push({ + instanceLocation, + keyword: "exclusiveMaximum", + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); } } - _getPromptType() { - return "few_shot"; - } - static lc_name() { - return "FewShotPromptTemplate"; - } - async getExamples(inputVariables) { - if (this.examples !== undefined) - return this.examples; - if (this.exampleSelector !== undefined) - return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); + if ($multipleOf !== undefined) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 0.00000011920929 && Math.abs($multipleOf - remainder) >= 0.00000011920929) { + errors5.push({ + instanceLocation, + keyword: "multipleOf", + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new FewShotPromptTemplate2({ - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables + } else if (instanceType === "string") { + const length = $minLength === undefined && $maxLength === undefined ? 0 : ucs2length(instance); + if ($minLength !== undefined && length < $minLength) { + errors5.push({ + instanceLocation, + keyword: "minLength", + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` }); } - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); - return renderTemplate([ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator), this.templateFormat, allValues); + if ($maxLength !== undefined && length > $maxLength) { + errors5.push({ + instanceLocation, + keyword: "maxLength", + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); } - serialize() { - if (this.exampleSelector || !this.examples) - throw new Error("Serializing an example selector is not currently supported"); - if (this.outputParser !== undefined) - throw new Error("Serializing an output parser is not currently supported"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - example_prompt: this.examplePrompt.serialize(), - example_separator: this.exampleSeparator, - suffix: this.suffix, - prefix: this.prefix, - template_format: this.templateFormat, - examples: this.examples - }; + if ($pattern !== undefined && !new RegExp($pattern, "u").test(instance)) { + errors5.push({ + instanceLocation, + keyword: "pattern", + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); } - static async deserialize(data) { - const { example_prompt } = data; - if (!example_prompt) - throw new Error("Missing example prompt"); - const examplePrompt = await PromptTemplate.deserialize(example_prompt); - let examples; - if (Array.isArray(data.examples)) - examples = data.examples; - else - throw new Error("Invalid examples format. Only list or string are supported."); - return new FewShotPromptTemplate2({ - inputVariables: data.input_variables, - examplePrompt, - examples, - exampleSeparator: data.example_separator, - prefix: data.prefix, - suffix: data.suffix, - templateFormat: data.template_format + if ($format !== undefined && format[$format] && !format[$format](instance)) { + errors5.push({ + instanceLocation, + keyword: "format", + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` }); } - }; - FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate2 extends BaseChatPromptTemplate { - lc_serializable = true; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = ` + } + return { valid: errors5.length === 0, errors: errors5 }; +} +var init_validate3 = __esm(() => { + init_dereference(); + init_format2(); +}); -`; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - _getPromptType() { - return "few_shot_chat"; - } - static lc_name() { - return "FewShotChatMessagePromptTemplate"; +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validator.js +class Validator { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = "2019-09", shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate5(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; } - constructor(fields) { - super(fields); - this.examples = fields.examples; - this.examplePrompt = fields.examplePrompt; - this.exampleSeparator = fields.exampleSeparator ?? ` + dereference(schema, this.lookup); + } +} +var init_validator = __esm(() => { + init_dereference(); + init_validate3(); +}); -`; - this.exampleSelector = fields.exampleSelector; - this.prefix = fields.prefix ?? ""; - this.suffix = fields.suffix ?? ""; - this.templateFormat = fields.templateFormat ?? "f-string"; - this.validateTemplate = fields.validateTemplate ?? true; - if (this.examples !== undefined && this.exampleSelector !== undefined) - throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === undefined && this.exampleSelector === undefined) - throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) - totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - async getExamples(inputVariables) { - if (this.examples !== undefined) - return this.examples; - if (this.exampleSelector !== undefined) - return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let examples = await this.getExamples(allValues); - examples = examples.map((example) => { - const result = {}; - this.examplePrompt.inputVariables.forEach((inputVariable) => { - result[inputVariable] = example[inputVariable]; - }); - return result; - }); - const messages = []; - for (const example of examples) { - const exampleMessages = await this.examplePrompt.formatMessages(example); - messages.push(...exampleMessages); - } - return messages; +// ../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/index.js +var init_esm = __esm(() => { + init_dereference(); + init_format2(); + init_types2(); + init_validate3(); + init_validator(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/json_schema.js +function toJsonSchema(schema, params) { + const canCache = !params && schema != null && typeof schema === "object"; + if (canCache) { + const cached3 = _jsonSchemaCache.get(schema); + if (cached3) + return cached3; + } + let result; + if (isStandardJsonSchema(schema) && !isZodSchemaV4(schema)) + result = schema["~standard"].jsonSchema.input({ target: "draft-07" }); + else if (isZodSchemaV4(schema)) { + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) + result = toJSONSchema2(interopZodObjectStrict(inputSchema, true), params); + else + result = toJSONSchema2(schema, params); + } else if (isZodSchemaV3(schema)) + result = zodToJsonSchema(schema); + else + result = schema; + if (canCache && result != null && typeof result === "object") + _jsonSchemaCache.set(schema, result); + return result; +} +function validatesOnlyStrings(schema) { + if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) + return false; + if ("type" in schema) { + if (typeof schema.type === "string") + return schema.type === "string"; + if (Array.isArray(schema.type)) + return schema.type.every((t) => t === "string"); + return false; + } + if ("enum" in schema) + return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); + if ("const" in schema) + return typeof schema.const === "string"; + if ("allOf" in schema && Array.isArray(schema.allOf)) + return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { + const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; + return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); + } + if ("not" in schema) + return false; + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) + return validatesOnlyStrings(resolved[ref]); + return false; + } + return false; +} +var json_schema_exports, _jsonSchemaCache; +var init_json_schema3 = __esm(() => { + init_runtime2(); + init_zod2(); + init_zodToJsonSchema(); + init_zod_to_json_schema(); + init_standard_schema(); + init_core4(); + init_esm(); + json_schema_exports = /* @__PURE__ */ __exportAll({ + Validator: () => Validator, + deepCompareStrict: () => deepCompareStrict, + toJsonSchema: () => toJsonSchema, + validatesOnlyStrings: () => validatesOnlyStrings + }); + _jsonSchemaCache = /* @__PURE__ */ new WeakMap; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +function hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys2 = new Array(obj.length); + for (let k = 0;k < keys2.length; k++) + keys2[k] = "" + k; + return keys2; + } + if (Object.keys) + return Object.keys(obj); + let keys = []; + for (let i in obj) + if (hasOwnProperty(obj, i)) + keys.push(i); + return keys; +} +function _deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); + case "undefined": + return null; + default: + return obj; + } +} +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; } - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = (await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example)))).flat().map((message) => message.content); - return renderTemplate([ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator), this.templateFormat, allValues); + return false; + } + return true; +} +function escapePathComponent(path2) { + if (path2.indexOf("/") === -1 && path2.indexOf("~") === -1) + return path2; + return path2.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function unescapePathComponent(path2) { + return path2.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function hasUndefined(obj) { + if (obj === undefined) + return true; + if (obj) { + if (Array.isArray(obj)) { + for (let i2 = 0, len = obj.length;i2 < len; i2++) + if (hasUndefined(obj[i2])) + return true; + } else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0;i < objKeysLength; i++) + if (hasUndefined(obj[objKeys[i]])) + return true; } - async partial(values) { - const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new FewShotChatMessagePromptTemplate2({ - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables + } + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; + if (typeof value !== "undefined") + messageParts.push(`${key}: ${value}`); + } + return messageParts.join(` +`); +} +var _hasOwnProperty, PatchError; +var init_helpers = __esm(() => { + /*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */ + _hasOwnProperty = Object.prototype.hasOwnProperty; + PatchError = class extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { + name, + index, + operation, + tree + })); + this.name = name; + this.index = index; + this.operation = operation; + this.tree = tree; + Object.setPrototypeOf(this, new.target.prototype); + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree }); } }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/pipeline.js -var PipelinePromptTemplate; -var init_pipeline2 = __esm(() => { - init_base10(); - init_chat2(); - PipelinePromptTemplate = class PipelinePromptTemplate2 extends BasePromptTemplate { - static lc_name() { - return "PipelinePromptTemplate"; - } - pipelinePrompts; - finalPrompt; - constructor(input) { - super({ - ...input, - inputVariables: [] - }); - this.pipelinePrompts = input.pipelinePrompts; - this.finalPrompt = input.finalPrompt; - this.inputVariables = this.computeInputValues(); - } - computeInputValues() { - const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); - const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); - return [...new Set(inputValues)]; - } - static extractRequiredInputValues(allValues, requiredValueNames) { - return requiredValueNames.reduce((requiredValues, valueName) => { - requiredValues[valueName] = allValues[valueName]; - return requiredValues; - }, {}); - } - async formatPipelinePrompts(values) { - const allValues = await this.mergePartialAndUserVariables(values); - for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { - const pipelinePromptInputValues = PipelinePromptTemplate2.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); - if (pipelinePrompt instanceof ChatPromptTemplate) - allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); - else - allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +function getValueByPointer(document2, pointer2) { + if (pointer2 == "") + return document2; + var getOriginalDestination = { + op: "_get", + path: pointer2 + }; + applyOperation(document2, getOriginalDestination); + return getOriginalDestination.value; +} +function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) + if (typeof validateOperation == "function") + validateOperation(operation, 0, document2, operation.path); + else + validator2(operation, 0); + if (operation.path === "") { + let returnValue = { newDocument: document2 }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document2; + return returnValue; + } else if (operation.op === "move" || operation.op === "copy") { + returnValue.newDocument = getValueByPointer(document2, operation.from); + if (operation.op === "move") + returnValue.removed = document2; + return returnValue; + } else if (operation.op === "test") { + returnValue.test = _areEquals(document2, operation.value); + if (returnValue.test === false) + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); + returnValue.newDocument = document2; + return returnValue; + } else if (operation.op === "remove") { + returnValue.removed = document2; + returnValue.newDocument = null; + return returnValue; + } else if (operation.op === "_get") { + operation.value = document2; + return returnValue; + } else if (validateOperation) + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document2); + else + return returnValue; + } else { + if (!mutateDocument) + document2 = _deepClone(document2); + const keys = (operation.path || "").split("/"); + let obj = document2; + let t = 1; + let len = keys.length; + let existingPathFragment = undefined; + let key; + let validateFunction; + if (typeof validateOperation == "function") + validateFunction = validateOperation; + else + validateFunction = validator2; + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) + key = unescapePathComponent(key); + if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) + existingPathFragment = keys.slice(0, t).join("/"); + else if (t == len - 1) + existingPathFragment = operation.path; + if (existingPathFragment !== undefined) + validateFunction(operation, 0, document2, existingPathFragment); + } } - return PipelinePromptTemplate2.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); - } - async formatPromptValue(values) { - return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); + t++; + if (Array.isArray(obj)) { + if (key === "-") + key = obj.length; + else if (validateOperation && !isInteger(key)) + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document2); + else if (isInteger(key)) + key = ~~key; + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document2); + const returnValue = arrOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); + return returnValue; + } + } else if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); + return returnValue; + } + obj = obj[key]; + if (validateOperation && t < len && (!obj || typeof obj !== "object")) + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document2); } - async format(values) { - return this.finalPrompt.format(await this.formatPipelinePrompts(values)); + } +} +function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (!mutateDocument) + document2 = _deepClone(document2); + const results = new Array(patch.length); + for (let i = 0, length = patch.length;i < length; i++) { + results[i] = applyOperation(document2, patch[i], validateOperation, true, banPrototypeModifications, i); + document2 = results[i].newDocument; + } + results.newDocument = document2; + return results; +} +function applyReducer(document2, operation, index) { + const operationResult = applyOperation(document2, operation); + if (operationResult.test === false) + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document2); + return operationResult.newDocument; +} +function validator2(operation, index, document2, existingPathFragment) { + if (typeof operation !== "object" || operation === null || Array.isArray(operation)) + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document2); + else if (!objOps[operation.op]) + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document2); + else if (typeof operation.path !== "string") + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document2); + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document2); + else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document2); + else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === undefined) + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document2); + else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document2); + else if (document2) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document2); + } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { + if (operation.path !== existingPathFragment) + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document2); + } else if (operation.op === "move" || operation.op === "copy") { + var error90 = validate7([{ + op: "_get", + path: operation.from, + value: undefined + }], document2); + if (error90 && error90.name === "OPERATION_PATH_UNRESOLVABLE") + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document2); } - async partial(values) { - const promptDict = { ...this }; - promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); - promptDict.partialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new PipelinePromptTemplate2(promptDict); + } +} +function validate7(sequence, document2, externalValidator) { + try { + if (!Array.isArray(sequence)) + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + if (document2) + applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); + else { + externalValidator = externalValidator || validator2; + for (var i = 0;i < sequence.length; i++) + externalValidator(sequence[i], i, document2, undefined); } - serialize() { - throw new Error("Not implemented."); + } catch (e) { + if (e instanceof JsonPatchError) + return e; + else + throw e; + } +} +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length;i-- !== 0; ) + if (!_areEquals(a[i], b[i])) + return false; + return true; } - _getPromptType() { - return "pipeline"; + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length;i-- !== 0; ) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length;i-- !== 0; ) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/structured.js -function isWithStructuredOutput(x) { - return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; -} -function isRunnableBinding(x) { - return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; + return true; + } + return a !== a && b !== b; } -var StructuredPrompt; -var init_structured2 = __esm(() => { - init_base4(); - init_chat2(); - StructuredPrompt = class StructuredPrompt2 extends ChatPromptTemplate { - schema; - method; - lc_namespace = [ - "langchain_core", - "prompts", - "structured" - ]; - get lc_aliases() { +var core_exports, JsonPatchError, deepClone, objOps, arrOps; +var init_core5 = __esm(() => { + init_runtime2(); + init_helpers(); + core_exports = /* @__PURE__ */ __exportAll({ + JsonPatchError: () => JsonPatchError, + _areEquals: () => _areEquals, + applyOperation: () => applyOperation, + applyPatch: () => applyPatch, + applyReducer: () => applyReducer, + deepClone: () => deepClone, + getValueByPointer: () => getValueByPointer, + validate: () => validate7, + validator: () => validator2 + }); + JsonPatchError = PatchError; + deepClone = _deepClone; + objOps = { + add: function(obj, key, document2) { + if (key === "__proto__" || key === "constructor") + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + obj[key] = this.value; + return { newDocument: document2 }; + }, + remove: function(obj, key, document2) { + if (key === "__proto__" || key === "constructor") + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + var removed = obj[key]; + delete obj[key]; return { - ...super.lc_aliases, - schema: "schema_" + newDocument: document2, + removed }; - } - constructor(input) { - super(input); - this.schema = input.schema; - this.method = input.method; - } - pipe(coerceable) { - if (isWithStructuredOutput(coerceable)) - return super.pipe(coerceable.withStructuredOutput(this.schema)); - if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) - return super.pipe(new RunnableBinding({ - bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), - kwargs: coerceable.kwargs ?? {}, - config: coerceable.config, - configFactories: coerceable.configFactories - })); - throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); - } - static fromMessagesAndSchema(promptMessages, schema, method) { - return StructuredPrompt2.fromMessages(promptMessages, { - schema, - method + }, + replace: function(obj, key, document2) { + if (key === "__proto__" || key === "constructor") + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons"); + var removed = obj[key]; + obj[key] = this.value; + return { + newDocument: document2, + removed + }; + }, + move: function(obj, key, document2) { + let removed = getValueByPointer(document2, this.path); + if (removed) + removed = _deepClone(removed); + const originalValue = applyOperation(document2, { + op: "remove", + path: this.from + }).removed; + applyOperation(document2, { + op: "add", + path: this.path, + value: originalValue + }); + return { + newDocument: document2, + removed + }; + }, + copy: function(obj, key, document2) { + const valueToCopy = getValueByPointer(document2, this.from); + applyOperation(document2, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy) }); + return { newDocument: document2 }; + }, + test: function(obj, key, document2) { + return { + newDocument: document2, + test: _areEquals(obj[key], this.value) + }; + }, + _get: function(obj, key, document2) { + this.value = obj[key]; + return { newDocument: document2 }; } }; + arrOps = { + add: function(arr2, i, document2) { + if (isInteger(i)) + arr2.splice(i, 0, this.value); + else + arr2[i] = this.value; + return { + newDocument: document2, + index: i + }; + }, + remove: function(arr2, i, document2) { + return { + newDocument: document2, + removed: arr2.splice(i, 1)[0] + }; + }, + replace: function(arr2, i, document2) { + var removed = arr2[i]; + arr2[i] = this.value; + return { + newDocument: document2, + removed + }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get + }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/prompts/index.js -var prompts_exports; -var init_prompts2 = __esm(() => { - init_runtime2(); - init_base10(); - init_string3(); - init_template(); - init_prompt(); - init_image(); - init_dict(); - init_chat2(); - init_few_shot(); - init_pipeline2(); - init_structured2(); - prompts_exports = /* @__PURE__ */ __exportAll({ - AIMessagePromptTemplate: () => AIMessagePromptTemplate, - BaseChatPromptTemplate: () => BaseChatPromptTemplate, - BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, - BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, - BasePromptTemplate: () => BasePromptTemplate, - BaseStringPromptTemplate: () => BaseStringPromptTemplate, - ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, - ChatPromptTemplate: () => ChatPromptTemplate, - DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, - DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, - DictPromptTemplate: () => DictPromptTemplate, - FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, - FewShotPromptTemplate: () => FewShotPromptTemplate, - HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, - ImagePromptTemplate: () => ImagePromptTemplate, - MessagesPlaceholder: () => MessagesPlaceholder, - PipelinePromptTemplate: () => PipelinePromptTemplate, - PromptTemplate: () => PromptTemplate, - StructuredPrompt: () => StructuredPrompt, - SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, - checkValidTemplate: () => checkValidTemplate, - interpolateFString: () => interpolateFString, - interpolateMustache: () => interpolateMustache, - parseFString: () => parseFString, - parseMustache: () => parseMustache, - parseTemplate: () => parseTemplate2, - renderTemplate: () => renderTemplate - }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +function _generate(mirror, obj, patches, path2, invertible) { + if (obj === mirror) + return; + if (typeof obj.toJSON === "function") + obj = obj.toJSON(); + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var deleted = false; + for (var t = oldKeys.length - 1;t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) + _generate(oldVal, newVal, patches, path2 + "/" + escapePathComponent(key), invertible); + else if (oldVal !== newVal) { + if (invertible) + patches.push({ + op: "test", + path: path2 + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + patches.push({ + op: "replace", + path: path2 + "/" + escapePathComponent(key), + value: _deepClone(newVal) + }); + } + } else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) + patches.push({ + op: "test", + path: path2 + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + patches.push({ + op: "remove", + path: path2 + "/" + escapePathComponent(key) + }); + deleted = true; + } else { + if (invertible) + patches.push({ + op: "test", + path: path2, + value: mirror + }); + patches.push({ + op: "replace", + path: path2, + value: obj + }); + } + } + if (!deleted && newKeys.length == oldKeys.length) + return; + for (var t = 0;t < newKeys.length; t++) { + var key = newKeys[t]; + if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) + patches.push({ + op: "add", + path: path2 + "/" + escapePathComponent(key), + value: _deepClone(obj[key]) + }); + } +} +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} +var init_duplex = __esm(() => { + init_helpers(); + init_core5(); + /*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2013-2021 Joachim Wester + * MIT license + */ }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/retrievers/document_compressors/index.js -var document_compressors_exports, BaseDocumentCompressor = class { - static isBaseDocumentCompressor(x) { - return x?.compressDocuments !== undefined; - } -}; -var init_document_compressors = __esm(() => { - init_runtime2(); - document_compressors_exports = /* @__PURE__ */ __exportAll({ BaseDocumentCompressor: () => BaseDocumentCompressor }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/fast-json-patch/index.js +var init_fast_json_patch = __esm(() => { + init_helpers(); + init_core5(); + init_duplex(); + ({ ...core_exports }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/retrievers/index.js -var retrievers_exports, BaseRetriever; -var init_retrievers = __esm(() => { +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/log_stream.js +async function _getStandardizedInputs(run2, schemaFormat) { + if (schemaFormat === "original") + throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); + const { inputs } = run2; + if ([ + "retriever", + "llm", + "prompt" + ].includes(run2.run_type)) + return inputs; + if (Object.keys(inputs).length === 1 && inputs?.input === "") + return; + return inputs.input; +} +async function _getStandardizedOutputs(run2, schemaFormat) { + const { outputs } = run2; + if (schemaFormat === "original") + return outputs; + if ([ + "retriever", + "llm", + "prompt" + ].includes(run2.run_type)) + return outputs; + if (outputs !== undefined && Object.keys(outputs).length === 1 && outputs?.output !== undefined) + return outputs.output; + return outputs; +} +function isChatGenerationChunk(x) { + return x !== undefined && x.message !== undefined; +} +var log_stream_exports, RunLogPatch = class { + ops; + constructor(fields) { + this.ops = fields.ops ?? []; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch({}, ops); + return new RunLog({ + ops, + state: states[states.length - 1].newDocument + }); + } +}, RunLog, isLogStreamHandler = (handler) => handler.name === "log_stream_tracer", LogStreamCallbackHandler; +var init_log_stream = __esm(() => { init_runtime2(); - init_manager(); - init_config(); - init_base4(); - retrievers_exports = /* @__PURE__ */ __exportAll({ BaseRetriever: () => BaseRetriever }); - BaseRetriever = class extends Runnable { - callbacks; - tags; - metadata; - verbose; + init_ai(); + init_base3(); + init_core5(); + init_fast_json_patch(); + init_stream(); + log_stream_exports = /* @__PURE__ */ __exportAll({ + LogStreamCallbackHandler: () => LogStreamCallbackHandler, + RunLog: () => RunLog, + RunLogPatch: () => RunLogPatch, + isLogStreamHandler: () => isLogStreamHandler + }); + RunLog = class RunLog2 extends RunLogPatch { + state; constructor(fields) { super(fields); - this.callbacks = fields?.callbacks; - this.tags = fields?.tags ?? []; - this.metadata = fields?.metadata ?? {}; - this.verbose = fields?.verbose ?? false; + this.state = fields.state; } - _getRelevantDocuments(_query, _callbacks) { - throw new Error("Not implemented!"); + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch(this.state, other.ops); + return new RunLog2({ + ops, + state: states[states.length - 1].newDocument + }); } - async invoke(input, options) { - const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); - const runManager = await (await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }))?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, undefined, undefined, undefined, parsedConfig.runName); - try { - const results = await this._getRelevantDocuments(input, runManager); - await runManager?.handleRetrieverEnd(results); - return results; - } catch (error51) { - await runManager?.handleRetrieverError(error51); - throw error51; - } + static fromRunLogPatch(patch) { + const states = applyPatch({}, patch.ops); + return new RunLog2({ + ops: patch.ops, + state: states[states.length - 1].newDocument + }); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/stores.js -var stores_exports, BaseStore, InMemoryStore; -var init_stores = __esm(() => { - init_runtime2(); - init_serializable(); - stores_exports = /* @__PURE__ */ __exportAll({ - BaseStore: () => BaseStore, - InMemoryStore: () => InMemoryStore - }); - BaseStore = class extends Serializable { - }; - InMemoryStore = class extends BaseStore { - lc_namespace = ["langchain", "storage"]; - store = {}; - async mget(keys) { - return keys.map((key) => this.store[key]); - } - async mset(keyValuePairs) { - for (const [key, value] of keyValuePairs) - this.store[key] = value; - } - async mdelete(keys) { - for (const key of keys) - delete this.store[key]; - } - async* yieldKeys(prefix) { - const keys = Object.keys(this.store); - for (const key of keys) - if (prefix === undefined || key.startsWith(prefix)) - yield key; + LogStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + _schemaFormat = "original"; + rootId; + keyMapByRunId = {}; + counterMapByRunName = {}; + transformStream; + writer; + receiveStream; + name = "log_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; + this.transformStream = new TransformStream; + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/structured_query/ir.js -var Operators, Comparators, Visitor = class { -}, Expression = class { - accept(visitor) { - if (this.exprName === "Operation") - return visitor.visitOperation(this); - else if (this.exprName === "Comparison") - return visitor.visitComparison(this); - else if (this.exprName === "StructuredQuery") - return visitor.visitStructuredQuery(this); - else - throw new Error("Unknown Expression type"); - } -}, FilterDirective, Comparison, Operation, StructuredQuery; -var init_ir = __esm(() => { - Operators = { - and: "and", - or: "or", - not: "not" - }; - Comparators = { - eq: "eq", - ne: "ne", - lt: "lt", - gt: "gt", - lte: "lte", - gte: "gte" - }; - FilterDirective = class extends Expression { - }; - Comparison = class extends FilterDirective { - exprName = "Comparison"; - constructor(comparator, attribute, value) { - super(); - this.comparator = comparator; - this.attribute = attribute; - this.value = value; + [Symbol.asyncIterator]() { + return this.receiveStream; } - }; - Operation = class extends FilterDirective { - exprName = "Operation"; - constructor(operator, args) { - super(); - this.operator = operator; - this.args = args; + async persistRun(_run) {} + _includeRun(run2) { + if (run2.id === this.rootId) + return false; + const runTags = run2.tags ?? []; + let include = this.includeNames === undefined && this.includeTags === undefined && this.includeTypes === undefined; + if (this.includeNames !== undefined) + include = include || this.includeNames.includes(run2.name); + if (this.includeTypes !== undefined) + include = include || this.includeTypes.includes(run2.run_type); + if (this.includeTags !== undefined) + include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + if (this.excludeNames !== undefined) + include = include && !this.excludeNames.includes(run2.name); + if (this.excludeTypes !== undefined) + include = include && !this.excludeTypes.includes(run2.run_type); + if (this.excludeTags !== undefined) + include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; } - }; - StructuredQuery = class extends Expression { - exprName = "StructuredQuery"; - constructor(query3, filter) { - super(); - this.query = query3; - this.filter = filter; + async* tapOutputIterable(runId, output) { + for await (const chunk of output) { + if (runId !== this.rootId) { + const key = this.keyMapByRunId[runId]; + if (key) + await this.writer.write(new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${key}/streamed_output/-`, + value: chunk + }] })); + } + yield chunk; + } } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/structured_query/utils.js -function isObject2(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj); -} -function isFilterEmpty(filter) { - if (!filter) - return true; - if (typeof filter === "string" && filter.length > 0) - return false; - if (typeof filter === "function") - return false; - return isObject2(filter) && Object.keys(filter).length === 0; -} -function isInt(value) { - if (typeof value === "number") - return value % 1 === 0; - else if (typeof value === "string") { - const numberValue = parseInt(value, 10); - return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; - } - return false; -} -function isFloat(value) { - if (typeof value === "number") - return value % 1 !== 0; - else if (typeof value === "string") { - const numberValue = parseFloat(value); - return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; - } - return false; -} -function isString(value) { - return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); -} -function isBoolean(value) { - return typeof value === "boolean"; -} -function castValue(input) { - let value; - if (isString(input)) - value = input; - else if (isInt(input)) - value = parseInt(input, 10); - else if (isFloat(input)) - value = parseFloat(input); - else if (isBoolean(input)) - value = Boolean(input); - else - throw new Error("Unsupported value type"); - return value; -} -var init_utils6 = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/structured_query/base.js -var BaseTranslator, BasicTranslator; -var init_base11 = __esm(() => { - init_ir(); - init_utils6(); - BaseTranslator = class extends Visitor { - }; - BasicTranslator = class extends BaseTranslator { - allowedOperators; - allowedComparators; - constructor(opts) { - super(); - this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; - this.allowedComparators = opts?.allowedComparators ?? [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - } - formatFunction(func) { - if (func in Comparators) { - if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) - throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); - } else if (func in Operators) { - if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) - throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); - } else - throw new Error("Unknown comparator or operator"); - return `$${func}`; - } - visitOperation(operation) { - const args = operation.args?.map((arg) => arg.accept(this)); - return { [this.formatFunction(operation.operator)]: args }; - } - visitComparison(comparison) { - return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; - } - visitStructuredQuery(query3) { - let nextArg = {}; - if (query3.filter) - nextArg = { filter: query3.filter.accept(this) }; - return nextArg; - } - mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) - return; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) - return; - return generatedFilter; + async onRunCreate(run2) { + if (this.rootId === undefined) { + this.rootId = run2.id; + await this.writer.write(new RunLogPatch({ ops: [{ + op: "replace", + path: "", + value: { + id: run2.id, + name: run2.name, + type: run2.run_type, + streamed_output: [], + final_output: undefined, + logs: {} + } + }] })); } - if (isFilterEmpty(generatedFilter)) { - if (forceDefaultFilter) - return defaultFilter; - if (mergeType === "and") + if (!this._includeRun(run2)) + return; + if (this.counterMapByRunName[run2.name] === undefined) + this.counterMapByRunName[run2.name] = 0; + this.counterMapByRunName[run2.name] += 1; + const count = this.counterMapByRunName[run2.name]; + this.keyMapByRunId[run2.id] = count === 1 ? run2.name : `${run2.name}:${count}`; + const logEntry = { + id: run2.id, + name: run2.name, + type: run2.run_type, + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {}, + start_time: new Date(run2.start_time).toISOString(), + streamed_output: [], + streamed_output_str: [], + final_output: undefined, + end_time: undefined + }; + if (this._schemaFormat === "streaming_events") + logEntry.inputs = await _getStandardizedInputs(run2, this._schemaFormat); + await this.writer.write(new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${this.keyMapByRunId[run2.id]}`, + value: logEntry + }] })); + } + async onRunUpdate(run2) { + try { + const runName = this.keyMapByRunId[run2.id]; + if (runName === undefined) return; - return defaultFilter; + const ops = []; + if (this._schemaFormat === "streaming_events") + ops.push({ + op: "replace", + path: `/logs/${runName}/inputs`, + value: await _getStandardizedInputs(run2, this._schemaFormat) + }); + ops.push({ + op: "add", + path: `/logs/${runName}/final_output`, + value: await _getStandardizedOutputs(run2, this._schemaFormat) + }); + if (run2.end_time !== undefined) + ops.push({ + op: "add", + path: `/logs/${runName}/end_time`, + value: new Date(run2.end_time).toISOString() + }); + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } finally { + if (run2.id === this.rootId) { + const patch = new RunLogPatch({ ops: [{ + op: "replace", + path: "/final_output", + value: await _getStandardizedOutputs(run2, this._schemaFormat) + }] }); + await this.writer.write(patch); + if (this.autoClose) + await this.writer.close(); + } } - if (mergeType === "and") - return { $and: [defaultFilter, generatedFilter] }; - else if (mergeType === "or") - return { $or: [defaultFilter, generatedFilter] }; + } + async onLLMNewToken(run2, token, kwargs) { + const runName = this.keyMapByRunId[run2.id]; + if (runName === undefined) + return; + const isChatModel = run2.inputs.messages !== undefined; + let streamedOutputValue; + if (isChatModel) + if (isChatGenerationChunk(kwargs?.chunk)) + streamedOutputValue = kwargs?.chunk; + else + streamedOutputValue = new AIMessageChunk({ + id: `run-${run2.id}`, + content: token + }); else - throw new Error("Unknown merge type"); + streamedOutputValue = token; + const patch = new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${runName}/streamed_output_str/-`, + value: token + }, { + op: "add", + path: `/logs/${runName}/streamed_output/-`, + value: streamedOutputValue + }] }); + await this.writer.write(patch); } }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/structured_query/functional.js -var FunctionalTranslator; -var init_functional = __esm(() => { - init_ir(); - init_utils6(); - init_base11(); - FunctionalTranslator = class extends BaseTranslator { - allowedOperators = [Operators.and, Operators.or]; - allowedComparators = [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - formatFunction() { - throw new Error("Not implemented"); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/event_stream.js +function assignName({ name, serialized }) { + if (name !== undefined) + return name; + if (serialized?.name !== undefined) + return serialized.name; + else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) + return serialized.id[serialized.id.length - 1]; + return "Unnamed"; +} +var isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer", EventStreamCallbackHandler; +var init_event_stream = __esm(() => { + init_ai(); + init_base3(); + init_stream(); + init_outputs(); + EventStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + runInfoMap = /* @__PURE__ */ new Map; + tappedPromises = /* @__PURE__ */ new Map; + transformStream; + writer; + receiveStream; + readableStreamClosed = false; + name = "event_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream({ flush: () => { + this.readableStreamClosed = true; + } }); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); } - getAllowedComparatorsForType(inputType) { - switch (inputType) { - case "string": - return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "number": - return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "boolean": - return [Comparators.eq, Comparators.ne]; - default: - throw new Error(`Unsupported data type: ${inputType}`); - } + [Symbol.asyncIterator]() { + return this.receiveStream; } - getComparatorFunction(comparator) { - switch (comparator) { - case Comparators.eq: - return (a, b) => a === b; - case Comparators.ne: - return (a, b) => a !== b; - case Comparators.gt: - return (a, b) => a > b; - case Comparators.gte: - return (a, b) => a >= b; - case Comparators.lt: - return (a, b) => a < b; - case Comparators.lte: - return (a, b) => a <= b; - default: - throw new Error("Unknown comparator"); - } + async persistRun(_run) {} + _includeRun(run2) { + const runTags = run2.tags ?? []; + let include = this.includeNames === undefined && this.includeTags === undefined && this.includeTypes === undefined; + if (this.includeNames !== undefined) + include = include || this.includeNames.includes(run2.name); + if (this.includeTypes !== undefined) + include = include || this.includeTypes.includes(run2.runType); + if (this.includeTags !== undefined) + include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + if (this.excludeNames !== undefined) + include = include && !this.excludeNames.includes(run2.name); + if (this.excludeTypes !== undefined) + include = include && !this.excludeTypes.includes(run2.runType); + if (this.excludeTags !== undefined) + include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; } - getOperatorFunction(operator) { - switch (operator) { - case Operators.and: - return (a, b) => a && b; - case Operators.or: - return (a, b) => a || b; - default: - throw new Error("Unknown operator"); + async* tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) + return; + const runInfo = this.runInfoMap.get(runId); + if (runInfo === undefined) { + yield firstChunk.value; + return; + } + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") + return new GenerationChunk({ text: data }); + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + if (tappedPromise === undefined) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve2) => { + tappedPromiseResolver = resolve2; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {} + }; + await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") + await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } + }, runInfo); + yield chunk; + } + } finally { + tappedPromiseResolver?.(); + } + } else { + yield firstChunk.value; + for await (const chunk of outputStream) + yield chunk; } } - visitOperation(operation) { - const { operator, args } = operation; - if (this.allowedOperators.includes(operator)) { - const operatorFunction = this.getOperatorFunction(operator); - return (document2) => { - if (!args) - return true; - return args.reduce((acc, arg) => { - const result = arg.accept(this); - if (typeof result === "function") - return operatorFunction(acc, result(document2)); - else - throw new Error("Filter is not a function"); - }, true); - }; + async send(payload, run2) { + if (this.readableStreamClosed) + return; + if (this._includeRun(run2)) + await this.writer.write(payload); + } + async sendEndEvent(payload, run2) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== undefined) + tappedPromise.then(() => { + this.send(payload, run2); + }); + else + await this.send(payload, run2); + } + async onLLMStart(run2) { + const runName = assignName(run2); + const runType = run2.inputs.messages !== undefined ? "chat_model" : "llm"; + const runInfo = { + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {}, + name: runName, + runType, + inputs: run2.inputs + }; + this.runInfoMap.set(run2.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { input: run2.inputs }, + name: runName, + tags: run2.tags ?? [], + run_id: run2.id, + metadata: run2.extra?.metadata ?? {} + }, runInfo); + } + async onLLMNewToken(run2, token, kwargs) { + const runInfo = this.runInfoMap.get(run2.id); + let chunk; + let eventName; + if (runInfo === undefined) + throw new Error(`onLLMNewToken: Run ID ${run2.id} not found in run map.`); + if (this.runInfoMap.size === 1) + return; + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === undefined) + chunk = new AIMessageChunk({ + content: token, + id: `run-${run2.id}` + }); + else + chunk = kwargs.chunk.message; + } else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === undefined) + chunk = new GenerationChunk({ text: token }); + else + chunk = kwargs.chunk; } else - throw new Error("Operator not allowed"); + throw new Error(`Unexpected run type ${runInfo.runType}`); + await this.send({ + event: eventName, + data: { chunk }, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); } - visitComparison(comparison) { - const { comparator, attribute, value } = comparison; - const undefinedTrue = [Comparators.ne]; - if (this.allowedComparators.includes(comparator)) { - if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) - throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); - const comparatorFunction = this.getComparatorFunction(comparator); - return (document2) => { - const documentValue = document2.metadata[attribute]; - if (documentValue === undefined) { - if (undefinedTrue.includes(comparator)) - return true; - return false; - } - return comparatorFunction(documentValue, castValue(value)); + async onLLMEnd(run2) { + const runInfo = this.runInfoMap.get(run2.id); + this.runInfoMap.delete(run2.id); + let eventName; + if (runInfo === undefined) + throw new Error(`onLLMEnd: Run ID ${run2.id} not found in run map.`); + const generations = run2.outputs?.generations; + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== undefined) + break; + output = generation[0]?.message; + } + eventName = "on_chat_model_end"; + } else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo + }; + }); + }), + llmOutput: run2.outputs?.llmOutput ?? {} }; + eventName = "on_llm_end"; } else - throw new Error("Comparator not allowed"); - } - visitStructuredQuery(query3) { - if (!query3.filter) - return {}; - const filterFunction = query3.filter?.accept(this); - if (typeof filterFunction !== "function") - throw new Error("Structured query filter is not a function"); - return { filter: filterFunction }; + throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs + }, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); } - mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) - return; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) - return; - return generatedFilter; - } - if (isFilterEmpty(generatedFilter)) { - if (mergeType === "and") - return; - return defaultFilter; + async onChainStart(run2) { + const runName = assignName(run2); + const runType = run2.run_type ?? "chain"; + const runInfo = { + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {}, + name: runName, + runType: run2.run_type + }; + let eventData = {}; + if (run2.inputs.input === "" && Object.keys(run2.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } else if (run2.inputs.input !== undefined) { + eventData.input = run2.inputs.input; + runInfo.inputs = run2.inputs.input; + } else { + eventData.input = run2.inputs; + runInfo.inputs = run2.inputs; } - if (mergeType === "and") - return (document2) => defaultFilter(document2) && generatedFilter(document2); - else if (mergeType === "or") - return (document2) => defaultFilter(document2) || generatedFilter(document2); - else - throw new Error("Unknown merge type"); + this.runInfoMap.set(run2.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run2.tags ?? [], + run_id: run2.id, + metadata: run2.extra?.metadata ?? {} + }, runInfo); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/structured_query/index.js -var structured_query_exports; -var init_structured_query = __esm(() => { - init_runtime2(); - init_ir(); - init_utils6(); - init_base11(); - init_functional(); - structured_query_exports = /* @__PURE__ */ __exportAll({ - BaseTranslator: () => BaseTranslator, - BasicTranslator: () => BasicTranslator, - Comparators: () => Comparators, - Comparison: () => Comparison, - Expression: () => Expression, - FilterDirective: () => FilterDirective, - FunctionalTranslator: () => FunctionalTranslator, - Operation: () => Operation, - Operators: () => Operators, - StructuredQuery: () => StructuredQuery, - Visitor: () => Visitor, - castValue: () => castValue, - isBoolean: () => isBoolean, - isFilterEmpty: () => isFilterEmpty, - isFloat: () => isFloat, - isInt: () => isInt, - isObject: () => isObject2, - isString: () => isString - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/testing/matchers.js -function getMessageTypeName(msg) { - if (!BaseMessage.isInstance(msg)) - return typeof msg; - return msg.constructor.name || msg.type; -} -function makeMessageTypeMatcher(typeName, isInstance) { - return function(received, expected) { - const { isNot, utils } = this; - if (!isInstance(received)) - return { - pass: false, - message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} - -Expected: ${isNot ? "not " : ""}${typeName} -Received: ${getMessageTypeName(received)}`, - actual: getMessageTypeName(received), - expected: typeName + async onChainEnd(run2) { + const runInfo = this.runInfoMap.get(run2.id); + this.runInfoMap.delete(run2.id); + if (runInfo === undefined) + throw new Error(`onChainEnd: Run ID ${run2.id} not found in run map.`); + const eventName = `on_${run2.run_type}_end`; + const inputs = run2.inputs ?? runInfo.inputs ?? {}; + const data = { + output: run2.outputs?.output ?? run2.outputs, + input: inputs }; - if (expected === undefined) - return { - pass: true, - message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} - -Expected: not ${typeName} -Received: ${typeName}` + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; + } + await this.sendEndEvent({ + event: eventName, + data, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {} + }, runInfo); + } + async onToolStart(run2) { + const runName = assignName(run2); + const runInfo = { + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run2.inputs ?? {} }; - const msg = received; - if (typeof expected === "string") - return { - pass: msg.content === expected, - message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} - -Expected: ${typeName} with content ${utils.printExpected(expected)} -Received: ${typeName} with content ${utils.printReceived(msg.content)}`, - actual: msg.content, - expected + this.runInfoMap.set(run2.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { input: run2.inputs ?? {} }, + name: runName, + run_id: run2.id, + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {} + }, runInfo); + } + async onToolEnd(run2) { + const runInfo = this.runInfoMap.get(run2.id); + this.runInfoMap.delete(run2.id); + if (runInfo === undefined) + throw new Error(`onToolEnd: Run ID ${run2.id} not found in run map.`); + if (runInfo.inputs === undefined) + throw new Error(`onToolEnd: Run ID ${run2.id} is a tool call, and is expected to have traced inputs.`); + const output = run2.outputs?.output === undefined ? run2.outputs : run2.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs + }, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onToolError(run2) { + const runInfo = this.runInfoMap.get(run2.id); + this.runInfoMap.delete(run2.id); + if (runInfo === undefined) + throw new Error(`onToolEnd: Run ID ${run2.id} not found in run map.`); + if (runInfo.inputs === undefined) + throw new Error(`onToolEnd: Run ID ${run2.id} is a tool call, and is expected to have traced inputs.`); + await this.sendEndEvent({ + event: "on_tool_error", + data: { + input: runInfo.inputs, + error: run2.error + }, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onRetrieverStart(run2) { + const runName = assignName(run2); + const runInfo = { + tags: run2.tags ?? [], + metadata: run2.extra?.metadata ?? {}, + name: runName, + runType: "retriever", + inputs: { query: run2.inputs.query } }; - return { - pass: Object.entries(expected).every(([key, value]) => this.equals(msg[key], value)), - message: () => { - const receivedFields = {}; - for (const key of Object.keys(expected)) - receivedFields[key] = msg[key]; - return `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} - -Expected: ${typeName} matching ${utils.printExpected(expected)} -Received: ${typeName} with ${utils.printReceived(receivedFields)}`; - }, - actual: (() => { - const receivedFields = {}; - for (const key of Object.keys(expected)) - receivedFields[key] = msg[key]; - return receivedFields; - })(), - expected - }; + this.runInfoMap.set(run2.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { input: { query: run2.inputs.query } }, + name: runName, + tags: run2.tags ?? [], + run_id: run2.id, + metadata: run2.extra?.metadata ?? {} + }, runInfo); + } + async onRetrieverEnd(run2) { + const runInfo = this.runInfoMap.get(run2.id); + this.runInfoMap.delete(run2.id); + if (runInfo === undefined) + throw new Error(`onRetrieverEnd: Run ID ${run2.id} not found in run map.`); + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run2.outputs?.documents ?? run2.outputs, + input: runInfo.inputs + }, + run_id: run2.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === undefined) + throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data + }, runInfo); + } + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + Promise.all(pendingPromises).finally(() => { + this.writer.close(); + }); + } }; -} -function toHaveToolCalls(received, expected) { - const { isNot, utils } = this; - if (!AIMessage.isInstance(received)) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolCalls")} - -Expected: AIMessage -Received: ${getMessageTypeName(received)}` - }; - const actual = received.tool_calls ?? []; - if (actual.length !== expected.length) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolCalls")} - -Expected ${isNot ? "not " : ""}${expected.length} tool call(s), received ${actual.length}`, - actual: actual.length, - expected: expected.length - }; - const unmatched = expected.filter((exp) => !actual.some((tc) => Object.entries(exp).every(([key, value]) => this.equals(tc[key], value)))); - if (unmatched.length > 0) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolCalls")} - -Could not find matching tool call(s) for: -${utils.printExpected(unmatched)} -Received tool calls: ${utils.printReceived(actual.map((tc) => ({ - name: tc.name, - id: tc.id, - args: tc.args - })))}`, - actual: actual.map((tc) => ({ - name: tc.name, - id: tc.id, - args: tc.args - })), - expected - }; - return { - pass: true, - message: () => `${utils.matcherHint("toHaveToolCalls")} +}); -Expected AIMessage not to have matching tool calls` - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/is-network-error/index.js +function isNetworkError2(error90) { + if (!(error90 && isError2(error90) && error90.name === "TypeError" && typeof error90.message === "string")) + return false; + const { message, stack } = error90; + if (message === "Load failed") + return stack === undefined || "__sentry_captured__" in error90; + if (message.startsWith("error sending request for url")) + return true; + return errorMessages2.has(message); } -function toHaveToolCallCount(received, expected) { - const { isNot, utils } = this; - if (!AIMessage.isInstance(received)) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolCallCount")} - -Expected: AIMessage -Received: ${getMessageTypeName(received)}` - }; - const actual = received.tool_calls?.length ?? 0; - return { - pass: actual === expected, - message: () => `${utils.matcherHint("toHaveToolCallCount")} +var objectToString2, isError2 = (value) => objectToString2.call(value) === "[object Error]", errorMessages2; +var init_is_network_error2 = __esm(() => { + objectToString2 = Object.prototype.toString; + errorMessages2 = new Set([ + "network error", + "Failed to fetch", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" + ]); +}); -Expected ${isNot ? "not " : ""}${expected} tool call(s) -Received: ${actual}`, - actual, - expected - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/p-retry/index.js +function validateRetries2(retries) { + if (typeof retries === "number") { + if (retries < 0) + throw new TypeError("Expected `retries` to be a non-negative number."); + if (Number.isNaN(retries)) + throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } else if (retries !== undefined) + throw new TypeError("Expected `retries` to be a number or Infinity."); } -function toContainToolCall(received, expected) { - const { isNot, utils } = this; - if (!AIMessage.isInstance(received)) - return { - pass: false, - message: () => `${utils.matcherHint("toContainToolCall")} - -Expected: AIMessage -Received: ${getMessageTypeName(received)}` - }; - const actual = received.tool_calls ?? []; - return { - pass: actual.some((tc) => Object.entries(expected).every(([key, value]) => this.equals(tc[key], value))), - message: () => `${utils.matcherHint("toContainToolCall")} - -Expected AIMessage ${isNot ? "not " : ""}to contain a tool call matching ${utils.printExpected(expected)} -Received tool calls: ${utils.printReceived(actual.map((tc) => ({ - name: tc.name, - id: tc.id - })))}`, - actual: actual.map((tc) => ({ - name: tc.name, - id: tc.id - })), - expected - }; +function validateNumberOption2(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === undefined) + return; + if (typeof value !== "number" || Number.isNaN(value)) + throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + if (!allowInfinity && !Number.isFinite(value)) + throw new TypeError(`Expected \`${name}\` to be a finite number.`); + if (value < min) + throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`); } -function toHaveToolMessages(received, expected) { - const { isNot, utils } = this; - if (!Array.isArray(received)) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolMessages")} - -Expected an array of messages -Received: ${typeof received}` - }; - const toolMessages = received.filter(ToolMessage.isInstance); - if (toolMessages.length !== expected.length) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveToolMessages")} - -Expected ${isNot ? "not " : ""}${expected.length} tool message(s), found ${toolMessages.length}`, - actual: toolMessages.length, - expected: expected.length - }; - for (let i = 0;i < expected.length; i++) - if (!Object.entries(expected[i]).every(([key, value]) => this.equals(toolMessages[i][key], value))) - return { - pass: false, - message: () => { - const receivedFields = {}; - for (const key of Object.keys(expected[i])) - receivedFields[key] = toolMessages[i][key]; - return `${utils.matcherHint("toHaveToolMessages")} - -Tool message at index ${i} did not match: -Expected: ${utils.printExpected(expected[i])} -Received: ${utils.printReceived(receivedFields)}`; - }, - actual: toolMessages[i], - expected: expected[i] - }; - return { - pass: true, - message: () => `${utils.matcherHint("toHaveToolMessages")} - -Expected messages not to contain matching tool messages` - }; +function calculateDelay2(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; } -function toHaveBeenInterrupted(received, expectedValue) { - const { isNot, utils } = this; - const interrupts = received?.__interrupt__; - if (!(Array.isArray(interrupts) && interrupts.length > 0)) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveBeenInterrupted")} - -Expected result ${isNot ? "not " : ""}to have been interrupted -Received __interrupt__: ${utils.printReceived(interrupts)}` - }; - if (expectedValue === undefined) - return { - pass: true, - message: () => `${utils.matcherHint("toHaveBeenInterrupted")} - -Expected result not to have been interrupted -Received ${interrupts.length} interrupt(s)` - }; - const actualValue = interrupts[0]?.value; - return { - pass: this.equals(actualValue, expectedValue), - message: () => `${utils.matcherHint("toHaveBeenInterrupted")} - -Expected interrupt value: ${utils.printExpected(expectedValue)} -Received interrupt value: ${utils.printReceived(actualValue)}`, - actual: actualValue, - expected: expectedValue - }; +function calculateRemainingTime2(start, max) { + if (!Number.isFinite(max)) + return max; + return max - (performance.now() - start); } -function toHaveStructuredResponse(received, expected) { - const { isNot, utils } = this; - const structuredResponse = received?.structuredResponse; - if (!(structuredResponse !== undefined)) - return { - pass: false, - message: () => `${utils.matcherHint("toHaveStructuredResponse")} - -Expected result ${isNot ? "not " : ""}to have a structured response -Received structuredResponse: undefined` - }; - if (expected === undefined) - return { - pass: true, - message: () => `${utils.matcherHint("toHaveStructuredResponse")} - -Expected result not to have a structured response` - }; - return { - pass: Object.entries(expected).every(([key, value]) => this.equals(structuredResponse[key], value)), - message: () => `${utils.matcherHint("toHaveStructuredResponse")} - -Expected structured response: ${utils.printExpected(expected)} -Received structured response: ${utils.printReceived(structuredResponse)}`, - actual: structuredResponse, - expected - }; -} -var toBeHumanMessage, toBeAIMessage, toBeSystemMessage, toBeToolMessage, langchainMatchers; -var init_matchers = __esm(() => { - init_base(); - init_tool(); - init_ai(); - init_human(); - init_system(); - init_messages(); - toBeHumanMessage = makeMessageTypeMatcher("HumanMessage", HumanMessage.isInstance); - toBeAIMessage = makeMessageTypeMatcher("AIMessage", AIMessage.isInstance); - toBeSystemMessage = makeMessageTypeMatcher("SystemMessage", SystemMessage.isInstance); - toBeToolMessage = makeMessageTypeMatcher("ToolMessage", ToolMessage.isInstance); - langchainMatchers = { - toBeHumanMessage, - toBeAIMessage, - toBeSystemMessage, - toBeToolMessage, - toHaveToolCalls, - toHaveToolCallCount, - toContainToolCall, - toHaveToolMessages, - toHaveBeenInterrupted, - toHaveStructuredResponse - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/testing/fake_model_builder.js -function deriveContent(messages) { - return messages.map((m) => m.text).filter(Boolean).join("-"); -} -function nextToolCallId() { - idCounter += 1; - return `fake_tc_${idCounter}`; -} -function fakeModel() { - return new FakeBuiltModel; +async function onAttemptFailure2({ error: error90, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error90 instanceof Error ? error90 : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error90}". You should only throw errors.`); + if (normalizedError instanceof AbortError2) + throw normalizedError.originalError; + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context); + if (calculateRemainingTime2(startTime, maxRetryTime) <= 0) + throw normalizedError; + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = calculateRemainingTime2(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) + throw normalizedError; + if (normalizedError instanceof TypeError && !isNetworkError2(normalizedError)) { + if (consumeRetry) + throw normalizedError; + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context)) + throw normalizedError; + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = calculateDelay2(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + if (finalDelay > 0) + await new Promise((resolve2, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve2(); + }, finalDelay); + if (options.unref) + timeoutToken.unref?.(); + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + options.signal?.throwIfAborted(); + return true; } -var idCounter = 0, FakeBuiltModel; -var init_fake_model_builder = __esm(() => { - init_base(); - init_ai(); - init_base4(); - init_messages(); - init_chat_models(); - FakeBuiltModel = class FakeBuiltModel2 extends BaseChatModel { - queue = []; - _alwaysThrowError; - _structuredResponseValue; - _tools = []; - _callIndex = 0; - _calls = []; - get calls() { - return this._calls; - } - get callCount() { - return this._calls.length; - } - constructor() { - super({}); - } - _llmType() { - return "fake-model-builder"; - } - _combineLLMOutput() { - return []; - } - respond(entry) { - if (typeof entry === "function") - this.queue.push({ - kind: "factory", - factory: entry - }); - else if (BaseMessage.isInstance(entry)) - this.queue.push({ - kind: "message", - message: entry - }); - else - this.queue.push({ - kind: "error", - error: entry - }); - return this; - } - respondWithTools(toolCalls) { - this.queue.push({ - kind: "toolCalls", - toolCalls: toolCalls.map((tc) => ({ - name: tc.name, - args: tc.args, - id: tc.id ?? nextToolCallId(), - type: "tool_call" - })) - }); - return this; - } - alwaysThrow(error51) { - this._alwaysThrowError = error51; - return this; - } - structuredResponse(value) { - this._structuredResponseValue = value; - return this; - } - bindTools(tools) { - const merged = [...this._tools, ...tools]; - const next = new FakeBuiltModel2; - next.queue = this.queue; - next._alwaysThrowError = this._alwaysThrowError; - next._structuredResponseValue = this._structuredResponseValue; - next._tools = merged; - next._calls = this._calls; - next._callIndex = this._callIndex; - return next.withConfig({}); - } - withStructuredOutput(_params, _config) { - const { _structuredResponseValue } = this; - return RunnableLambda.from(async () => { - return _structuredResponseValue; - }); - } - async _generate(messages, options, _runManager) { - this._calls.push({ - messages: [...messages], +async function pRetry2(input, options = {}) { + options = { ...options }; + validateRetries2(options.retries); + if (Object.hasOwn(options, "forever")) + throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1000; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + validateNumberOption2("factor", options.factor, { + min: 0, + allowInfinity: false + }); + validateNumberOption2("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false + }); + validateNumberOption2("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true + }); + validateNumberOption2("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true + }); + if (!(options.factor > 0)) + options.factor = 1; + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error90) { + if (await onAttemptFailure2({ + error: error90, + attemptNumber, + retriesConsumed, + startTime, options - }); - const currentCallIndex = this._callIndex; - this._callIndex += 1; - if (this._alwaysThrowError) - throw this._alwaysThrowError; - const entry = this.queue[currentCallIndex]; - if (!entry) - throw new Error(`FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`); - if (entry.kind === "error") - throw entry.error; - if (entry.kind === "factory") { - const result = entry.factory(messages); - if (!BaseMessage.isInstance(result)) - throw result; - return { generations: [{ - text: "", - message: result - }] }; + })) + retriesConsumed++; + } + } + throw new Error("Retry attempts exhausted without throwing an error."); +} +var AbortError2; +var init_p_retry2 = __esm(() => { + init_is_network_error2(); + AbortError2 = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; } - if (entry.kind === "message") - return { generations: [{ - text: "", - message: entry.message - }] }; - const content = deriveContent(messages); - return { - generations: [{ - text: content, - message: new AIMessage({ - content, - id: currentCallIndex.toString(), - tool_calls: entry.toolCalls.length > 0 ? entry.toolCalls.map((tc) => ({ - ...tc, - type: "tool_call" - })) : undefined - }) - }], - llmOutput: {} - }; + this.name = "AbortError"; + this.message = message; } }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/testing/index.js -var testing_exports; -var init_testing = __esm(() => { +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/async_caller.js +var import_p_queue4, async_caller_exports, STATUS_NO_RETRY, defaultFailedAttemptHandler = (error90) => { + if (typeof error90 !== "object" || error90 === null) + return; + if ("message" in error90 && typeof error90.message === "string" && (error90.message.startsWith("Cancel") || error90.message.startsWith("AbortError")) || "name" in error90 && typeof error90.name === "string" && error90.name === "AbortError") + throw error90; + if ("code" in error90 && typeof error90.code === "string" && error90.code === "ECONNABORTED") + throw error90; + const responseStatus = "response" in error90 && typeof error90.response === "object" && error90.response !== null && "status" in error90.response && typeof error90.response.status === "number" ? error90.response.status : undefined; + const directStatus = "status" in error90 && typeof error90.status === "number" ? error90.status : undefined; + const status = responseStatus ?? directStatus; + if (status && STATUS_NO_RETRY.includes(+status)) + throw error90; + if (("error" in error90 && typeof error90.error === "object" && error90.error !== null && "code" in error90.error && typeof error90.error.code === "string" ? error90.error.code : undefined) === "insufficient_quota") { + const err = new Error("message" in error90 && typeof error90.message === "string" ? error90.message : "Insufficient quota"); + err.name = "InsufficientQuotaError"; + throw err; + } +}, AsyncCaller2 = class { + maxConcurrency; + maxRetries; + onFailedAttempt; + queue; + constructor(params) { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue2 = "default" in import_p_queue4.default ? import_p_queue4.default.default : import_p_queue4.default; + this.queue = new PQueue2({ concurrency: this.maxConcurrency }); + } + async call(callable, ...args) { + return this.queue.add(() => pRetry2(() => callable(...args).catch((error90) => { + if (error90 instanceof Error) + throw error90; + else + throw new Error(error90); + }), { + onFailedAttempt: ({ error: error90 }) => this.onFailedAttempt?.(error90), + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + callWithOptions(options, callable, ...args) { + if (options.signal) { + let listener; + return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { + listener = () => { + reject(getAbortSignalError(options.signal)); + }; + options.signal?.addEventListener("abort", listener, { once: true }); + })]).finally(() => { + if (options.signal && listener) + options.signal.removeEventListener("abort", listener); + }); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); + } +}; +var init_async_caller2 = __esm(() => { init_runtime2(); - init_matchers(); - init_fake_model_builder(); - testing_exports = /* @__PURE__ */ __exportAll({ - FakeBuiltModel: () => FakeBuiltModel, - fakeModel: () => fakeModel, - langchainMatchers: () => langchainMatchers, - toBeAIMessage: () => toBeAIMessage, - toBeHumanMessage: () => toBeHumanMessage, - toBeSystemMessage: () => toBeSystemMessage, - toBeToolMessage: () => toBeToolMessage, - toContainToolCall: () => toContainToolCall, - toHaveBeenInterrupted: () => toHaveBeenInterrupted, - toHaveStructuredResponse: () => toHaveStructuredResponse, - toHaveToolCallCount: () => toHaveToolCallCount, - toHaveToolCalls: () => toHaveToolCalls, - toHaveToolMessages: () => toHaveToolMessages - }); + init_signal(); + init_p_retry2(); + import_p_queue4 = __toESM(require_dist(), 1); + async_caller_exports = /* @__PURE__ */ __exportAll({ AsyncCaller: () => AsyncCaller2 }); + STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 + ]; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/tracers/run_collector.js -var run_collector_exports, RunCollectorCallbackHandler; -var init_run_collector = __esm(() => { - init_runtime2(); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/root_listener.js +var RootListenersTracer; +var init_root_listener = __esm(() => { init_base3(); - run_collector_exports = /* @__PURE__ */ __exportAll({ RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); - RunCollectorCallbackHandler = class extends BaseTracer { - name = "run_collector"; - exampleId; - tracedRuns; - constructor({ exampleId } = {}) { + RootListenersTracer = class extends BaseTracer { + name = "RootListenersTracer"; + rootId; + config; + argOnStart; + argOnEnd; + argOnError; + constructor({ config: config3, onStart, onEnd, onError: onError2 }) { super({ _awaitHandler: true }); - this.exampleId = exampleId; - this.tracedRuns = []; + this.config = config3; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError2; } - async persistRun(run2) { - const run_ = { ...run2 }; - run_.reference_example_id = this.exampleId; - this.tracedRuns.push(run_); + persistRun(_) { + return Promise.resolve(); + } + async onRunCreate(run2) { + if (this.rootId) + return; + this.rootId = run2.id; + if (this.argOnStart) + await this.argOnStart(run2, this.config); + } + async onRunUpdate(run2) { + if (run2.id !== this.rootId) + return; + if (!run2.error) { + if (this.argOnEnd) + await this.argOnEnd(run2, this.config); + } else if (this.argOnError) + await this.argOnError(run2, this.config); } }; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/types/stream.js -var stream_exports3; -var init_stream3 = __esm(() => { - init_runtime2(); - stream_exports3 = /* @__PURE__ */ __exportAll({}); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/chunk_array.js -var chunk_array_exports, chunkArray = (arr3, chunkSize) => arr3.reduce((chunks, elem, index2) => { - const chunkIndex = Math.floor(index2 / chunkSize); - chunks[chunkIndex] = (chunks[chunkIndex] || []).concat([elem]); - return chunks; -}, []); -var init_chunk_array = __esm(() => { - init_runtime2(); - chunk_array_exports = /* @__PURE__ */ __exportAll({ chunkArray: () => chunkArray }); -}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/utils.js +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +var _RootEventFilter = class { + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + constructor(fields) { + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; + } + includeEvent(event, rootType) { + let include = this.includeNames === undefined && this.includeTypes === undefined && this.includeTags === undefined; + const eventTags = event.tags ?? []; + if (this.includeNames !== undefined) + include = include || this.includeNames.includes(event.name); + if (this.includeTypes !== undefined) + include = include || this.includeTypes.includes(rootType); + if (this.includeTags !== undefined) + include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); + if (this.excludeNames !== undefined) + include = include && !this.excludeNames.includes(event.name); + if (this.excludeTypes !== undefined) + include = include && !this.excludeTypes.includes(rootType); + if (this.excludeTags !== undefined) + include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; + } +}, toBase64Url = (str) => { + return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +}; +var init_utils4 = () => {}; -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/context.js -function context(strings, ...values) { - const raw2 = strings.raw; - let result = ""; - for (let i = 0;i < raw2.length; i++) { - const next = raw2[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{"); - result += next; - if (i < values.length) { - const value = alignValue(values[i], result); - result += typeof value === "string" ? value : JSON.stringify(value); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/graph_mermaid.js +function _escapeNodeLabel(nodeLabel) { + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +function _generateMermaidGraphStyles(nodeColors) { + let styles2 = ""; + for (const [className, color2] of Object.entries(nodeColors)) + styles2 += ` classDef ${className} ${color2}; +`; + return styles2; +} +function drawMermaid(nodes, edges, config3) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config3 ?? {}; + let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%% +graph TD; +` : `graph TD; +`; + if (withStyles) { + const defaultClassLabel = "default"; + const formatDict = { [defaultClassLabel]: "{0}({1})" }; + if (firstNode !== undefined) + formatDict[firstNode] = "{0}([{1}]):::first"; + if (lastNode !== undefined) + formatDict[lastNode] = "{0}([{1}]):::last"; + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + let finalLabel = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; + if (Object.keys(node.metadata ?? {}).length) + finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join(` +`)}`; + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); + mermaidGraph += ` ${nodeLabel} +`; } } - result = stripIndent(result); - result = result.trim(); - result = result.replace(/\\n/g, ` -`); - return result; -} -function alignValue(value, precedingText) { - if (typeof value !== "string" || !value.includes(` -`)) - return value; - const indentMatch = precedingText.slice(precedingText.lastIndexOf(` -`) + 1).match(/^(\s+)/); - if (indentMatch) { - const indent = indentMatch[1]; - return value.replace(/\n/g, ` -${indent}`); + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); + if (!edgeGroups[commonPrefix]) + edgeGroups[commonPrefix] = []; + edgeGroups[commonPrefix].push(edge); } - return value; -} -function stripIndent(text) { - const lines = text.split(` -`); - let minIndent = null; - for (const line of lines) { - const match2 = line.match(/^(\s+)\S+/); - if (match2) { - const indent = match2[1].length; - if (minIndent === null) - minIndent = indent; - else - minIndent = Math.min(minIndent, indent); + const seenSubgraphs = /* @__PURE__ */ new Set; + function sortPrefixesByDepth(prefixes) { + return [...prefixes].sort((a, b) => { + return a.split(":").length - b.split(":").length; + }); + } + function addSubgraph(edges2, prefix) { + const selfLoop = edges2.length === 1 && edges2[0].source === edges2[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(prefix)) + throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); + seenSubgraphs.add(prefix); + mermaidGraph += ` subgraph ${subgraph} +`; + } + const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1)); + for (const nestedPrefix of nestedPrefixes) + addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + for (const edge of edges2) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== undefined) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) + edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); + edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; + } else + edgeLabel = conditional ? " -.-> " : " --> "; + mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)}; +`; } + if (prefix && !selfLoop) + mermaidGraph += ` end +`; } - if (minIndent === null) - return text; - return lines.map((line) => line[0] === " " || line[0] === "\t" ? line.slice(minIndent) : line).join(` -`); + addSubgraph(edgeGroups[""] ?? [], ""); + for (const prefix in edgeGroups) + if (!prefix.includes(":") && prefix !== "") + addSubgraph(edgeGroups[prefix], prefix); + if (withStyles) + mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + return mermaidGraph; } -var context_exports; -var init_context2 = __esm(() => { - init_runtime2(); - context_exports = /* @__PURE__ */ __exportAll({ context: () => context }); +async function drawMermaidImage(mermaidSyntax, config3) { + let backgroundColor = config3?.backgroundColor ?? "white"; + const imageType = config3?.imageType ?? "png"; + const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax); + if (backgroundColor !== undefined) { + if (!/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(backgroundColor)) + backgroundColor = `!${backgroundColor}`; + } + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; + const res = await fetch(imageUrl); + if (!res.ok) + throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}` + ].join(` +`)); + return await res.blob(); +} +var MARKDOWN_SPECIAL_CHARS; +var init_graph_mermaid = __esm(() => { + init_utils4(); + MARKDOWN_SPECIAL_CHARS = [ + "*", + "_", + "`" + ]; }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/event_source_parse.js -async function getBytes(stream2, onChunk) { - if (stream2 instanceof ReadableStream) { - const reader = stream2.getReader(); - while (true) { - const result = await reader.read(); - if (result.done) { - onChunk(new Uint8Array, true); - break; - } - onChunk(result.value); - } - } else +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/graph.js +function nodeDataStr(id, data) { + if (id !== undefined && !validate3(id)) + return id; + else if (isRunnableInterface(data)) try { - for await (const chunk of stream2) - onChunk(new Uint8Array(chunk)); - onChunk(new Uint8Array, true); - } catch (e) { - throw new Error([ - "Parsing event source stream failed.", - "Ensure your implementation of fetch returns a web or Node readable stream.", - `Error: ${e.message}` - ].join(` -`)); - } -} -function getLines(onLine) { - let buffer; - let position; - let fieldLength; - let discardTrailingNewline = false; - return function onChunk(arr3, flush) { - if (flush) { - onLine(arr3, 0, true); - return; - } - if (buffer === undefined) { - buffer = arr3; - position = 0; - fieldLength = -1; - } else - buffer = concat2(buffer, arr3); - const bufLength = buffer.length; - let lineStart = 0; - while (position < bufLength) { - if (discardTrailingNewline) { - if (buffer[position] === 10) - lineStart = ++position; - discardTrailingNewline = false; - } - let lineEnd = -1; - for (;position < bufLength && lineEnd === -1; ++position) - switch (buffer[position]) { - case 58: - if (fieldLength === -1) - fieldLength = position - lineStart; - break; - case 13: - discardTrailingNewline = true; - case 10: - lineEnd = position; - break; - } - if (lineEnd === -1) - break; - onLine(buffer.subarray(lineStart, lineEnd), fieldLength); - lineStart = position; - fieldLength = -1; - } - if (lineStart === bufLength) - buffer = undefined; - else if (lineStart !== 0) { - buffer = buffer.subarray(lineStart); - position -= lineStart; + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); } - }; + else + return data.name ?? "UnknownSchema"; } -function getMessages(onMessage, onId, onRetry) { - let message = newMessage(); - const decoder = new TextDecoder; - return function onLine(line, fieldLength, flush) { - if (flush) { - if (!isEmpty(message)) { - onMessage?.(message); - message = newMessage(); +function nodeDataJson(node) { + if (isRunnableInterface(node.data)) + return { + type: "runnable", + data: { + id: node.data.lc_id, + name: node.data.getName() } - return; - } - if (line.length === 0) { - onMessage?.(message); - message = newMessage(); - } else if (fieldLength > 0) { - const field = decoder.decode(line.subarray(0, fieldLength)); - const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1); - const value = decoder.decode(line.subarray(valueOffset)); - switch (field) { - case "data": - message.data = message.data ? message.data + ` -` + value : value; - break; - case "event": - message.event = value; - break; - case "id": - onId?.(message.id = value); - break; - case "retry": { - const retry = parseInt(value, 10); - if (!Number.isNaN(retry)) - onRetry?.(message.retry = retry); - break; - } + }; + else + return { + type: "schema", + data: { + ...toJsonSchema(node.data.schema), + title: node.data.name } - } - }; + }; } -function concat2(a, b) { - const res = new Uint8Array(a.length + b.length); - res.set(a); - res.set(b, a.length); - return res; +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) + if (!exclude.includes(node.id) && !targets.has(node.id)) + found.push(node); + return found.length === 1 ? found[0] : undefined; } -function newMessage() { - return { - data: "", - event: "", - id: "", - retry: undefined - }; +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) + if (!exclude.includes(node.id) && !sources.has(node.id)) + found.push(node); + return found.length === 1 ? found[0] : undefined; } -function convertEventStreamToIterableReadableDataStream(stream2, onMetadataEvent) { - const dataStream = new ReadableStream({ async start(controller) { - const enqueueLine = getMessages((msg) => { - if (msg.event === "error") - throw new Error(msg.data ?? "Unspecified event streaming error."); - else if (msg.event === "metadata") - onMetadataEvent?.(msg); - else if (msg.data) - controller.enqueue(msg.data); +var graph_exports, Graph = class Graph2 { + nodes = {}; + edges = []; + constructor(params) { + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; + } + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = validate3(node.id) ? i : node.id; }); - const onLine = (line, fieldLength, flush) => { - enqueueLine(line, fieldLength, flush); - if (flush) - controller.close(); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node) + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target] + }; + if (typeof edge.data !== "undefined") + item.data = edge.data; + if (typeof edge.conditional !== "undefined") + item.conditional = edge.conditional; + return item; + }) }; - await getBytes(stream2, getLines(onLine)); - } }); - return IterableReadableStream.fromReadableStream(dataStream); -} -function isEmpty(message) { - return message.data === "" && message.event === "" && message.id === "" && message.retry === undefined; -} -var event_source_parse_exports, EventStreamContentType = "text/event-stream"; -var init_event_source_parse = __esm(() => { + } + addNode(data, id, metadata) { + if (id !== undefined && this.nodes[id] !== undefined) + throw new Error(`Node with id ${id} already exists`); + const nodeId = id ?? v42(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata + }; + this.nodes[nodeId] = node; + return node; + } + removeNode(node) { + delete this.nodes[node.id]; + this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); + } + addEdge(source, target, data, conditional) { + if (this.nodes[source.id] === undefined) + throw new Error(`Source node ${source.id} not in graph`); + if (this.nodes[target.id] === undefined) + throw new Error(`Target node ${target.id} not in graph`); + const edge = { + source: source.id, + target: target.id, + data, + conditional + }; + this.edges.push(edge); + return edge; + } + firstNode() { + return _firstNode(this); + } + lastNode() { + return _lastNode(this); + } + extend(graph, prefix = "") { + let finalPrefix = prefix; + if (Object.values(graph.nodes).map((node) => node.id).every(validate3)) + finalPrefix = ""; + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { + ...value, + id: prefixed(key) + }; + }); + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target) + }; + }); + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last = graph.lastNode(); + return [first ? { + id: prefixed(first.id), + data: first.data + } : undefined, last ? { + id: prefixed(last.id), + data: last.data + } : undefined]; + } + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) + this.removeNode(firstNode); + } + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) + this.removeNode(lastNode); + } + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = /* @__PURE__ */ new Map; + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (validate3(nodeId) && nodeLabelCounts.get(label) === 1) + return label; + else + return nodeId; + }; + return new Graph2({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { + ...node, + id: getNodeId(id) + }])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target) + })) + }); + } + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc" + }, wrapLabelNWords } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords + }); + } + async drawMermaidPng(params) { + return drawMermaidImage(this.drawMermaid(params), { backgroundColor: params?.backgroundColor }); + } +}; +var init_graph = __esm(() => { init_runtime2(); - init_stream(); - event_source_parse_exports = /* @__PURE__ */ __exportAll({ - EventStreamContentType: () => EventStreamContentType, - convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, - getBytes: () => getBytes, - getLines: () => getLines, - getMessages: () => getMessages - }); + init_uuid(); + init_utils4(); + init_graph_mermaid(); + init_json_schema3(); + graph_exports = /* @__PURE__ */ __exportAll({ Graph: () => Graph }); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/format.js -var format_exports; -var init_format3 = __esm(() => { - init_runtime2(); - format_exports = /* @__PURE__ */ __exportAll({}); -}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/wrappers.js +function convertToHttpEventStream(stream2) { + const encoder2 = new TextEncoder; + const finalStream = new ReadableStream({ async start(controller) { + for await (const chunk of stream2) + controller.enqueue(encoder2.encode(`event: data +data: ${JSON.stringify(chunk)} -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/function_calling.js -function convertToOpenAIFunction(tool2, fields) { - const fieldsCopy = typeof fields === "number" ? undefined : fields; - return { - name: tool2.name, - description: tool2.description, - parameters: toJsonSchema(tool2.schema), - ...fieldsCopy?.strict !== undefined ? { strict: fieldsCopy.strict } : {} - }; -} -function convertToOpenAITool(tool2, fields) { - const fieldsCopy = typeof fields === "number" ? undefined : fields; - let toolDef; - if (isLangChainTool(tool2)) - toolDef = { - type: "function", - function: convertToOpenAIFunction(tool2) - }; - else - toolDef = tool2; - if (fieldsCopy?.strict !== undefined) - toolDef.function.strict = fieldsCopy.strict; - return toolDef; +`)); + controller.enqueue(encoder2.encode(`event: end + +`)); + controller.close(); + } }); + return IterableReadableStream.fromReadableStream(finalStream); } -var function_calling_exports; -var init_function_calling = __esm(() => { - init_runtime2(); - init_json_schema2(); - init_types4(); - function_calling_exports = /* @__PURE__ */ __exportAll({ - convertToOpenAIFunction: () => convertToOpenAIFunction, - convertToOpenAITool: () => convertToOpenAITool, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams - }); +var init_wrappers = __esm(() => { + init_stream(); }); -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/ml-distance/similarities.js -function cosine(a, b) { - let p = 0; - let p2 = 0; - let q2 = 0; - for (let i = 0;i < a.length; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; - } - return p / (Math.sqrt(p2) * Math.sqrt(q2)); -} -var init_similarities = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/ml-distance/distances.js -function innerProduct(a, b) { - let ans = 0; - for (let i = 0;i < a.length; i++) - ans += a[i] * b[i]; - return ans; -} -var init_distances = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js -function squaredEuclidean(p, q) { - let d = 0; - for (let i = 0;i < p.length; i++) - d += (p[i] - q[i]) * (p[i] - q[i]); - return d; -} -function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); -} -var init_euclidean = () => {}; - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/math.js -function matrixFunc(X, Y, func) { - if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) - return [[]]; - if (X[0].length !== Y[0].length) - throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); - return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); -} -function normalize2(M, similarity = false) { - const max = matrixMaxVal(M); - return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); -} -function cosineSimilarity(X, Y) { - return matrixFunc(X, Y, cosine); -} -function innerProduct2(X, Y) { - return matrixFunc(X, Y, innerProduct); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/iter.js +function isIterableIterator(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; } -function euclideanDistance(X, Y) { - return matrixFunc(X, Y, euclidean); +function isAsyncIterable(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; } -function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = 0.5, k = 4) { - if (Math.min(k, embeddingList.length) <= 0) - return []; - const similarityToQuery = cosineSimilarity(Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding], embeddingList)[0]; - const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; - const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; - const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; - while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { - let bestScore = -Infinity; - let bestIndex = -1; - const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); - similarityToQuery.forEach((queryScore, queryScoreIndex) => { - if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) - return; - const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); - const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; - if (score > bestScore) { - bestScore = score; - bestIndex = queryScoreIndex; - } - }); - selectedEmbeddings.push(embeddingList[bestIndex]); - selectedEmbeddingsIndexes.push(bestIndex); - } - return selectedEmbeddingsIndexes; +function isAsyncGenerator(x) { + return x != null && typeof x === "object" && typeof x.next === "function"; } -function argMax(array2) { - if (array2.length === 0) - return { - maxIndex: -1, - maxValue: NaN - }; - let maxValue = array2[0]; - let maxIndex = 0; - for (let i = 1;i < array2.length; i += 1) - if (array2[i] > maxValue) { - maxIndex = i; - maxValue = array2[i]; +async function consumeAsyncGenerator(generator, onYield) { + try { + let iterResult = await generator.next(); + while (!iterResult.done) { + await onYield?.(iterResult.value); + iterResult = await generator.next(); } - return { - maxIndex, - maxValue - }; -} -function matrixMaxVal(arrays) { - return arrays.reduce((acc, array2) => Math.max(acc, argMax(array2).maxValue), 0); -} -var math_exports; -var init_math = __esm(() => { - init_runtime2(); - init_similarities(); - init_distances(); - init_euclidean(); - math_exports = /* @__PURE__ */ __exportAll({ - cosineSimilarity: () => cosineSimilarity, - euclideanDistance: () => euclideanDistance, - innerProduct: () => innerProduct2, - matrixFunc: () => matrixFunc, - maximalMarginalRelevance: () => maximalMarginalRelevance, - normalize: () => normalize2 - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/ssrf.js -function isIPv4(ip) { - return IPV4_REGEX.test(ip); -} -function isIPv6(ip) { - return expandIpv6(ip) !== null; -} -function isIP(ip) { - return isIPv4(ip) || isIPv6(ip); -} -function parseIp(ip) { - if (isIPv4(ip)) - return ip.split(".").map((octet) => parseInt(octet, 10)); - else if (isIPv6(ip)) { - const expanded = expandIpv6(ip); - if (!expanded) - return null; - const parts = expanded.split(":"); - const result = []; - for (const part of parts) - result.push(parseInt(part, 16)); - return result; + return iterResult.value; + } finally { + await generator.return?.(undefined); } - return null; } -function expandIpv6(ip) { - if (!ip || typeof ip !== "string") - return null; - if (!ip.includes(":")) - return null; - if (!/^[0-9a-fA-F:]+$/.test(ip)) - return null; - let normalized = ip; - if (normalized.includes("::")) { - const parts2 = normalized.split("::"); - if (parts2.length > 2) - return null; - const [left, right] = parts2; - const leftParts = left ? left.split(":") : []; - const rightParts = right ? right.split(":") : []; - const missing = 8 - (leftParts.length + rightParts.length); - if (missing < 0) - return null; - const zeros = Array(missing).fill("0"); - normalized = [ - ...leftParts, - ...zeros, - ...rightParts - ].filter((p) => p !== "").join(":"); - } - const parts = normalized.split(":"); - if (parts.length !== 8) - return null; - for (const part of parts) { - if (part.length === 0 || part.length > 4) - return null; - if (!/^[0-9a-fA-F]+$/.test(part)) - return null; +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) + break; + else + yield value; } - return parts.map((p) => p.padStart(4, "0").toLowerCase()).join(":"); -} -function parseCidr(cidr) { - const [addrStr, prefixStr] = cidr.split("/"); - if (!addrStr || !prefixStr) - return null; - const addr = parseIp(addrStr); - if (!addr) - return null; - const prefixLen = parseInt(prefixStr, 10); - if (isNaN(prefixLen)) - return null; - const isIpv6 = isIPv6(addrStr); - if (isIpv6 && prefixLen > 128) - return null; - if (!isIpv6 && prefixLen > 32) - return null; - return { - addr, - prefixLen, - isIpv6 - }; -} -function isIpInCidr(ip, cidr) { - const ipParsed = parseIp(ip); - if (!ipParsed) - return false; - const cidrParsed = parseCidr(cidr); - if (!cidrParsed) - return false; - const isIpv6 = isIPv6(ip); - if (isIpv6 !== cidrParsed.isIpv6) - return false; - const { addr: cidrAddr, prefixLen } = cidrParsed; - if (isIpv6) - for (let i = 0;i < Math.ceil(prefixLen / 16); i++) { - const mask = 65535 << 16 - Math.min(16, prefixLen - i * 16) & 65535; - if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) - return false; - } - else - for (let i = 0;i < Math.ceil(prefixLen / 8); i++) { - const mask = 255 << 8 - Math.min(8, prefixLen - i * 8) & 255; - if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) - return false; - } - return true; -} -function isPrivateIp(ip) { - if (!isIP(ip)) - return false; - for (const range of PRIVATE_IP_RANGES) - if (isIpInCidr(ip, range)) - return true; - return false; -} -function isCloudMetadata(hostname3, ip) { - if (CLOUD_METADATA_IPS.includes(ip || "")) - return true; - const lowerHostname = hostname3.toLowerCase(); - if (CLOUD_METADATA_HOSTNAMES.includes(lowerHostname)) - return true; - return false; } -function isLocalhost2(hostname3, ip) { - if (ip) { - if (ip === "127.0.0.1" || ip === "::1" || ip === "0.0.0.0") - return true; - if (ip.startsWith("127.")) - return true; +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) + break; + else + yield value; } - const lowerHostname = hostname3.toLowerCase(); - if (LOCALHOST_NAMES.includes(lowerHostname)) - return true; - return false; } -function validateSafeUrl(url2, options) { - const allowPrivate = options?.allowPrivate ?? false; - const allowHttp = options?.allowHttp ?? false; - try { - let parsedUrl; - try { - parsedUrl = new URL(url2); - } catch { - throw new Error(`Invalid URL: ${url2}`); - } - const hostname3 = parsedUrl.hostname; - if (!hostname3) - throw new Error("URL missing hostname."); - if (isCloudMetadata(hostname3)) - throw new Error(`URL points to cloud metadata endpoint: ${hostname3}`); - if (isLocalhost2(hostname3)) { - if (!allowPrivate) - throw new Error(`URL points to localhost: ${hostname3}`); - return url2; - } - const scheme = parsedUrl.protocol; - if (scheme !== "http:" && scheme !== "https:") - throw new Error(`Invalid URL scheme: ${scheme}. Only http and https are allowed.`); - if (scheme === "http:" && !allowHttp) - throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true."); - if (isIP(hostname3)) { - const ip = hostname3; - if (isLocalhost2(hostname3, ip)) { - if (!allowPrivate) - throw new Error(`URL points to localhost: ${hostname3}`); - return url2; - } - if (isCloudMetadata(hostname3, ip)) - throw new Error(`URL resolves to cloud metadata IP: ${ip} (${hostname3})`); - if (isPrivateIp(ip)) { - if (!allowPrivate) - throw new Error(`URL resolves to private IP: ${ip} (${hostname3}). Set allowPrivate: true to allow.`); - } - return url2; - } - return url2; - } catch (error51) { - if (error51 && typeof error51 === "object" && "message" in error51) - throw error51; - throw new Error(`URL validation failed: ${error51}`); - } +var isIterator = (x) => x != null && typeof x === "object" && ("next" in x) && typeof x.next === "function"; +var init_iter = __esm(() => { + init_async_local_storage(); + init_singletons(); + init_config(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/base.js +function _coerceToDict2(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; } -function isSafeUrl(url2, options) { - try { - validateSafeUrl(url2, options); - return true; - } catch { - return false; - } +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) + throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); } -function isSameOrigin(url1, url2) { - try { - return new URL(url1).origin === new URL(url2).origin; - } catch { - return false; - } +function _coerceToRunnable(coerceable) { + if (typeof coerceable === "function") + return new RunnableLambda({ func: coerceable }); + else if (Runnable.isRunnable(coerceable)) + return coerceable; + else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) + runnables[key] = _coerceToRunnable(value); + return new RunnableMap({ steps: runnables }); + } else + throw new Error(`Expected a Runnable, function or object. +Instead got an unsupported type.`); } -var ssrf_exports, PRIVATE_IP_RANGES, CLOUD_METADATA_IPS, CLOUD_METADATA_HOSTNAMES, LOCALHOST_NAMES, IPV4_REGEX; -var init_ssrf = __esm(() => { - init_runtime2(); - ssrf_exports = /* @__PURE__ */ __exportAll({ - isCloudMetadata: () => isCloudMetadata, - isLocalhost: () => isLocalhost2, - isPrivateIp: () => isPrivateIp, - isSafeUrl: () => isSafeUrl, - isSameOrigin: () => isSameOrigin, - validateSafeUrl: () => validateSafeUrl +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) + return new RunnableToolLike({ + name, + description, + schema: exports_external2.object({ input: exports_external2.string() }).transform((input) => input.input), + bound: runnable + }); + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable }); - PRIVATE_IP_RANGES = [ - "10.0.0.0/8", - "172.16.0.0/12", - "192.168.0.0/16", - "127.0.0.0/8", - "169.254.0.0/16", - "0.0.0.0/8", - "::1/128", - "fc00::/7", - "fe80::/10", - "ff00::/8" - ]; - CLOUD_METADATA_IPS = [ - "169.254.169.254", - "169.254.170.2", - "100.100.100.200" - ]; - CLOUD_METADATA_HOSTNAMES = [ - "metadata.google.internal", - "metadata", - "instance-data" - ]; - LOCALHOST_NAMES = ["localhost", "localhost.localdomain"]; - IPV4_REGEX = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/vectorstores.js -var vectorstores_exports, VectorStoreRetriever, VectorStore, SaveableVectorStore; -var init_vectorstores = __esm(() => { - init_runtime2(); +} +var Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableTraceable, RunnableLambda, RunnableParallel, RunnableWithFallbacks, RunnableAssign, RunnablePick, RunnableToolLike; +var init_base4 = __esm(() => { + init_utils2(); init_serializable(); - init_retrievers(); - vectorstores_exports = /* @__PURE__ */ __exportAll({ - SaveableVectorStore: () => SaveableVectorStore, - VectorStore: () => VectorStore, - VectorStoreRetriever: () => VectorStoreRetriever - }); - VectorStoreRetriever = class extends BaseRetriever { - static lc_name() { - return "VectorStoreRetriever"; + init_uuid(); + init_async_local_storage(); + init_singletons(); + init_config(); + init_signal(); + init_stream(); + init_log_stream(); + init_event_stream(); + init_p_retry2(); + init_async_caller2(); + init_root_listener(); + init_utils4(); + init_zod2(); + init_graph(); + init_wrappers(); + init_iter(); + init_traceable2(); + init_v3(); + Runnable = class extends Serializable { + lc_runnable = true; + name; + getName(suffix) { + const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; + return suffix ? `${name}${suffix}` : name; } - get lc_namespace() { - return ["langchain_core", "vectorstores"]; + withRetry(fields) { + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); } - vectorStore; - k = 4; - searchType = "similarity"; - searchKwargs; - filter; - _vectorstoreType() { - return this.vectorStore._vectorstoreType(); + withConfig(config3) { + return new RunnableBinding({ + bound: this, + config: config3, + kwargs: {} + }); } - constructor(fields) { - super(fields); - this.vectorStore = fields.vectorStore; - this.k = fields.k ?? this.k; - this.searchType = fields.searchType ?? this.searchType; - this.filter = fields.filter; - if (fields.searchType === "mmr") - this.searchKwargs = fields.searchKwargs; + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + return new RunnableWithFallbacks({ + runnable: this, + fallbacks + }); } - async _getRelevantDocuments(query3, runManager) { - if (this.searchType === "mmr") { - if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") - throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); - return this.vectorStore.maxMarginalRelevanceSearch(query3, { - k: this.k, - filter: this.filter, - ...this.searchKwargs - }, runManager?.getChild("vectorstore")); + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && options.length !== length) + throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + if (Array.isArray(options)) + return options.map(ensureConfig); + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); } - return this.vectorStore.similaritySearch(query3, this.k, this.filter, runManager?.getChild("vectorstore")); - } - async addDocuments(documents, options) { - return this.vectorStore.addDocuments(documents, options); - } - }; - VectorStore = class extends Serializable { - lc_namespace = [ - "langchain", - "vectorstores", - this._vectorstoreType() - ]; - embeddings; - constructor(embeddings, dbConfig) { - super(dbConfig); - this.embeddings = embeddings; - } - async delete(_params) { - throw new Error("Not implemented."); - } - async similaritySearch(query3, k = 4, filter = undefined, _callbacks = undefined) { - return (await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query3), k, filter)).map((result) => result[0]); + return Array.from({ length }, () => ensureConfig(options)); } - async similaritySearchWithScore(query3, k = 4, filter = undefined, _callbacks = undefined) { - return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query3), k, filter); + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const caller = new AsyncCaller2({ + maxConcurrency: configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency, + onFailedAttempt: (e) => { + throw e; + } + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + return await this.invoke(input, configList[i]); + } catch (e) { + if (batchOptions?.returnExceptions) + return e; + throw e; + } + })); + return Promise.all(batchCalls); } - static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + async* _streamIterator(input, options) { + yield this.invoke(input, options); } - static fromDocuments(_docs, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + async stream(input, options) { + const config3 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this._streamIterator(input, config3), + config: config3 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } - asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { - if (typeof kOrFields === "number") - return new VectorStoreRetriever({ - vectorStore: this, - k: kOrFields, - filter, - tags: [...tags ?? [], this._vectorstoreType()], - metadata, - verbose, - callbacks + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === undefined) + runnableConfig = ensureConfig(options); + else + runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal }); - else { - const params = { - vectorStore: this, - k: kOrFields?.k, - filter: kOrFields?.filter, - tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], - metadata: kOrFields?.metadata, - verbose: kOrFields?.verbose, - callbacks: kOrFields?.callbacks, - searchType: kOrFields?.searchType - }; - if (kOrFields?.searchType === "mmr") - return new VectorStoreRetriever({ - ...params, - searchKwargs: kOrFields.searchKwargs - }); - return new VectorStoreRetriever({ ...params }); - } - } - }; - SaveableVectorStore = class extends VectorStore { - static load(_directory, _embeddings) { - throw new Error("Not implemented"); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/chat_models.js -var FakeChatModel, FakeStreamingChatModel, FakeListChatModel; -var init_chat_models2 = __esm(() => { - init_ai(); - init_outputs(); - init_json_schema2(); - init_base4(); - init_messages(); - init_chat_models(); - FakeChatModel = class extends BaseChatModel { - _combineLLMOutput() { - return []; - } - _llmType() { - return "fake"; + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; } - async _generate(messages, options, runManager) { - if (options?.stop?.length) - return { generations: [{ - message: new AIMessage(options.stop[0]), - text: options.stop[0] - }] }; - const text = messages.map((m) => { - if (typeof m.content === "string") - return m.content; - return JSON.stringify(m.content, null, 2); - }).join(` -`); - await runManager?.handleLLMNewToken(text); - return { - generations: [{ - message: new AIMessage(text), - text - }], - llmOutput: {} - }; + async _callWithConfig(func, input, options) { + const config3 = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config3))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config3.runId, config3?.runType, undefined, undefined, config3?.runName ?? this.getName()); + delete config3.runId; + let output; + try { + output = await raceWithSignal(func.call(this, input, config3, runManager), config3.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict2(output, "output")); + return output; } - }; - FakeStreamingChatModel = class FakeStreamingChatModel2 extends BaseChatModel { - sleep = 50; - responses = []; - chunks = []; - toolStyle = "openai"; - thrownErrorString; - tools = []; - constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString, ...rest }) { - super(rest); - this.sleep = sleep; - this.responses = responses; - this.chunks = chunks; - this.toolStyle = toolStyle; - this.thrownErrorString = thrownErrorString; + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + outputs = await raceWithSignal(func.call(this, inputs, optionsList, runManagers, batchOptions), optionsList?.[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(outputs, "output")))); + return outputs; } - _llmType() { - return "fake"; + _concatOutputChunks(first, second) { + return concat(first, second); } - bindTools(tools) { - const merged = [...this.tools, ...tools]; - const toolDicts = merged.map((t) => { - switch (this.toolStyle) { - case "openai": - return { - type: "function", - function: { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) + async* _transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config3 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config3); + const outerThis = this; + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) + if (finalInput === undefined) + finalInput = chunk; + else + try { + finalInput = outerThis._concatOutputChunks(finalInput, chunk); + } catch { + finalInput = undefined; + finalInputSupported = false; + } + yield chunk; + } + } + let runManager; + try { + const pipe2 = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config3.runId, config3.runType, undefined, undefined, config3.runName ?? this.getName(), undefined, { lc_defers_inputs: true }), config3.signal, config3); + delete config3.runId; + runManager = pipe2.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe2.output; + if (streamEventsHandler !== undefined && runManager !== undefined) + iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== undefined && runManager !== undefined) + iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = undefined; + finalOutputSupported = false; } - }; - case "anthropic": - return { - name: t.name, - description: t.description, - input_schema: toJsonSchema(t.schema) - }; - case "bedrock": - return { toolSpec: { - name: t.name, - description: t.description, - inputSchema: toJsonSchema(t.schema) - } }; - case "google": - return { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - }; - default: - throw new Error(`Unsupported tool style: ${this.toolStyle}`); } + } catch (e) { + await runManager?.handleChainError(e, undefined, undefined, undefined, { inputs: _coerceToDict2(finalInput, "input") }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: _coerceToDict2(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph; + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: exports_external2.any() }); - const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; - const next = new FakeStreamingChatModel2({ - sleep: this.sleep, - responses: this.responses, - chunks: this.chunks, - toolStyle: this.toolStyle, - thrownErrorString: this.thrownErrorString + const runnableNode = graph.addNode(this); + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: exports_external2.any() }); - next.tools = merged; - return next.withConfig({ tools: wrapped }); - } - async _generate(messages, _options, _runManager) { - if (this.thrownErrorString) - throw new Error(this.thrownErrorString); - return { generations: [{ - text: "", - message: new AIMessage({ - content: this.responses?.[0]?.content ?? messages[0].content ?? "", - tool_calls: this.chunks?.[0]?.tool_calls - }) - }] }; + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; } - async* _streamResponseChunks(_messages, options, runManager) { - if (this.thrownErrorString) - throw new Error(this.thrownErrorString); - if (this.chunks?.length) { - for (const msgChunk of this.chunks) { - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: msgChunk.content, - tool_calls: msgChunk.tool_calls, - additional_kwargs: msgChunk.additional_kwargs ?? {} - }), - text: msgChunk.content?.toString() ?? "" - }); - if (options.signal?.aborted) - break; - yield cg; - await runManager?.handleLLMNewToken(msgChunk.content, undefined, undefined, undefined, undefined, { chunk: cg }); - } - return; - } - const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); - const text = typeof fallback.content === "string" ? fallback.content : ""; - for (const ch of text) { - await new Promise((r) => setTimeout(r, this.sleep)); - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ content: ch }), - text: ch - }); - if (options.signal?.aborted) - break; - yield cg; - await runManager?.handleLLMNewToken(ch, undefined, undefined, undefined, undefined, { chunk: cg }); - } + pipe(coerceable) { + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable) + }); } - }; - FakeListChatModel = class FakeListChatModel2 extends BaseChatModel { - static lc_name() { - return "FakeListChatModel"; + pick(keys) { + return this.pipe(new RunnablePick(keys)); } - lc_serializable = true; - responses; - i = 0; - sleep; - emitCustomEvent = false; - generationInfo; - tools = []; - toolStyle = "openai"; - constructor(params) { - super(params); - const { responses, sleep, emitCustomEvent, generationInfo } = params; - this.responses = responses; - this.sleep = sleep; - this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; - this.generationInfo = generationInfo; + assign(mapping) { + return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); } - _combineLLMOutput() { - return []; + async* transform(generator, options) { + let finalChunk; + for await (const chunk of generator) + if (finalChunk === undefined) + finalChunk = chunk; + else + finalChunk = this._concatOutputChunks(finalChunk, chunk); + yield* this._streamIterator(finalChunk, ensureConfig(options)); } - _llmType() { - return "fake-list"; + async* streamLog(input, options, streamOptions) { + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "original" + }); + const config3 = ensureConfig(options); + yield* this._streamLog(input, logStreamCallbackHandler, config3); } - async _generate(_messages, options, runManager) { - await this._sleepIfRequested(); - if (options?.thrownErrorString) - throw new Error(options.thrownErrorString); - if (this.emitCustomEvent) - await runManager?.handleCustomEvent("some_test_event", { someval: true }); - if (options?.stop?.length) - return { generations: [this._formatGeneration(options.stop[0])] }; + async* _streamLog(input, logStreamCallbackHandler, config3) { + const { callbacks } = config3; + if (callbacks === undefined) + config3.callbacks = [logStreamCallbackHandler]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat([logStreamCallbackHandler]); else { - const response = this._currentResponse(); - this._incrementResponse(); - return { - generations: [this._formatGeneration(response)], - llmOutput: {} - }; + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(logStreamCallbackHandler, true); + config3.callbacks = copiedCallbacks; } - } - _formatGeneration(text) { - return { - message: new AIMessage(text), - text - }; - } - async* _streamResponseChunks(_messages, options, runManager) { - const response = this._currentResponse(); - this._incrementResponse(); - if (this.emitCustomEvent) - await runManager?.handleCustomEvent("some_test_event", { someval: true }); - const responseChars = [...response]; - for (let i = 0;i < responseChars.length; i++) { - const text = responseChars[i]; - const isLastChunk = i === responseChars.length - 1; - await this._sleepIfRequested(); - if (options?.thrownErrorString) - throw new Error(options.thrownErrorString); - const chunk = this._createResponseChunk(text, isLastChunk ? this.generationInfo : undefined); - if (options.signal?.aborted) - break; - yield chunk; - runManager?.handleLLMNewToken(text); + const runnableStreamPromise = this.stream(input, config3); + async function consumeRunnableStream() { + try { + const runnableStream = await runnableStreamPromise; + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ ops: [{ + op: "add", + path: "/streamed_output/-", + value: chunk + }] }); + await logStreamCallbackHandler.writer.write(patch); + } + } finally { + await logStreamCallbackHandler.writer.close(); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + try { + for await (const log of logStreamCallbackHandler) + yield log; + } finally { + await runnableStreamConsumePromise; } } - async _sleepIfRequested() { - if (this.sleep !== undefined) - await this._sleep(); + streamEvents(input, options, streamOptions) { + let stream2; + if (options.version === "v1") + stream2 = this._streamEventsV1(input, options, streamOptions); + else if (options.version === "v2") + stream2 = this._streamEventsV2(input, options, streamOptions); + else + throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + if (options.encoding === "text/event-stream") + return convertToHttpEventStream(stream2); + else + return IterableReadableStream.fromAsyncGenerator(stream2); } - async _sleep() { - return new Promise((resolve2) => { - setTimeout(() => resolve2(), this.sleep); + async* _streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false }); + const config3 = ensureConfig(options); + const runId = config3.runId ?? v72(); + config3.runId = runId; + const callbacks = config3.callbacks; + if (callbacks === undefined) + config3.callbacks = [eventStreamer]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat(eventStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + config3.callbacks = copiedCallbacks; + } + const abortController = new AbortController; + const outerThis = this; + async function consumeRunnableStream() { + let signal; + try { + if (config3.signal) + if ("any" in AbortSignal) + signal = AbortSignal.any([abortController.signal, config3.signal]); + else { + const composed = new AbortController; + config3.signal.addEventListener("abort", () => composed.abort(), { once: true }); + abortController.signal.addEventListener("abort", () => composed.abort(), { once: true }); + signal = composed.signal; + } + else + signal = abortController.signal; + const runnableStream = await outerThis.stream(input, { + ...config3, + signal + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + for await (const _ of tappedStream) + if (abortController.signal.aborted) + break; + } finally { + await eventStreamer.finish(); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; + try { + for await (const event of eventStreamer) { + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; + } + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + if (event.data?.input) + delete event.data.input; + } + yield event; + } + } finally { + abortController.abort(); + await runnableStreamConsumePromise; + } } - _createResponseChunk(text, generationInfo) { - return new ChatGenerationChunk({ - message: new AIMessageChunk({ content: text }), - text, - generationInfo + async* _streamEventsV1(input, options, streamOptions) { + let runLog; + let hasEncounteredStartEvent = false; + const config3 = ensureConfig(options); + const rootTags = config3.tags ?? []; + const rootMetadata = config3.metadata ?? {}; + const rootName = config3.runName ?? this.getName(); + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "streaming_events" }); - } - _currentResponse() { - return this.responses[this.i]; - } - _incrementResponse() { - if (this.i < this.responses.length - 1) - this.i += 1; - else - this.i = 0; - } - bindTools(tools) { - const merged = [...this.tools, ...tools]; - const toolDicts = merged.map((t) => { - switch (this.toolStyle) { - case "openai": - return { - type: "function", - function: { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - } - }; - case "anthropic": - return { - name: t.name, - description: t.description, - input_schema: toJsonSchema(t.schema) - }; - case "bedrock": - return { toolSpec: { - name: t.name, - description: t.description, - inputSchema: toJsonSchema(t.schema) - } }; - case "google": - return { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - }; - default: - throw new Error(`Unsupported tool style: ${this.toolStyle}`); + const rootEventFilter = new _RootEventFilter({ ...streamOptions }); + const logStream = this._streamLog(input, logStreamCallbackHandler, config3); + for await (const log of logStream) { + if (!runLog) + runLog = RunLog.fromRunLogPatch(log); + else + runLog = runLog.concat(log); + if (runLog.state === undefined) + throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + if (!hasEncounteredStartEvent) { + hasEncounteredStartEvent = true; + const state3 = { ...runLog.state }; + const event = { + run_id: state3.id, + event: `on_${state3.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { input } + }; + if (rootEventFilter.includeEvent(event, state3.type)) + yield event; } - }); - const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; - const next = new FakeListChatModel2({ - responses: this.responses, - sleep: this.sleep, - emitCustomEvent: this.emitCustomEvent, - generationInfo: this.generationInfo - }); - next.tools = merged; - next.toolStyle = this.toolStyle; - next.i = this.i; - return next.withConfig({ tools: wrapped }); + const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); + const dedupedPaths = [...new Set(paths)]; + for (const path2 of dedupedPaths) { + let eventType; + let data = {}; + const logEntry = runLog.state.logs[path2]; + if (logEntry.end_time === undefined) + if (logEntry.streamed_output.length > 0) + eventType = "stream"; + else + eventType = "start"; + else + eventType = "end"; + if (eventType === "start") { + if (logEntry.inputs !== undefined) + data.input = logEntry.inputs; + } else if (eventType === "end") { + if (logEntry.inputs !== undefined) + data.input = logEntry.inputs; + data.output = logEntry.final_output; + } else if (eventType === "stream") { + const chunkCount = logEntry.streamed_output.length; + if (chunkCount !== 1) + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + data = { chunk: logEntry.streamed_output[0] }; + logEntry.streamed_output = []; + } + yield { + event: `on_${logEntry.type}_${eventType}`, + name: logEntry.name, + run_id: logEntry.id, + tags: logEntry.tags, + metadata: logEntry.metadata, + data + }; + } + const { state: state2 } = runLog; + if (state2.streamed_output.length > 0) { + const chunkCount = state2.streamed_output.length; + if (chunkCount !== 1) + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state2.name}"`); + const data = { chunk: state2.streamed_output[0] }; + state2.streamed_output = []; + const event = { + event: `on_${state2.type}_stream`, + run_id: state2.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data + }; + if (rootEventFilter.includeEvent(event, state2.type)) + yield event; + } + } + const state = runLog?.state; + if (state !== undefined) { + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { output: state.final_output } + }; + if (rootEventFilter.includeEvent(event, state.type)) + yield event; + } } - withStructuredOutput(_params, _config) { - return RunnableLambda.from(async (input) => { - const message = await this.invoke(input); - if (message.tool_calls?.[0]?.args) - return message.tool_calls[0].args; - if (typeof message.content === "string") - return JSON.parse(message.content); - throw new Error("No structured output found"); + static isRunnable(thing) { + return isRunnableInterface(thing); + } + withListeners({ onStart, onEnd, onError: onError2 }) { + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [(config3) => ({ callbacks: [new RootListenersTracer({ + config: config3, + onStart, + onEnd, + onError: onError2 + })] })] }); } + asTool(fields) { + return convertRunnableToTool(this, fields); + } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/embeddings.js -var SyntheticEmbeddings, FakeEmbeddings; -var init_embeddings2 = __esm(() => { - init_embeddings(); - SyntheticEmbeddings = class extends Embeddings { - vectorSize; - constructor(params) { - super(params ?? {}); - this.vectorSize = params?.vectorSize ?? 4; + RunnableBinding = class RunnableBinding2 extends Runnable { + static lc_name() { + return "RunnableBinding"; } - async embedDocuments(documents) { - return Promise.all(documents.map((doc2) => this.embedQuery(doc2))); + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + bound; + config; + kwargs; + configFactories; + constructor(fields) { + super(fields); + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.configFactories; } - async embedQuery(document2) { - let doc2 = document2; - doc2 = doc2.toLowerCase().replaceAll(/[^a-z ]/g, ""); - const padMod = doc2.length % this.vectorSize; - const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; - const padSize = doc2.length + padGapSize; - doc2 = doc2.padEnd(padSize, " "); - const chunkSize = doc2.length / this.vectorSize; - const docChunk = []; - for (let co = 0;co < doc2.length; co += chunkSize) - docChunk.push(doc2.slice(co, co + chunkSize)); - return docChunk.map((s) => { - let sum = 0; - for (let co = 0;co < s.length; co += 1) - sum += s === " " ? 0 : s.charCodeAt(co); - return sum % 26 / 26; + getName(suffix) { + return this.bound.getName(suffix); + } + async _mergeConfig(...options) { + const config3 = mergeConfigs(this.config, ...options); + return mergeConfigs(config3, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config3))) : []); + } + withConfig(config3) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { + ...this.config, + ...config3 + } }); } - }; - FakeEmbeddings = class extends Embeddings { - constructor(params) { - super(params ?? {}); + withRetry(fields) { + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); } - embedDocuments(documents) { - return Promise.resolve(documents.map(() => [ - 0.1, - 0.2, - 0.3, - 0.4 - ])); + async invoke(input, options) { + return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); } - embedQuery(_) { - return Promise.resolve([ - 0.1, - 0.2, - 0.3, - 0.4 - ]); + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); + } + _concatOutputChunks(first, second) { + return this.bound._concatOutputChunks(first, second); + } + async* _streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async* transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + streamEvents(input, options, streamOptions) { + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), + version: options.version + }, streamOptions); + }; + return IterableReadableStream.fromAsyncGenerator(generator()); + } + static isRunnableBinding(thing) { + return thing.bound && Runnable.isRunnable(thing.bound); + } + withListeners({ onStart, onEnd, onError: onError2 }) { + return new RunnableBinding2({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + configFactories: [(config3) => ({ callbacks: [new RootListenersTracer({ + config: config3, + onStart, + onEnd, + onError: onError2 + })] })] + }); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/llms.js -var FakeLLM, FakeStreamingLLM; -var init_llms2 = __esm(() => { - init_llms(); - FakeLLM = class extends LLM { - response; - thrownErrorString; + RunnableEach = class RunnableEach2 extends Runnable { + static lc_name() { + return "RunnableEach"; + } + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + bound; constructor(fields) { super(fields); - this.response = fields.response; - this.thrownErrorString = fields.thrownErrorString; + this.bound = fields.bound; } - _llmType() { - return "fake"; + async invoke(inputs, config3) { + return this._callWithConfig(this._invoke.bind(this), inputs, config3); } - async _call(prompt, _options, runManager) { - if (this.thrownErrorString) - throw new Error(this.thrownErrorString); - const response = this.response ?? prompt; - await runManager?.handleLLMNewToken(response); - return response; + async _invoke(inputs, config3, runManager) { + return this.bound.batch(inputs, patchConfig(config3, { callbacks: runManager?.getChild() })); + } + withListeners({ onStart, onEnd, onError: onError2 }) { + return new RunnableEach2({ bound: this.bound.withListeners({ + onStart, + onEnd, + onError: onError2 + }) }); } }; - FakeStreamingLLM = class extends LLM { - sleep = 50; - responses; - thrownErrorString; + RunnableRetry = class extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + lc_namespace = ["langchain_core", "runnables"]; + maxAttemptNumber = 3; + onFailedAttempt = () => {}; constructor(fields) { super(fields); - this.sleep = fields.sleep ?? this.sleep; - this.responses = fields.responses; - this.thrownErrorString = fields.thrownErrorString; + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; } - _llmType() { - return "fake"; + _patchConfigForRetry(attempt, config3, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; + return patchConfig(config3, { callbacks: runManager?.getChild(tag) }); } - async _call(prompt) { - if (this.thrownErrorString) - throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - return response ?? prompt; + async _invoke(input, config3, runManager) { + return pRetry2((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config3, runManager)), { + onFailedAttempt: ({ error: error90 }) => this.onFailedAttempt(error90, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); } - async* _streamResponseChunks(input, _options, runManager) { - if (this.thrownErrorString) - throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - for (const c of response ?? input) { - await new Promise((resolve2) => setTimeout(resolve2, this.sleep)); - yield { - text: c, - generationInfo: {} - }; - await runManager?.handleLLMNewToken(c); + async invoke(input, config3) { + return this._callWithConfig(this._invoke.bind(this), input, config3); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await pRetry2(async (attemptNumber) => { + const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === undefined || resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true + }); + let firstException; + for (let i = 0;i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + if (result instanceof Error) { + if (firstException === undefined) { + firstException = result; + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) + throw firstException; + return results; + }, { + onFailedAttempt: ({ error: error90 }) => this.onFailedAttempt(error90, error90.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } catch (e) { + if (batchOptions?.returnExceptions !== true) + throw e; } + return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); + } + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/message_history.js -var FakeChatMessageHistory, FakeListChatMessageHistory, FakeTracer; -var init_message_history = __esm(() => { - init_ai(); - init_human(); - init_base3(); - init_messages(); - init_chat_history(); - FakeChatMessageHistory = class extends BaseChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); + RunnableSequence = class RunnableSequence2 extends Runnable { + static lc_name() { + return "RunnableSequence"; } - async getMessages() { - return this.messages; + first; + middle = []; + last; + omitSequenceTags = false; + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + constructor(fields) { + super(fields); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; } - async addMessage(message) { - this.messages.push(message); + get steps() { + return [ + this.first, + ...this.middle, + this.last + ]; } - async addUserMessage(message) { - this.messages.push(new HumanMessage(message)); + async invoke(input, options) { + const config3 = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config3))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config3.runId, undefined, undefined, undefined, config3?.runName); + delete config3.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0;i < initialSteps.length; i += 1) + nextStepInput = await raceWithSignal(initialSteps[i].invoke(nextStepInput, patchConfig(config3, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`) })), config3.signal); + if (config3.signal?.aborted) + throw getAbortSignalError(config3.signal); + finalOutput = await this.last.invoke(nextStepInput, patchConfig(config3, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`) })); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); + return finalOutput; } - async addAIMessage(message) { - this.messages.push(new AIMessage(message)); + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let nextStepInputs = inputs; + try { + for (let i = 0;i < this.steps.length; i += 1) + nextStepInputs = await raceWithSignal(this.steps[i].batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); + return patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions), configList[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(_coerceToDict2(nextStepInputs, "output")))); + return nextStepInputs; } - async clear() { - this.messages = []; + _concatOutputChunks(first, second) { + return this.last._concatOutputChunks(first, second); } - }; - FakeListChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); + async* _streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId, ...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); + const steps = [ + this.first, + ...this.middle, + this.last + ]; + let concatSupported = true; + let finalOutput; + async function* inputGenerator() { + yield input; + } + try { + let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`) })); + for (let i = 1;i < steps.length; i += 1) + finalGenerator = await steps[i].transform(finalGenerator, patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`) })); + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = undefined; + concatSupported = false; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict2(finalOutput, "output")); } - async addMessage(message) { - this.messages.push(message); + getGraph(config3) { + const graph = new Graph; + let currentLastNode = null; + this.steps.forEach((step, index) => { + const stepGraph = step.getGraph(config3); + if (index !== 0) + stepGraph.trimFirstNode(); + if (index !== this.steps.length - 1) + stepGraph.trimLastNode(); + graph.extend(stepGraph); + const stepFirstNode = stepGraph.firstNode(); + if (!stepFirstNode) + throw new Error(`Runnable ${step} has no first node`); + if (currentLastNode) + graph.addEdge(currentLastNode, stepFirstNode); + currentLastNode = stepGraph.lastNode(); + }); + return graph; } - async getMessages() { - return this.messages; + pipe(coerceable) { + if (RunnableSequence2.isRunnableSequence(coerceable)) + return new RunnableSequence2({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle + ]), + last: coerceable.last, + name: this.name ?? coerceable.name + }); + else + return new RunnableSequence2({ + first: this.first, + middle: [...this.middle, this.last], + last: _coerceToRunnable(coerceable), + name: this.name + }); } - }; - FakeTracer = class extends BaseTracer { - name = "fake_tracer"; - runs = []; - constructor() { - super(); + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && Runnable.isRunnable(thing); } - persistRun(run2) { - this.runs.push(run2); - return Promise.resolve(); + static from([first, ...runnables], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") + extra.name = nameOrFields; + else if (nameOrFields !== undefined) + extra = nameOrFields; + return new RunnableSequence2({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]) + }); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/output_parsers.js -var FakeSplitIntoListParser; -var init_output_parsers2 = __esm(() => { - init_base6(); - FakeSplitIntoListParser = class extends BaseOutputParser { - lc_namespace = ["tests", "fake"]; - getFormatInstructions() { - return ""; + RunnableMap = class RunnableMap2 extends Runnable { + static lc_name() { + return "RunnableMap"; } - async parse(text) { - return text.split(",").map((value) => value.trim()); + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + steps; + getStepsKeys() { + return Object.keys(this.steps); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/retrievers.js -var FakeRetriever; -var init_retrievers2 = __esm(() => { - init_document(); - init_retrievers(); - FakeRetriever = class extends BaseRetriever { - lc_namespace = ["test", "fake"]; - output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; constructor(fields) { - super(); - this.output = fields?.output ?? this.output; + super(fields); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) + this.steps[key] = _coerceToRunnable(value); } - async _getRelevantDocuments(_query) { - return this.output; + static from(steps) { + return new RunnableMap2({ steps }); + } + async invoke(input, options) { + const config3 = ensureConfig(options); + const runManager = await (await getCallbackManagerForConfig(config3))?.handleChainStart(this.toJSON(), { input }, config3.runId, undefined, undefined, undefined, config3?.runName); + delete config3.runId; + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, patchConfig(config3, { callbacks: runManager?.getChild(`map:key:${key}`) })); + }); + await raceWithSignal(Promise.all(promises), config3.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; + } + async* _transform(generator, runManager, options) { + const steps = { ...this.steps }; + const inputCopies = atee(generator, Object.keys(steps).length); + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); + return [key, gen.next().then((result) => ({ + key, + gen, + result + }))]; + })); + while (tasks.size) { + const { key, result, gen } = await raceWithSignal(Promise.race(tasks.values()), options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result2) => ({ + key, + gen, + result: result2 + }))); + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config3 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config3), + config: config3 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/runnables.js -var FakeRunnable; -var init_runnables2 = __esm(() => { - init_base4(); - FakeRunnable = class extends Runnable { - lc_namespace = ["tests", "fake"]; - returnOptions; + RunnableTraceable = class RunnableTraceable2 extends Runnable { + lc_serializable = false; + lc_namespace = ["langchain_core", "runnables"]; + func; constructor(fields) { super(fields); - this.returnOptions = fields.returnOptions; + if (!isTraceableFunction(fields.func)) + throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + this.func = fields.func; } async invoke(input, options) { - if (this.returnOptions) - return options ?? {}; - return { input }; + const [config3] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config3); + return raceWithSignal(this.func(patchConfig(config3, { callbacks }), input), config3?.signal); + } + async* _streamIterator(input, options) { + const [config3] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (isAsyncIterable(result)) { + for await (const item of result) { + config3?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config3?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) + break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new RunnableTraceable2({ func }); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/tools.js -var FakeTool; -var init_tools3 = __esm(() => { - init_tools2(); - FakeTool = class extends StructuredTool { - name; - description; - schema; + RunnableLambda = class RunnableLambda2 extends Runnable { + static lc_name() { + return "RunnableLambda"; + } + lc_namespace = ["langchain_core", "runnables"]; + func; constructor(fields) { + if (isTraceableFunction(fields.func)) + return RunnableTraceable.from(fields.func); super(fields); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; + assertNonTraceableFunction(fields.func); + this.func = fields.func; } - async _call(arg, _runManager) { - return JSON.stringify(arg); + static from(func) { + return new RunnableLambda2({ func }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/tracers.js -var SingleRunExtractor; -var init_tracers = __esm(() => { - init_base3(); - SingleRunExtractor = class extends BaseTracer { - runPromiseResolver; - runPromise; - name = "single_run_extractor"; - constructor() { - super(); - this.runPromise = new Promise((extract) => { - this.runPromiseResolver = extract; + async _invoke(input, config3, runManager) { + return new Promise((resolve2, reject) => { + const childConfig = patchConfig(config3, { + callbacks: runManager?.getChild(), + recursionLimit: (config3?.recursionLimit ?? 25) - 1 + }); + AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { ...childConfig }); + if (output && Runnable.isRunnable(output)) { + if (config3?.recursionLimit === 0) + throw new Error("Recursion limit reached."); + output = await output.invoke(input, { + ...childConfig, + recursionLimit: (childConfig.recursionLimit ?? 25) - 1 + }); + } else if (isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config3?.signal?.throwIfAborted(); + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config3?.signal?.throwIfAborted(); + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } + resolve2(output); + } catch (e) { + reject(e); + } + }); }); } - async persistRun(run2) { - this.runPromiseResolver(run2); + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); } - async extract() { - return this.runPromise; + async* _transform(generator, runManager, config3) { + let finalChunk; + for await (const chunk of generator) + if (finalChunk === undefined) + finalChunk = chunk; + else + try { + finalChunk = this._concatOutputChunks(finalChunk, chunk); + } catch { + finalChunk = chunk; + } + const childConfig = patchConfig(config3, { + callbacks: runManager?.getChild(), + recursionLimit: (config3?.recursionLimit ?? 25) - 1 + }); + const output = await new Promise((resolve2, reject) => { + AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + resolve2(await this.func(finalChunk, { + ...childConfig, + config: childConfig + })); + } catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config3?.recursionLimit === 0) + throw new Error("Recursion limit reached."); + const stream2 = await output.stream(finalChunk, childConfig); + for await (const chunk of stream2) + yield chunk; + } else if (isAsyncIterable(output)) + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config3?.signal?.throwIfAborted(); + yield chunk; + } + else if (isIterableIterator(output)) + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config3?.signal?.throwIfAborted(); + yield chunk; + } + else + yield output; + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config3 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config3), + config: config3 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/vectorstores.js -var FakeVectorStore; -var init_vectorstores2 = __esm(() => { - init_document(); - init_similarities(); - init_vectorstores(); - FakeVectorStore = class FakeVectorStore2 extends VectorStore { - memoryVectors = []; - similarity; - _vectorstoreType() { - return "memory"; + RunnableParallel = class extends RunnableMap { + }; + RunnableWithFallbacks = class extends Runnable { + static lc_name() { + return "RunnableWithFallbacks"; } - constructor(embeddings, { similarity, ...rest } = {}) { - super(embeddings, rest); - this.similarity = similarity ?? cosine; + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnable; + fallbacks; + constructor(fields) { + super(fields); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; } - async addDocuments(documents) { - const texts = documents.map(({ pageContent }) => pageContent); - return this.addVectors(await this.embeddings.embedDocuments(texts), documents); + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) + yield fallback; } - async addVectors(vectors, documents) { - const memoryVectors = vectors.map((embedding, idx) => ({ - content: documents[idx].pageContent, - embedding, - metadata: documents[idx].metadata + async invoke(input, options) { + const config3 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config3); + const { runId, ...otherConfigFields } = config3; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + return await AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config3?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(_coerceToDict2(output, "output")); + return output; + } catch (e) { + if (firstError === undefined) + firstError = e; + } + } + if (firstError === undefined) + throw new Error("No error stored at end of fallback."); + await runManager?.handleChainError(firstError); + throw firstError; + }); + } + async* _streamIterator(input, options) { + const config3 = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config3); + const { runId, ...otherConfigFields } = config3; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + let firstError; + let stream2; + for (const runnable of this.runnables()) { + config3?.signal?.throwIfAborted(); + const childConfig = patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + try { + stream2 = consumeAsyncIterableInContext(childConfig, await runnable.stream(input, childConfig)); + break; + } catch (e) { + if (firstError === undefined) + firstError = e; + } + } + if (stream2 === undefined) { + const error90 = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error90); + throw error90; + } + let output; + try { + for await (const chunk of stream2) { + yield chunk; + try { + output = output === undefined ? output : this._concatOutputChunks(output, chunk); + } catch { + output = undefined; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(_coerceToDict2(output, "output")); + } + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) + throw new Error("Not implemented."); + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config3) => getCallbackManagerForConfig(config3))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), _coerceToDict2(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; })); - this.memoryVectors = this.memoryVectors.concat(memoryVectors); + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(_coerceToDict2(outputs[i], "output")))); + return outputs; + } catch (e) { + if (firstError === undefined) + firstError = e; + } + } + if (!firstError) + throw new Error("No error stored at end of fallbacks."); + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; } - async similaritySearchVectorWithScore(query3, k, filter) { - const filterFunction = (memoryVector) => { - if (!filter) - return true; - return filter(new Document({ - metadata: memoryVector.metadata, - pageContent: memoryVector.content - })); + }; + RunnableAssign = class extends Runnable { + static lc_name() { + return "RunnableAssign"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + mapper; + constructor(fields) { + if (fields instanceof RunnableMap) + fields = { mapper: fields }; + super(fields); + this.mapper = fields.mapper; + } + async invoke(input, options) { + const mapperResult = await this.mapper.invoke(input, options); + return { + ...input, + ...mapperResult }; - const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); - return filteredMemoryVectors.map((vector, index2) => ({ - similarity: this.similarity(query3, vector.embedding), - index: index2 - })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k).map((search) => [new Document({ - metadata: filteredMemoryVectors[search.index].metadata, - pageContent: filteredMemoryVectors[search.index].content - }), search.similarity]); } - static async fromTexts(texts, metadatas, embeddings, dbConfig) { - const docs = []; - for (let i = 0;i < texts.length; i += 1) { - const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; - const newDoc = new Document({ - pageContent: texts[i], - metadata - }); - docs.push(newDoc); + async* _transform(generator, runManager, options) { + const mapperKeys = this.mapper.getStepsKeys(); + const [forPassthrough, forMapper] = atee(generator); + const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); + const firstMapperChunkPromise = mapperOutput.next(); + for await (const chunk of forPassthrough) { + if (typeof chunk !== "object" || Array.isArray(chunk)) + throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); + if (Object.keys(filtered).length > 0) + yield filtered; } - return FakeVectorStore2.fromDocuments(docs, embeddings, dbConfig); + yield (await firstMapperChunkPromise).value; + for await (const chunk of mapperOutput) + yield chunk; } - static async fromDocuments(docs, embeddings, dbConfig) { - const instance = new this(embeddings, dbConfig); - await instance.addDocuments(docs); - return instance; + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } - static async fromExistingIndex(embeddings, dbConfig) { - return new this(embeddings, dbConfig); + async stream(input, options) { + async function* generator() { + yield input; + } + const config3 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config3), + config: config3 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } }; -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/utils/testing/index.js -var testing_exports2; -var init_testing2 = __esm(() => { - init_runtime2(); - init_chat_models2(); - init_embeddings2(); - init_llms2(); - init_message_history(); - init_output_parsers2(); - init_retrievers2(); - init_runnables2(); - init_tools3(); - init_tracers(); - init_vectorstores2(); - testing_exports2 = /* @__PURE__ */ __exportAll({ - FakeChatMessageHistory: () => FakeChatMessageHistory, - FakeChatModel: () => FakeChatModel, - FakeEmbeddings: () => FakeEmbeddings, - FakeLLM: () => FakeLLM, - FakeListChatMessageHistory: () => FakeListChatMessageHistory, - FakeListChatModel: () => FakeListChatModel, - FakeRetriever: () => FakeRetriever, - FakeRunnable: () => FakeRunnable, - FakeSplitIntoListParser: () => FakeSplitIntoListParser, - FakeStreamingChatModel: () => FakeStreamingChatModel, - FakeStreamingLLM: () => FakeStreamingLLM, - FakeTool: () => FakeTool, - FakeTracer: () => FakeTracer, - FakeVectorStore: () => FakeVectorStore, - SingleRunExtractor: () => SingleRunExtractor, - SyntheticEmbeddings: () => SyntheticEmbeddings - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/import_map.js -var import_map_exports; -var init_import_map = __esm(() => { - init_runtime2(); - init_dist2(); - init_agents(); - init_hash2(); - init_errors3(); - init_serializable(); - init_tool(); - init_caches(); - init_uuid(); - init_env(); - init_base2(); - init_base3(); - init_console(); - init_tracer_langchain(); - init_promises(); - init_manager(); - init_singletons(); - init_stream(); - init_log_stream(); - init_outputs(); - init_async_caller2(); - init_standard_schema(); - init_json_schema2(); - init_graph(); - init_messages(); - init_chat_history(); - init_documents(); - init_base7(); - init_langsmith2(); - init_embeddings(); - init_example_selectors(); - init_indexing(); - init_prompt_values(); - init_tiktoken(); - init_base5(); - init_runnables(); - init_json_patch(); - init_output_parsers(); - init_types3(); - init_structured_output(); - init_stream2(); - init_compat2(); - init_chat_models(); - init_event(); - init_llms(); - init_profile(); - init_memory(); - init_openai_functions(); - init_openai_tools(); - init_prompts2(); - init_document_compressors(); - init_retrievers(); - init_stores(); - init_structured_query(); - init_testing(); - init_tools2(); - init_run_collector(); - init_stream3(); - init_chunk_array(); - init_context2(); - init_event_source_parse(); - init_format3(); - init_function_calling(); - init_math(); - init_ssrf(); - init_vectorstores(); - init_testing2(); - import_map_exports = /* @__PURE__ */ __exportAll({ - agents: () => agents_exports, - caches: () => caches_exports, - callbacks__base: () => base_exports, - callbacks__manager: () => manager_exports, - callbacks__promises: () => promises_exports, - chat_history: () => chat_history_exports, - document_loaders__base: () => base_exports4, - document_loaders__langsmith: () => langsmith_exports, - documents: () => documents_exports, - embeddings: () => embeddings_exports, - errors: () => errors_exports, - example_selectors: () => example_selectors_exports, - index: () => src_exports, - indexing: () => indexing_exports, - language_models__base: () => base_exports3, - language_models__chat_models: () => chat_models_exports, - language_models__compat: () => compat_exports, - language_models__event: () => event_exports, - language_models__llms: () => llms_exports, - language_models__profile: () => profile_exports, - language_models__stream: () => stream_exports2, - language_models__structured_output: () => structured_output_exports, - load__serializable: () => serializable_exports, - memory: () => memory_exports, - messages: () => messages_exports, - messages__tool: () => tool_exports, - output_parsers: () => output_parsers_exports, - output_parsers__openai_functions: () => openai_functions_exports, - output_parsers__openai_tools: () => openai_tools_exports, - outputs: () => outputs_exports, - prompt_values: () => prompt_values_exports, - prompts: () => prompts_exports, - retrievers: () => retrievers_exports, - retrievers__document_compressors: () => document_compressors_exports, - runnables: () => runnables_exports, - runnables__graph: () => graph_exports, - singletons: () => singletons_exports, - stores: () => stores_exports, - structured_query: () => structured_query_exports, - testing: () => testing_exports, - tools: () => tools_exports, - tracers__base: () => base_exports2, - tracers__console: () => console_exports, - tracers__log_stream: () => log_stream_exports, - tracers__run_collector: () => run_collector_exports, - tracers__tracer_langchain: () => tracer_langchain_exports, - types__stream: () => stream_exports3, - utils__async_caller: () => async_caller_exports, - utils__chunk_array: () => chunk_array_exports, - utils__context: () => context_exports, - utils__env: () => env_exports, - utils__event_source_parse: () => event_source_parse_exports, - utils__format: () => format_exports, - utils__function_calling: () => function_calling_exports, - utils__hash: () => hash_exports, - utils__json_patch: () => json_patch_exports, - utils__json_schema: () => json_schema_exports, - utils__math: () => math_exports, - utils__ssrf: () => ssrf_exports, - utils__standard_schema: () => standard_schema_exports, - utils__stream: () => stream_exports, - utils__testing: () => testing_exports2, - utils__tiktoken: () => tiktoken_exports, - utils__types: () => types_exports, - utils__uuid: () => uuid_exports, - vectorstores: () => vectorstores_exports - }); -}); - -// ../../node_modules/.pnpm/@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_m7mvfgwurlnn5gsw4fw4cz3vfa/node_modules/@langchain/core/dist/load/index.js -function combineAliasesAndInvert(constructor) { - const aliases = {}; - for (let current = constructor;current && current.prototype; current = Object.getPrototypeOf(current)) - Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); - return Object.entries(aliases).reduce((acc, [key, value]) => { - acc[value] = key; - return acc; - }, {}); -} -async function reviver(value) { - const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path2, depth, maxDepth } = this; - const pathStr = path2.join("."); - if (depth > maxDepth) - throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`); - if (typeof value !== "object" || value == null) - return value; - if (Array.isArray(value)) - return Promise.all(value.map((v, i) => reviver.call({ - ...this, - path: [...path2, `${i}`], - depth: depth + 1 - }, v))); - const record2 = value; - if (isEscapedObject(record2)) - return unescapeValue(record2); - if ("lc" in record2 && "type" in record2 && "id" in record2 && record2.lc === 1 && record2.type === "secret") { - const [key] = record2.id; - if (key in secretsMap) - return secretsMap[key]; - else if (secretsFromEnv) { - const secretValueInEnv = getEnvironmentVariable(key); - if (secretValueInEnv) - return secretValueInEnv; + RunnablePick = class extends Runnable { + static lc_name() { + return "RunnablePick"; } - throw new Error(`Missing secret "${key}" at ${pathStr}`); - } - if ("lc" in record2 && "type" in record2 && "id" in record2 && record2.lc === 1 && record2.type === "not_implemented") { - const str = JSON.stringify(record2); - throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); - } - if ("lc" in record2 && "type" in record2 && "id" in record2 && "kwargs" in record2 && record2.lc === 1 && record2.type === "constructor") { - const serialized = record2; - const str = JSON.stringify(serialized); - const [name, ...namespaceReverse] = serialized.id.slice().reverse(); - const namespace = namespaceReverse.reverse(); - const importMaps = { - langchain_core: import_map_exports, - langchain: importMap - }; - let module = null; - const optionalImportNamespaceAliases = [namespace.join("/")]; - if (namespace[0] === "langchain_community") - optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); - const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => (alias in optionalImportsMap)); - if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) - if (matchingNamespaceAlias !== undefined) - module = await optionalImportsMap[matchingNamespaceAlias]; - else - throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); - else { - let finalImportMap; - if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { - finalImportMap = importMaps[namespace[0]]; - namespace.shift(); - } else - throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - if (namespace.length === 0) - throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - let importMapKey; - do { - importMapKey = namespace.join("__"); - if (importMapKey in finalImportMap) - break; + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + keys; + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) + fields = { keys: fields }; + super(fields); + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") + return input[this.keys]; + else { + const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== undefined); + return picked.length === 0 ? undefined : Object.fromEntries(picked); + } + } + async invoke(input, options) { + return this._callWithConfig(this._pick.bind(this), input, options); + } + async* _transform(generator) { + for await (const chunk of generator) { + const picked = await this._pick(chunk); + if (picked !== undefined) + yield picked; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config3 = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config3), + config: config3 + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + }; + RunnableToolLike = class extends RunnableBinding { + name; + description; + schema; + constructor(fields) { + const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) + try { + toolInput = await interopParseAsync(this.schema, input.args); + } catch { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } else - namespace.pop(); - } while (namespace.length > 0); - if (importMapKey in finalImportMap) - module = finalImportMap[importMapKey]; + toolInput = input; + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {} + }); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; } - if (typeof module !== "object" || module === null) - throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); - if (typeof builder !== "function") - throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); - const instance = new builder(mapKeys(await reviver.call({ - ...this, - path: [...path2, "kwargs"], - depth: depth + 1 - }, serialized.kwargs), keyFromJson, combineAliasesAndInvert(builder))); - Object.defineProperty(instance.constructor, "name", { value: name }); - return instance; - } - const result = {}; - for (const [key, val] of Object.entries(record2)) - result[key] = await reviver.call({ - ...this, - path: [...path2, key], - depth: depth + 1 - }, val); - return result; -} -async function load(text, options) { - const json2 = JSON.parse(text); - const context2 = { - optionalImportsMap: options?.optionalImportsMap ?? {}, - optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [], - secretsMap: options?.secretsMap ?? {}, - secretsFromEnv: options?.secretsFromEnv ?? false, - importMap: options?.importMap ?? {}, - path: ["$"], - depth: 0, - maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH }; - return reviver.call(context2, json2); -} -var DEFAULT_MAX_DEPTH = 50; -var init_load = __esm(() => { - init_map_keys(); - init_validation(); - init_serializable(); - init_env(); - init_import_constants(); - init_import_map(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js -function isLangChainSerializedObject(value) { - return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/transformers.js +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) + return _filterMessages(messagesOrOptions, options); + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); } -async function _reviver(value) { - if (value && typeof value === "object") - if (Array.isArray(value)) - return await Promise.all(value.map((item) => _reviver(item))); +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) + continue; + else if (excludeTypes && _isMessageType(msg, excludeTypes)) + continue; + else if (excludeIds && msg.id && excludeIds.includes(msg.id)) + continue; + if (!(includeTypes || includeIds || includeNames)) + filtered.push(msg); + else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) + filtered.push(msg); + else if (includeTypes && _isMessageType(msg, includeTypes)) + filtered.push(msg); + else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) + filtered.push(msg); + } + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) + return _mergeMessageRuns(messages); + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) + return []; + const merged = []; + for (const msg of messages) { + const curr = msg; + const last = merged.pop(); + if (!last) + merged.push(curr); + else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) + merged.push(last, curr); else { - const revivedObj = {}; - for (const [k, v] of Object.entries(value)) - revivedObj[k] = await _reviver(v); - if (revivedObj.lc === 2 && revivedObj.type === "undefined") - return; - else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) - try { - const constructorName = revivedObj.id[revivedObj.id.length - 1]; - let constructor; - switch (constructorName) { - case "Set": - constructor = Set; - break; - case "Map": - constructor = Map; - break; - case "RegExp": - constructor = RegExp; - break; - case "Error": - constructor = Error; - break; - case "Uint8Array": - constructor = Uint8Array; - break; - default: - return revivedObj; - } - if (revivedObj.method) - return constructor[revivedObj.method](...revivedObj.args || []); - else - return new constructor(...revivedObj.args || []); - } catch { - return revivedObj; - } - else if (isLangChainSerializedObject(revivedObj)) - return load(JSON.stringify(revivedObj)); - return revivedObj; + const lastChunk = convertToChunk(last); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") + mergedChunks.content = `${lastChunk.content} +${currChunk.content}`; + merged.push(_chunkToMsg(mergedChunks)); } - return value; + } + return merged; } -function _encodeConstructorArgs(constructor, method, args, kwargs) { - return { - lc: 2, - type: "constructor", - id: [constructor.name], - method: method ?? null, - args: args ?? [], - kwargs: kwargs ?? {} - }; +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) + throw new Error("Options parameter is required when providing messages."); + return _trimMessagesHelper(messages, options); + } else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); + } } -function _default3(obj) { - if (obj === undefined) - return { - lc: 2, - type: "undefined" - }; - else if (obj instanceof Set || obj instanceof Map) - return _encodeConstructorArgs(obj.constructor, undefined, [Array.from(obj)]); - else if (obj instanceof RegExp) - return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]); - else if (obj instanceof Error) - return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]); - else if (obj?.lg_name === "Send") - return { - node: obj.node, - args: obj.args +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; + if (startOn && strategy === "first") + throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + if (includeSystem && strategy === "first") + throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + let listTokenCounter; + if ("getNumTokens" in tokenCounter) + listTokenCounter = async (msgs) => { + return (await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)))).reduce((sum, count) => sum + count, 0); }; - else if (obj instanceof Uint8Array) - return _encodeConstructorArgs(Uint8Array, "from", [Array.from(obj)]); else - return obj; -} -var JsonPlusSerializer = class { - _dumps(obj) { - return new TextEncoder().encode(stringify3(obj, (_, value) => { - return _default3(value); - })); - } - async dumpsTyped(obj) { - if (obj instanceof Uint8Array) - return ["bytes", obj]; + listTokenCounter = async (msgs) => tokenCounter(msgs); + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) + if ("splitText" in textSplitter) + textSplitterFunc = textSplitter.splitText; else - return ["json", this._dumps(obj)]; - } - async _loads(data) { - return _reviver(JSON.parse(data)); + textSplitterFunc = async (text) => textSplitter(text); + if (strategy === "first") + return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : undefined, + endOn + }); + else if (strategy === "last") + return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn + }); + else + throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0;i < messagesCopy.length; i += 1) + if (await tokenCounter(i > 0 ? messagesCopy.slice(0, -i) : messagesCopy) <= maxTokens) { + idx = messagesCopy.length - i; + break; + } + if (idx < messagesCopy.length && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") + throw new Error("Expected content to be an array."); + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; + for (let i = 1;i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if (await tokenCounter(slicedMessages) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; + } else + break; + } + if (includedPartial && partialStrategy === "last") + excluded.content = [...reversedContent].reverse(); + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) + text = excluded.content.find((block) => block.type === "text" && block.text)?.text; + else if (typeof excluded.content === "string") + text = excluded.content; + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") + splitTexts.reverse(); + for (let _ = 0;_ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { + if (partialStrategy === "last") + excluded.content = [...splitTexts].reverse().join(""); + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; + } + } + } + } } - async loadsTyped(type, data) { - if (type === "bytes") - return typeof data === "string" ? new TextEncoder().encode(data) : data; - else if (type === "json") - return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); - else - throw new Error(`Unknown serialization type: ${type}`); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) + idx -= 1; } -}; -var init_jsonplus = __esm(() => { - init_fast_safe_stringify2(); - init_load(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/base.js -function deepCopy(obj) { - if (typeof obj !== "object" || obj === null) - return obj; - const newObj = Array.isArray(obj) ? [] : {}; - for (const key in obj) - if (Object.prototype.hasOwnProperty.call(obj, key)) - newObj[key] = deepCopy(obj[key]); - return newObj; -} -function emptyCheckpoint() { - return { - v: 4, - id: uuid62(-2), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: {}, - channel_versions: {}, - versions_seen: {} - }; -} -function copyCheckpoint(checkpoint) { - return { - v: checkpoint.v, - id: checkpoint.id, - ts: checkpoint.ts, - channel_values: { ...checkpoint.channel_values }, - channel_versions: { ...checkpoint.channel_versions }, - versions_seen: deepCopy(checkpoint.versions_seen) - }; -} -function compareChannelVersions(a, b) { - if (typeof a === "number" && typeof b === "number") - return Math.sign(a - b); - return String(a).localeCompare(String(b)); + return messagesCopy.slice(0, idx); } -function maxChannelVersion(...versions2) { - return versions2.reduce((max, version4, idx) => { - if (idx === 0) - return version4; - return compareChannelVersions(max, version4) >= 0 ? max : version4; +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); }); -} -function getCheckpointId(config2) { - return config2.configurable?.checkpoint_id || config2.configurable?.thread_ts || ""; -} -var BaseCheckpointSaver = class { - serde = new JsonPlusSerializer; - constructor(serde) { - this.serde = serde || this.serde; - } - async get(config2) { - const value = await this.getTuple(config2); - return value ? value.checkpoint : undefined; - } - getNextVersion(current) { - if (typeof current === "string") - throw new Error("Please override this method to use string versions."); - return current !== undefined && typeof current === "number" ? current + 1 : 1; + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) + messagesCopy = messagesCopy.slice(0, -1); } -}, WRITES_IDX_MAP; -var init_base12 = __esm(() => { - init_id2(); - init_types5(); - init_jsonplus(); - WRITES_IDX_MAP = { - [ERROR3]: -1, - [SCHEDULED]: -2, - [INTERRUPT2]: -3, - [RESUME2]: -4 - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/memory.js -function _generateKey(threadId, checkpointNamespace, checkpointId) { - return JSON.stringify([ - threadId, - checkpointNamespace, - checkpointId - ]); -} -function _parseKey(key) { - const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key); - return { - threadId, - checkpointNamespace, - checkpointId - }; + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : undefined, + endOn: startOn + }); + if (swappedSystem) + return [reversed_[0], ...reversed_.slice(1).reverse()]; + else + return reversed_.reverse(); } -var MemorySaver; -var init_memory2 = __esm(() => { - init_types5(); - init_base12(); - MemorySaver = class extends BaseCheckpointSaver { - storage = {}; - writes = {}; - constructor(serde) { - super(serde); - } - async _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) { - const deseriablizableCheckpoint = mutableCheckpoint; - const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId); - const pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS2).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped("json", writes))); - deseriablizableCheckpoint.channel_values ??= {}; - deseriablizableCheckpoint.channel_values[TASKS2] = pendingSends; - deseriablizableCheckpoint.channel_versions ??= {}; - deseriablizableCheckpoint.channel_versions[TASKS2] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(undefined); - } - async getTuple(config2) { - const thread_id = config2.configurable?.thread_id; - const checkpoint_ns = config2.configurable?.checkpoint_ns ?? ""; - let checkpoint_id = getCheckpointId(config2); - if (checkpoint_id) { - const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id]; - if (saved !== undefined) { - const [checkpoint, metadata, parentCheckpointId] = saved; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) - await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config: config2, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites - }; - if (parentCheckpointId !== undefined) - checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } else { - const checkpoints = this.storage[thread_id]?.[checkpoint_ns]; - if (checkpoints !== undefined) { - checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0]; - const [checkpoint, metadata, parentCheckpointId] = checkpoints[checkpoint_id]; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) - await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config: { configurable: { - thread_id, - checkpoint_id, - checkpoint_ns - } }, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) + chunk = new HumanMessageChunk(fields); + else + msg = new HumanMessage(fields); + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { ...fields }; + if ("tool_calls" in aiChunkFields) + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: undefined, + args: JSON.stringify(tc.args) + })) }; - if (parentCheckpointId !== undefined) - checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } - } - async* list(config2, options) { - let { before, limit, filter } = options ?? {}; - const threadIds = config2.configurable?.thread_id ? [config2.configurable?.thread_id] : Object.keys(this.storage); - const configCheckpointNamespace = config2.configurable?.checkpoint_ns; - const configCheckpointId = config2.configurable?.checkpoint_id; - for (const threadId of threadIds) - for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) { - if (configCheckpointNamespace !== undefined && checkpointNamespace !== configCheckpointNamespace) - continue; - const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {}; - const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0])); - for (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) { - if (configCheckpointId && checkpointId !== configCheckpointId) - continue; - if (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) - continue; - const metadata = await this.serde.loadsTyped("json", metadataStr); - if (filter && !Object.entries(filter).every(([key2, value]) => metadata[key2] === value)) - continue; - if (limit !== undefined) { - if (limit <= 0) - break; - limit -= 1; - } - const key = _generateKey(threadId, checkpointNamespace, checkpointId); - const writes = Object.values(this.writes[key] || {}); - const pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) - await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId); - const checkpointTuple = { - config: { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpointId - } }, - checkpoint: deserializedCheckpoint, - metadata, - pendingWrites - }; - if (parentCheckpointId !== undefined) - checkpointTuple.parentConfig = { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: parentCheckpointId - } }; - yield checkpointTuple; + chunk = new AIMessageChunk(aiChunkFields); + } else + msg = new AIMessage(fields); + break; + case "system": + if (returnChunk) + chunk = new SystemMessageChunk(fields); + else + msg = new SystemMessage(fields); + break; + case "developer": + if (returnChunk) + chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" } - } - } - async put(config2, checkpoint, metadata) { - const preparedCheckpoint = copyCheckpoint(checkpoint); - const threadId = config2.configurable?.thread_id; - const checkpointNamespace = config2.configurable?.checkpoint_ns ?? ""; - if (threadId === undefined) - throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })'); - if (!this.storage[threadId]) - this.storage[threadId] = {}; - if (!this.storage[threadId][checkpointNamespace]) - this.storage[threadId][checkpointNamespace] = {}; - const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]); - this.storage[threadId][checkpointNamespace][checkpoint.id] = [ - serializedCheckpoint, - serializedMetadata, - config2.configurable?.checkpoint_id - ]; - return { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpoint.id - } }; - } - async putWrites(config2, writes, taskId) { - const threadId = config2.configurable?.thread_id; - const checkpointNamespace = config2.configurable?.checkpoint_ns; - const checkpointId = config2.configurable?.checkpoint_id; - if (threadId === undefined) - throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })'); - if (checkpointId === undefined) - throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.`); - const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId); - const outerWrites_ = this.writes[outerKey]; - if (this.writes[outerKey] === undefined) - this.writes[outerKey] = {}; - await Promise.all(writes.map(async ([channel, value], idx) => { - const [, serializedValue] = await this.serde.dumpsTyped(value); - const innerKey = [taskId, WRITES_IDX_MAP[channel] || idx]; - const innerKeyStr = `${innerKey[0]},${innerKey[1]}`; - if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) - return; - this.writes[outerKey][innerKeyStr] = [ - taskId, - channel, - serializedValue - ]; - })); - } - async deleteThread(threadId) { - delete this.storage[threadId]; - for (const key of Object.keys(this.writes)) - if (_parseKey(key).threadId === threadId) - delete this.writes[key]; + }); + else + msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + break; + case "tool": + if ("tool_call_id" in fields) + if (returnChunk) + chunk = new ToolMessageChunk(fields); + else + msg = new ToolMessage(fields); + else + throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + break; + case "function": + if (returnChunk) + chunk = new FunctionMessageChunk(fields); + else { + if (!fields.name) + throw new Error("FunctionMessage must have a 'name' field"); + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) + if (returnChunk) + chunk = new ChatMessageChunk(fields); + else + msg = new ChatMessage(fields); + else + throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + break; + default: + throw new Error(`Unrecognized message type ${messageType}`); + } + if (returnChunk && chunk) + return chunk; + if (msg) + return msg; + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) + msg = _switchTypeToMessage(chunkType, fields); + if (!msg) + throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + return msg; +} +function defaultTextSplitter(text) { + const splits = text.split(` +`); + return Promise.resolve([...splits.slice(0, -1).map((s) => `${s} +`), splits[splits.length - 1]]); +} +var _isMessageType = (msg, types3) => { + const typesAsStrings = [...new Set(types3?.map((t) => { + if (typeof t === "string") + return t; + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") + throw new Error("Invalid type provided."); + return instantiatedMsgClass.getType(); + }))]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); +}, _MSG_CHUNK_MAP; +var init_transformers = __esm(() => { + init_base(); + init_tool(); + init_ai(); + init_chat(); + init_function(); + init_human(); + init_modifier(); + init_system(); + init_utils3(); + init_base4(); + _MSG_CHUNK_MAP = { + human: { + message: HumanMessage, + messageChunk: HumanMessageChunk + }, + ai: { + message: AIMessage, + messageChunk: AIMessageChunk + }, + system: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + developer: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + tool: { + message: ToolMessage, + messageChunk: ToolMessageChunk + }, + function: { + message: FunctionMessage, + messageChunk: FunctionMessageChunk + }, + generic: { + message: ChatMessage, + messageChunk: ChatMessageChunk + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/store/base.js -function validateNamespace(namespace) { - if (namespace.length === 0) - throw new InvalidNamespaceError("Namespace cannot be empty."); - for (const label of namespace) { - if (typeof label !== "string") - throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); - if (label.includes(".")) - throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); - if (label === "") - throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/content/tools.js +var KNOWN_BLOCK_TYPES; +var init_tools = __esm(() => { + KNOWN_BLOCK_TYPES = [ + "tool_call", + "tool_call_chunk", + "invalid_tool_call", + "server_tool_call", + "server_tool_call_chunk", + "server_tool_call_result" + ]; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/content/multimodal.js +var KNOWN_BLOCK_TYPES2; +var init_multimodal = __esm(() => { + KNOWN_BLOCK_TYPES2 = [ + "image", + "video", + "audio", + "text-plain", + "file" + ]; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/content/index.js +var KNOWN_BLOCK_TYPES3; +var init_content = __esm(() => { + init_tools(); + init_multimodal(); + KNOWN_BLOCK_TYPES3 = [ + "text", + "reasoning", + ...KNOWN_BLOCK_TYPES, + ...KNOWN_BLOCK_TYPES2 + ]; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/messages/index.js +var messages_exports; +var init_messages = __esm(() => { + init_runtime2(); + init_data(); + init_message(); + init_base(); + init_metadata(); + init_tool(); + init_ai(); + init_chat(); + init_function(); + init_human(); + init_modifier(); + init_system(); + init_utils3(); + init_transformers(); + init_content(); + messages_exports = /* @__PURE__ */ __exportAll({ + AIMessage: () => AIMessage, + AIMessageChunk: () => AIMessageChunk, + BaseMessage: () => BaseMessage, + BaseMessageChunk: () => BaseMessageChunk, + ChatMessage: () => ChatMessage, + ChatMessageChunk: () => ChatMessageChunk, + DEFAULT_MERGE_IGNORE_KEYS: () => DEFAULT_MERGE_IGNORE_KEYS, + FunctionMessage: () => FunctionMessage, + FunctionMessageChunk: () => FunctionMessageChunk, + HumanMessage: () => HumanMessage, + HumanMessageChunk: () => HumanMessageChunk, + KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES3, + RemoveMessage: () => RemoveMessage, + SystemMessage: () => SystemMessage, + SystemMessageChunk: () => SystemMessageChunk, + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + _isMessageFieldWithRole: () => _isMessageFieldWithRole, + _mergeDicts: () => _mergeDicts, + _mergeLists: () => _mergeLists, + _mergeObj: () => _mergeObj, + _mergeStatus: () => _mergeStatus, + coerceMessageLikeToMessage: () => coerceMessageLikeToMessage, + collapseToolCallChunks: () => collapseToolCallChunks, + convertToChunk: () => convertToChunk, + convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, + convertToProviderContentBlock: () => convertToProviderContentBlock, + defaultTextSplitter: () => defaultTextSplitter, + defaultToolCallParser: () => defaultToolCallParser, + filterMessages: () => filterMessages, + getBufferString: () => getBufferString, + iife: () => iife2, + isAIMessage: () => isAIMessage, + isAIMessageChunk: () => isAIMessageChunk, + isBase64ContentBlock: () => isBase64ContentBlock, + isBaseMessage: () => isBaseMessage, + isBaseMessageChunk: () => isBaseMessageChunk, + isChatMessage: () => isChatMessage, + isChatMessageChunk: () => isChatMessageChunk, + isDataContentBlock: () => isDataContentBlock, + isDirectToolOutput: () => isDirectToolOutput, + isFunctionMessage: () => isFunctionMessage, + isFunctionMessageChunk: () => isFunctionMessageChunk, + isHumanMessage: () => isHumanMessage, + isHumanMessageChunk: () => isHumanMessageChunk, + isIDContentBlock: () => isIDContentBlock, + isMessage: () => isMessage, + isOpenAIToolCallArray: () => isOpenAIToolCallArray, + isPlainTextContentBlock: () => isPlainTextContentBlock, + isSystemMessage: () => isSystemMessage, + isSystemMessageChunk: () => isSystemMessageChunk, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk, + isURLContentBlock: () => isURLContentBlock, + mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, + mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, + mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, + mergeContent: () => mergeContent, + mergeMessageRuns: () => mergeMessageRuns, + mergeResponseMetadata: () => mergeResponseMetadata, + mergeUsageMetadata: () => mergeUsageMetadata, + parseBase64DataUrl: () => parseBase64DataUrl, + parseMimeType: () => parseMimeType, + trimMessages: () => trimMessages + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/js-sha256/hash.js +function Sha256(is224, sharedMemory) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else + this.blocks = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + if (is224) { + this.h0 = 3238371032; + this.h1 = 914150663; + this.h2 = 812702999; + this.h3 = 4144912697; + this.h4 = 4290775857; + this.h5 = 1750603025; + this.h6 = 1694076839; + this.h7 = 3204075428; + } else { + this.h0 = 1779033703; + this.h1 = 3144134277; + this.h2 = 1013904242; + this.h3 = 2773480762; + this.h4 = 1359893119; + this.h5 = 2600822924; + this.h6 = 528734635; + this.h7 = 1541459225; } - if (namespace[0] === "langgraph") - throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; } -var InvalidNamespaceError, BaseStore2 = class { - async get(namespace, key) { - return (await this.batch([{ - namespace, - key - }]))[0]; - } - async search(namespacePrefix, options = {}) { - const { filter, limit = 10, offset = 0, query: query3 } = options; - return (await this.batch([{ - namespacePrefix, - filter, - limit, - offset, - query: query3 - }]))[0]; - } - async put(namespace, key, value, index2) { - validateNamespace(namespace); - await this.batch([{ - namespace, - key, - value, - index: index2 - }]); - } - async delete(namespace, key) { - await this.batch([{ - namespace, - key, - value: null - }]); - } - async listNamespaces(options = {}) { - const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; - const matchConditions = []; - if (prefix) - matchConditions.push({ - matchType: "prefix", - path: prefix - }); - if (suffix) - matchConditions.push({ - matchType: "suffix", - path: suffix - }); - return (await this.batch([{ - matchConditions: matchConditions.length ? matchConditions : undefined, - maxDepth, - limit, - offset - }]))[0]; - } - start() {} - stop() {} +var HEX_CHARS, EXTRA, SHIFT, K, blocks, sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); }; -var init_base13 = __esm(() => { - InvalidNamespaceError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidNamespaceError"; +var init_hash = __esm(() => { + HEX_CHARS = "0123456789abcdef".split(""); + EXTRA = [ + -2147483648, + 8388608, + 32768, + 128 + ]; + SHIFT = [ + 24, + 16, + 8, + 0 + ]; + K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]; + blocks = []; + Sha256.prototype.update = function(message) { + if (this.finalized) + return; + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) + throw new Error(ERROR); + else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) + message = new Uint8Array(message); + else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) + throw new Error(ERROR); + } + } else + throw new Error(ERROR); + notString = true; + } + var code, index = 0, i, length = message.length, blocks2 = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks2[0] = this.block; + this.block = blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; + } + if (notString) + for (i = this.start;index < length && i < 64; ++index) + blocks2[i >>> 2] |= message[index] << SHIFT[i++ & 3]; + else + for (i = this.start;index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 128) + blocks2[i >>> 2] |= code << SHIFT[i++ & 3]; + else if (code < 2048) { + blocks2[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks2[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); + blocks2[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks2[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else + this.start = i; + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; + }; + Sha256.prototype.finalize = function() { + if (this.finalized) + return; + this.finalized = true; + var blocks2 = this.blocks, i = this.lastByteIndex; + blocks2[16] = this.block; + blocks2[i >>> 2] |= EXTRA[i & 3]; + this.block = blocks2[16]; + if (i >= 56) { + if (!this.hashed) + this.hash(); + blocks2[0] = this.block; + blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; + } + blocks2[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks2[15] = this.bytes << 3; + this.hash(); + }; + Sha256.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f3 = this.h5, g = this.h6, h = this.h7, blocks2 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16;j < 64; ++j) { + t1 = blocks2[j - 15]; + s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; + t1 = blocks2[j - 2]; + s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + blocks2[j] = blocks2[j - 16] + s0 + blocks2[j - 7] + s1 << 0; + } + bc = b & c; + for (j = 0;j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks2[0] - 1413257819; + h = t1 - 150054599 << 0; + d = t1 + 24177077 << 0; + } else { + ab = 704751109; + t1 = blocks2[0] - 210244248; + h = t1 - 1521486534 << 0; + d = t1 + 143694565 << 0; + } + this.first = false; + } else { + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ab = a & b; + maj = ab ^ a & c ^ bc; + ch = e & f3 ^ ~e & g; + t1 = h + s1 + ch + K[j] + blocks2[j]; + t2 = s0 + maj; + h = d + t1 << 0; + d = t1 + t2 << 0; + } + s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); + s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); + da = d & a; + maj = da ^ d & b ^ ab; + ch = g & h ^ ~g & e; + t1 = f3 + s1 + ch + K[j + 1] + blocks2[j + 1]; + t2 = s0 + maj; + g = c + t1 << 0; + c = t1 + t2 << 0; + s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); + s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); + cd = c & d; + maj = cd ^ c & a ^ da; + ch = f3 & g ^ ~f3 & h; + t1 = e + s1 + ch + K[j + 2] + blocks2[j + 2]; + t2 = s0 + maj; + f3 = b + t1 << 0; + b = t1 + t2 << 0; + s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); + s1 = (f3 >>> 6 | f3 << 26) ^ (f3 >>> 11 | f3 << 21) ^ (f3 >>> 25 | f3 << 7); + bc = b & c; + maj = bc ^ b & d ^ cd; + ch = f3 & g ^ ~f3 & h; + t1 = e + s1 + ch + K[j + 3] + blocks2[j + 3]; + t2 = s0 + maj; + e = a + t1 << 0; + a = t1 + t2 << 0; + this.chromeBugWorkAround = true; } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; + this.h5 = this.h5 + f3 << 0; + this.h6 = this.h6 + g << 0; + this.h7 = this.h7 + h << 0; + }; + Sha256.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex3 = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; + if (!this.is224) + hex3 += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; + return hex3; + }; + Sha256.prototype.toString = Sha256.prototype.hex; + Sha256.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr2 = [ + h0 >>> 24 & 255, + h0 >>> 16 & 255, + h0 >>> 8 & 255, + h0 & 255, + h1 >>> 24 & 255, + h1 >>> 16 & 255, + h1 >>> 8 & 255, + h1 & 255, + h2 >>> 24 & 255, + h2 >>> 16 & 255, + h2 >>> 8 & 255, + h2 & 255, + h3 >>> 24 & 255, + h3 >>> 16 & 255, + h3 >>> 8 & 255, + h3 & 255, + h4 >>> 24 & 255, + h4 >>> 16 & 255, + h4 >>> 8 & 255, + h4 & 255, + h5 >>> 24 & 255, + h5 >>> 16 & 255, + h5 >>> 8 & 255, + h5 & 255, + h6 >>> 24 & 255, + h6 >>> 16 & 255, + h6 >>> 8 & 255, + h6 & 255 + ]; + if (!this.is224) + arr2.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); + return arr2; + }; + Sha256.prototype.array = Sha256.prototype.digest; + Sha256.prototype.arrayBuffer = function() { + this.finalize(); + var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) + dataView.setUint32(28, this.h7); + return buffer; }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js -var extractStore = (input) => { - if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") - return input.store; - return input; -}, AsyncBatchedStore; -var init_batch = __esm(() => { - init_base13(); - AsyncBatchedStore = class extends BaseStore2 { - lg_name = "AsyncBatchedStore"; - store; - queue = /* @__PURE__ */ new Map; - nextKey = 0; - running = false; - processingTask = null; - constructor(store) { +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/hash.js +var hash_exports; +var init_hash2 = __esm(() => { + init_runtime2(); + init_hash(); + hash_exports = /* @__PURE__ */ __exportAll({ sha256: () => sha256 }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/caches/index.js +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== undefined) + return { + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message) + }; + else + return { text: storedGeneration.text }; +} +function serializeGeneration(generation) { + const serializedValue = { text: generation.text }; + if (generation.message !== undefined) + serializedValue.message = generation.message.toDict(); + return serializedValue; +} +var caches_exports, defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")), BaseCache = class { + keyEncoder = defaultHashKeyEncoder; + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } +}, GLOBAL_MAP, InMemoryCache; +var init_caches = __esm(() => { + init_runtime2(); + init_hash(); + init_hash2(); + init_utils3(); + caches_exports = /* @__PURE__ */ __exportAll({ + BaseCache: () => BaseCache, + InMemoryCache: () => InMemoryCache, + defaultHashKeyEncoder: () => defaultHashKeyEncoder, + deserializeStoredGeneration: () => deserializeStoredGeneration, + serializeGeneration: () => serializeGeneration + }); + GLOBAL_MAP = /* @__PURE__ */ new Map; + InMemoryCache = class InMemoryCache2 extends BaseCache { + cache; + constructor(map2) { super(); - this.store = extractStore(store); + this.cache = map2 ?? /* @__PURE__ */ new Map; } - get isRunning() { - return this.running; + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); } - async batch(_operations) { - throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); + async update(prompt, llmKey, value) { + this.cache.set(this.keyEncoder(prompt, llmKey), value); } - async get(namespace, key) { - return this.enqueueOperation({ - namespace, - key - }); + static global() { + return new InMemoryCache2(GLOBAL_MAP); } - async search(namespacePrefix, options) { - const { filter, limit = 10, offset = 0, query: query3 } = options || {}; - return this.enqueueOperation({ - namespacePrefix, - filter, - limit, - offset, - query: query3 - }); + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompt_values.js +var prompt_values_exports, BasePromptValue, StringPromptValue, ChatPromptValue, ImagePromptValue; +var init_prompt_values = __esm(() => { + init_runtime2(); + init_serializable(); + init_human(); + init_utils3(); + prompt_values_exports = /* @__PURE__ */ __exportAll({ + BasePromptValue: () => BasePromptValue, + ChatPromptValue: () => ChatPromptValue, + ImagePromptValue: () => ImagePromptValue, + StringPromptValue: () => StringPromptValue + }); + BasePromptValue = class extends Serializable { + }; + StringPromptValue = class extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; } - async put(namespace, key, value) { - return this.enqueueOperation({ - namespace, - key, - value - }); + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + value; + constructor(value) { + super({ value }); + this.value = value; } - async delete(namespace, key) { - return this.enqueueOperation({ - namespace, - key, - value: null - }); + toString() { + return this.value; } - start() { - if (!this.running) { - this.running = true; - this.processingTask = this.processBatchQueue(); - } + toChatMessages() { + return [new HumanMessage(this.value)]; } - async stop() { - this.running = false; - if (this.processingTask) - await this.processingTask; + }; + ChatPromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ChatPromptValue"; } - enqueueOperation(operation) { - return new Promise((resolve2, reject) => { - const key = this.nextKey; - this.nextKey += 1; - this.queue.set(key, { - operation, - resolve: resolve2, - reject - }); - }); + messages; + constructor(fields) { + if (Array.isArray(fields)) + fields = { messages: fields }; + super(fields); + this.messages = fields.messages; } - async processBatchQueue() { - while (this.running) { - await new Promise((resolve2) => { - setTimeout(resolve2, 0); - }); - if (this.queue.size === 0) - continue; - const batch = new Map(this.queue); - this.queue.clear(); - try { - const operations = Array.from(batch.values()).map(({ operation }) => operation); - const results = await this.store.batch(operations); - batch.forEach(({ resolve: resolve2 }, key) => { - resolve2(results[Array.from(batch.keys()).indexOf(key)]); - }); - } catch (e) { - batch.forEach(({ reject }) => { - reject(e); - }); - } - } + toString() { + return getBufferString(this.messages); } - toJSON() { - return { - queue: this.queue, - nextKey: this.nextKey, - running: this.running, - store: "[LangGraphStore]" - }; + toChatMessages() { + return this.messages; + } + }; + ImagePromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ImagePromptValue"; + } + imageUrl; + value; + constructor(fields) { + if (!("imageUrl" in fields)) + fields = { imageUrl: fields }; + super(fields); + this.imageUrl = fields.imageUrl; + } + toString() { + return this.imageUrl.url; + } + toChatMessages() { + return [new HumanMessage({ content: [{ + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url + } + }] })]; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js -function tokenizePath(path2) { - if (!path2) - return []; - const tokens = []; - let current = []; - let i = 0; - while (i < path2.length) { - const char = path2[i]; - if (char === "[") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let bracketCount = 1; - const indexChars = ["["]; - i += 1; - while (i < path2.length && bracketCount > 0) { - if (path2[i] === "[") - bracketCount += 1; - else if (path2[i] === "]") - bracketCount -= 1; - indexChars.push(path2[i]); - i += 1; - } - tokens.push(indexChars.join("")); - continue; - } else if (char === "{") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let braceCount = 1; - const fieldChars = ["{"]; - i += 1; - while (i < path2.length && braceCount > 0) { - if (path2[i] === "{") - braceCount += 1; - else if (path2[i] === "}") - braceCount -= 1; - fieldChars.push(path2[i]); - i += 1; - } - tokens.push(fieldChars.join("")); - continue; - } else if (char === ".") { - if (current.length) { - tokens.push(current.join("")); - current = []; +// ../../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js +var require_base64_js = __commonJS((exports) => { + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i = 0, len = code.length;i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + var i; + var len; + revLookup[45] = 62; + revLookup[95] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) + validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr2 = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0;i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr2[curByte++] = tmp >> 16 & 255; + arr2[curByte++] = tmp >> 8 & 255; + arr2[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr2[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr2[curByte++] = tmp >> 8 & 255; + arr2[curByte++] = tmp & 255; + } + return arr2; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start;i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); + } + return parts.join(""); + } +}); + +// ../../node_modules/.pnpm/js-tiktoken@1.0.21/node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js +function bytePairMerge(piece, ranks) { + let parts = Array.from({ length: piece.length }, (_, i) => ({ start: i, end: i + 1 })); + while (parts.length > 1) { + let minRank = null; + for (let i = 0;i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; } - } else - current.push(char); - i += 1; + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } } - if (current.length) - tokens.push(current.join("")); - return tokens; + return parts; } -function isFilterOperators(obj) { - return typeof obj === "object" && obj !== null && Object.keys(obj).every((key) => key === "$eq" || key === "$ne" || key === "$gt" || key === "$gte" || key === "$lt" || key === "$lte" || key === "$in" || key === "$nin"); +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); } -function compareValues(itemValue, filterValue) { - if (isFilterOperators(filterValue)) - return Object.keys(filterValue).filter((k) => k.startsWith("$")).every((op) => { - const value = filterValue[op]; - switch (op) { - case "$eq": - return itemValue === value; - case "$ne": - return itemValue !== value; - case "$gt": - return Number(itemValue) > Number(value); - case "$gte": - return Number(itemValue) >= Number(value); - case "$lt": - return Number(itemValue) < Number(value); - case "$lte": - return Number(itemValue) <= Number(value); - case "$in": - return Array.isArray(value) ? value.includes(itemValue) : false; - case "$nin": - return Array.isArray(value) ? !value.includes(itemValue) : true; - default: - return false; - } - }); - return itemValue === filterValue; +function escapeRegex3(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); } -function getTextAtPath(obj, path2) { - if (!path2 || path2 === "$") - return [JSON.stringify(obj, null, 2)]; - const tokens = Array.isArray(path2) ? path2 : tokenizePath(path2); - function extractFromObj(obj2, tokens2, pos) { - if (pos >= tokens2.length) { - if (typeof obj2 === "string" || typeof obj2 === "number" || typeof obj2 === "boolean") - return [String(obj2)]; - if (obj2 === null || obj2 === undefined) - return []; - if (Array.isArray(obj2) || typeof obj2 === "object") - return [JSON.stringify(obj2, null, 2)]; - return []; +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; } - const token = tokens2[pos]; - const results = []; - if (pos === 0 && token === "$") - results.push(JSON.stringify(obj2, null, 2)); - if (token.startsWith("[") && token.endsWith("]")) { - if (!Array.isArray(obj2)) - return []; - const index2 = token.slice(1, -1); - if (index2 === "*") - for (const item of obj2) - results.push(...extractFromObj(item, tokens2, pos + 1)); - else - try { - let idx = parseInt(index2, 10); - if (idx < 0) - idx = obj2.length + idx; - if (idx >= 0 && idx < obj2.length) - results.push(...extractFromObj(obj2[idx], tokens2, pos + 1)); - } catch { - return []; - } - } else if (token.startsWith("{") && token.endsWith("}")) { - if (typeof obj2 !== "object" || obj2 === null) - return []; - const fields = token.slice(1, -1).split(",").map((f3) => f3.trim()); - for (const field of fields) { - const nestedTokens = tokenizePath(field); - if (nestedTokens.length) { - let currentObj = obj2; - for (const nestedToken of nestedTokens) - if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) - currentObj = currentObj[nestedToken]; - else { - currentObj = undefined; - break; - } - if (currentObj !== undefined) { - if (typeof currentObj === "string" || typeof currentObj === "number" || typeof currentObj === "boolean") - results.push(String(currentObj)); - else if (Array.isArray(currentObj) || typeof currentObj === "object") - results.push(JSON.stringify(currentObj, null, 2)); - } - } - } - } else if (token === "*") { - if (Array.isArray(obj2)) - for (const item of obj2) - results.push(...extractFromObj(item, tokens2, pos + 1)); - else if (typeof obj2 === "object" && obj2 !== null) - for (const value of Object.values(obj2)) - results.push(...extractFromObj(value, tokens2, pos + 1)); - } else if (typeof obj2 === "object" && obj2 !== null && token in obj2) - results.push(...extractFromObj(obj2[token], tokens2, pos + 1)); - return results; - } - return extractFromObj(obj, tokens, 0); -} -var init_utils7 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js -var InMemoryStore2; -var init_memory3 = __esm(() => { - init_base13(); - init_utils7(); - InMemoryStore2 = class extends BaseStore2 { - data = /* @__PURE__ */ new Map; - vectors = /* @__PURE__ */ new Map; - _indexConfig; - constructor(options) { - super(); - if (options?.index) - this._indexConfig = { - ...options.index, - __tokenizedFields: (options.index.fields ?? ["$"]).map((p) => [p, p === "$" ? [p] : tokenizePath(p)]) - }; - } - async batch(operations) { - const results = []; - const putOps = /* @__PURE__ */ new Map; - const searchOps = /* @__PURE__ */ new Map; - for (let i = 0;i < operations.length; i += 1) { - const op = operations[i]; - if ("key" in op && "namespace" in op && !("value" in op)) - results.push(this.getOperation(op)); - else if ("namespacePrefix" in op) { - const candidates = this.filterItems(op); - searchOps.set(i, [op, candidates]); - results.push(null); - } else if ("value" in op) { - const key = `${op.namespace.join(":")}:${op.key}`; - putOps.set(key, op); - results.push(null); - } else if ("matchConditions" in op) - results.push(this.listNamespacesOperation(op)); - } - if (searchOps.size > 0) - if (this._indexConfig?.embeddings) { - const queries = /* @__PURE__ */ new Set; - for (const [op] of searchOps.values()) - if (op.query) - queries.add(op.query); - const queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : []; - const queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])); - for (const [i, [op, candidates]] of searchOps.entries()) - if (op.query && queryVectors[op.query]) { - const queryVector = queryVectors[op.query]; - results[i] = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10); - } else - results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: undefined - })), op.offset ?? 0, op.limit ?? 10); - } else - for (const [i, [op, candidates]] of searchOps.entries()) - results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: undefined - })), op.offset ?? 0, op.limit ?? 10); - if (putOps.size > 0 && this._indexConfig?.embeddings) { - const toEmbed = this.extractTexts(Array.from(putOps.values())); - if (Object.keys(toEmbed).length > 0) { - const embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed)); - this.insertVectors(toEmbed, embeddings); - } - } - for (const op of putOps.values()) - this.putOperation(op); - return results; + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "davinci-002": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; } - getOperation(op) { - const namespaceKey = op.namespace.join(":"); - return this.data.get(namespaceKey)?.get(op.key) ?? null; + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; } - putOperation(op) { - const namespaceKey = op.namespace.join(":"); - if (!this.data.has(namespaceKey)) - this.data.set(namespaceKey, /* @__PURE__ */ new Map); - const namespaceMap = this.data.get(namespaceKey); - if (op.value === null) - namespaceMap.delete(op.key); - else { - const now = /* @__PURE__ */ new Date; - if (namespaceMap.has(op.key)) { - const item = namespaceMap.get(op.key); - item.value = op.value; - item.updatedAt = now; - } else - namespaceMap.set(op.key, { - value: op.value, - key: op.key, - namespace: op.namespace, - createdAt: now, - updatedAt: now - }); - } + case "ada": + case "babbage": + case "babbage-002": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; } - listNamespacesOperation(op) { - let namespaces = Array.from(this.data.keys()).map((ns3) => ns3.split(":")); - if (op.matchConditions && op.matchConditions.length > 0) - namespaces = namespaces.filter((ns3) => op.matchConditions.every((condition) => this.doesMatch(condition, ns3))); - if (op.maxDepth !== undefined) - namespaces = Array.from(new Set(namespaces.map((ns3) => ns3.slice(0, op.maxDepth).join(":")))).map((ns3) => ns3.split(":")); - namespaces.sort((a, b) => a.join(":").localeCompare(b.join(":"))); - return namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length)); + case "gpt-3.5-turbo-instruct-0914": + case "gpt-3.5-turbo-instruct": + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "gpt-3.5-turbo-1106": + case "gpt-35-turbo": + case "gpt-4-1106-preview": + case "gpt-4-vision-preview": + case "gpt-3.5-turbo-0125": + case "gpt-4-turbo": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": { + return "cl100k_base"; } - doesMatch(matchCondition, key) { - const { matchType, path: path2 } = matchCondition; - if (matchType === "prefix") { - if (path2.length > key.length) - return false; - return path2.every((pElem, index2) => { - const kElem = key[index2]; - return pElem === "*" || kElem === pElem; - }); - } else if (matchType === "suffix") { - if (path2.length > key.length) - return false; - return path2.every((pElem, index2) => { - const kElem = key[key.length - path2.length + index2]; - return pElem === "*" || kElem === pElem; - }); - } - throw new Error(`Unsupported match type: ${matchType}`); + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-2024-11-20": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "gpt-4o-search-preview": + case "gpt-4o-search-preview-2025-03-11": + case "gpt-4o-mini-search-preview": + case "gpt-4o-mini-search-preview-2025-03-11": + case "gpt-4o-audio-preview": + case "gpt-4o-audio-preview-2024-12-17": + case "gpt-4o-audio-preview-2024-10-01": + case "gpt-4o-mini-audio-preview": + case "gpt-4o-mini-audio-preview-2024-12-17": + case "o1": + case "o1-2024-12-17": + case "o1-mini": + case "o1-mini-2024-09-12": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-pro": + case "o1-pro-2025-03-19": + case "o3": + case "o3-2025-04-16": + case "o3-mini": + case "o3-mini-2025-01-31": + case "o4-mini": + case "o4-mini-2025-04-16": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": + case "gpt-4o-realtime-preview-2024-12-17": + case "gpt-4o-mini-realtime-preview": + case "gpt-4o-mini-realtime-preview-2024-12-17": + case "gpt-4.1": + case "gpt-4.1-2025-04-14": + case "gpt-4.1-mini": + case "gpt-4.1-mini-2025-04-14": + case "gpt-4.1-nano": + case "gpt-4.1-nano-2025-04-14": + case "gpt-4.5-preview": + case "gpt-4.5-preview-2025-02-27": + case "gpt-5": + case "gpt-5-2025-08-07": + case "gpt-5-nano": + case "gpt-5-nano-2025-08-07": + case "gpt-5-mini": + case "gpt-5-mini-2025-08-07": + case "gpt-5-chat-latest": { + return "o200k_base"; } - filterItems(op) { - const candidates = []; - for (const [namespace, items] of this.data.entries()) - if (namespace.startsWith(op.namespacePrefix.join(":"))) - candidates.push(...items.values()); - let filteredCandidates = candidates; - if (op.filter) - filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value))); - return filteredCandidates; + default: + throw new Error("Unknown model"); + } +} +var import_base64_js, __defProp3, __defNormalProp = (obj, key, value) => (key in obj) ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value, __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}, _Tiktoken = class { + specialTokens; + inverseSpecialTokens; + patStr; + textEncoder = new TextEncoder; + textDecoder = new TextDecoder("utf-8"); + rankMap = /* @__PURE__ */ new Map; + textMap = /* @__PURE__ */ new Map; + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split(` +`).filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = import_base64_js.default.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); } - scoreResults(candidates, queryVector, offset = 0, limit = 10) { - const flatItems = []; - const flatVectors = []; - const scoreless = []; - for (const item of candidates) { - const vectors = this.getVectors(item); - if (vectors.length) - for (const vector of vectors) { - flatItems.push(item); - flatVectors.push(vector); - } - else - scoreless.push(item); + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex(Object.keys(this.specialTokens)); + const ret = []; + const allowedSpecialSet = new Set(allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial); + const disallowedSpecialSet = new Set(disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter((x) => !allowedSpecialSet.has(x)) : disallowedSpecial); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error(`The text contains a special token that is not allowed: ${specialMatch[0]}`); } - const sortedResults = this.cosineSimilarity(queryVector, flatVectors).map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]); - const seen = /* @__PURE__ */ new Set; - const kept = []; - for (const [score, item] of sortedResults) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (seen.has(key)) - continue; - const ix = seen.size; - if (ix >= offset + limit) + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) break; - if (ix < offset) { - seen.add(key); + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match2 of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match2[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); continue; } - seen.add(key); - kept.push([score, item]); + ret.push(...bytePairEncode(piece, this.rankMap)); } - if (scoreless.length && kept.length < limit) - for (const item of scoreless.slice(0, limit - kept.length)) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (!seen.has(key)) { - seen.add(key); - kept.push([undefined, item]); - } - } - return kept.map(([score, item]) => ({ - ...item, - score - })); - } - paginateResults(results, offset, limit) { - return results.slice(offset, offset + limit); - } - extractTexts(ops) { - if (!ops.length || !this._indexConfig) - return {}; - const toEmbed = {}; - for (const op of ops) - if (op.value !== null && op.index !== false) { - const paths = op.index === null || op.index === undefined ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, tokenizePath(ix)]); - for (const [path2, field] of paths) { - const texts = getTextAtPath(op.value, field); - if (texts.length) - if (texts.length > 1) - texts.forEach((text, i) => { - if (!toEmbed[text]) - toEmbed[text] = []; - toEmbed[text].push([ - op.namespace, - op.key, - `${path2}.${i}` - ]); - }); - else { - if (!toEmbed[texts[0]]) - toEmbed[texts[0]] = []; - toEmbed[texts[0]].push([ - op.namespace, - op.key, - path2 - ]); - } - } - } - return toEmbed; + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; } - insertVectors(texts, embeddings) { - for (const [text, metadata] of Object.entries(texts)) { - const embedding = embeddings.shift(); - if (!embedding) - throw new Error(`No embedding found for text: ${text}`); - for (const [namespace, key, field] of metadata) { - const namespaceKey = namespace.join(":"); - if (!this.vectors.has(namespaceKey)) - this.vectors.set(namespaceKey, /* @__PURE__ */ new Map); - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(key)) - namespaceMap.set(key, /* @__PURE__ */ new Map); - namespaceMap.get(key).set(field, embedding); - } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0;i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; } } - getVectors(item) { - const namespaceKey = item.namespace.join(":"); - const itemKey = item.key; - if (!this.vectors.has(namespaceKey)) - return []; - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(itemKey)) - return []; - const itemMap = namespaceMap.get(itemKey); - const vectors = Array.from(itemMap.values()); - if (!vectors.length) - return []; - return vectors; - } - cosineSimilarity(X, Y) { - if (!Y.length) - return []; - const dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0)); - const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0)); - const magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))); - return dotProducts.map((dot, i) => { - const magnitude2 = magnitudes2[i]; - return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0; - }); - } - get indexConfig() { - return this._indexConfig; + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js -var BaseCache2 = class { - serde = new JsonPlusSerializer; - constructor(serde) { - this.serde = serde || this.serde; + return this.textDecoder.decode(mergedArray); } -}; -var init_base14 = __esm(() => { - init_jsonplus(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js -var init_memory4 = __esm(() => { - init_base14(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js -var init_cache = __esm(() => { - init_base14(); - init_memory4(); +}, Tiktoken; +var init_chunk_VL2OQCWN = __esm(() => { + import_base64_js = __toESM(require_base64_js(), 1); + __defProp3 = Object.defineProperty; + Tiktoken = _Tiktoken; + __publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => escapeRegex3(i)).join("|"), "g"); + }); }); -// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.2_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opente_u4ugm6khuu6u2d5gcbcvrymsdu/node_modules/@langchain/langgraph-checkpoint/dist/index.js -var init_dist3 = __esm(() => { - init_id2(); - init_types5(); - init_base12(); - init_memory2(); - init_base13(); - init_batch(); - init_memory3(); - init_base14(); - init_memory4(); - init_cache(); +// ../../node_modules/.pnpm/js-tiktoken@1.0.21/node_modules/js-tiktoken/dist/lite.js +var init_lite = __esm(() => { + init_chunk_VL2OQCWN(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/base.js -function isBaseChannel(obj) { - return obj != null && obj.lg_is_channel === true; -} -function getOnlyChannels(channels) { - if (channels[IS_ONLY_BASE_CHANNEL] === true) - return channels; - const newChannels = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) - continue; - const value = channels[k]; - if (isBaseChannel(value)) - newChannels[k] = value; - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; -} -function emptyChannels(channels, checkpoint) { - const filteredChannels = getOnlyChannels(channels); - const newChannels = {}; - for (const k in filteredChannels) { - if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) - continue; - const channelValue = checkpoint.channel_values[k]; - newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/tiktoken.js +async function getEncoding(encoding) { + if (!(encoding in cache)) + cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { + delete cache[encoding]; + throw e; + }); + return await cache[encoding]; } -function createCheckpoint(checkpoint, channels, step, options) { - let values; - if (channels === undefined) - values = checkpoint.channel_values; - else { - values = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) - continue; - try { - values[k] = channels[k].checkpoint(); - } catch (error51) { - if (error51.name === EmptyChannelError.unminifiable_name) {} else - throw error51; - } - } - } - return { - v: 4, - id: options?.id ?? uuid62(step), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: values, - channel_versions: checkpoint.channel_versions, - versions_seen: checkpoint.versions_seen - }; +async function encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); } -var BaseChannel = class { - ValueType; - UpdateType; - lg_is_channel = true; - consume() { - return false; - } - finish() { +var tiktoken_exports, cache, caller; +var init_tiktoken = __esm(() => { + init_runtime2(); + init_async_caller2(); + init_lite(); + tiktoken_exports = /* @__PURE__ */ __exportAll({ + encodingForModel: () => encodingForModel, + getEncoding: () => getEncoding + }); + cache = {}; + caller = /* @__PURE__ */ new AsyncCaller2({}); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/base.js +function isOpenAITool(tool) { + if (typeof tool !== "object" || !tool) return false; + if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) + return true; + return false; +} +var base_exports3, getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-5")) + return "gpt-5"; + if (modelName.startsWith("gpt-3.5-turbo-16k")) + return "gpt-3.5-turbo-16k"; + if (modelName.startsWith("gpt-3.5-turbo-")) + return "gpt-3.5-turbo"; + if (modelName.startsWith("gpt-4-32k")) + return "gpt-4-32k"; + if (modelName.startsWith("gpt-4-")) + return "gpt-4"; + if (modelName.startsWith("gpt-4o")) + return "gpt-4o"; + return modelName; +}, getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; } - isAvailable() { - try { - this.get(); - return true; - } catch (error51) { - if (error51.name === EmptyChannelError.unminifiable_name) - return false; - throw error51; - } +}, getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-5": + case "gpt-5-turbo": + case "gpt-5-turbo-preview": + return 400000; + case "gpt-4o": + case "gpt-4o-mini": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + return 128000; + case "gpt-4-turbo": + case "gpt-4-turbo-preview": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-0125-preview": + case "gpt-4-1106-preview": + return 128000; + case "gpt-4-32k": + case "gpt-4-32k-0314": + case "gpt-4-32k-0613": + return 32768; + case "gpt-4": + case "gpt-4-0314": + case "gpt-4-0613": + return 8192; + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-16k-0613": + return 16384; + case "gpt-3.5-turbo": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-1106": + case "gpt-3.5-turbo-0125": + return 4096; + case "text-davinci-003": + case "text-davinci-002": + return 4097; + case "text-davinci-001": + return 2049; + case "text-curie-001": + case "text-babbage-001": + case "text-ada-001": + return 2048; + case "code-davinci-002": + case "code-davinci-001": + return 8000; + case "code-cushman-001": + return 2048; + case "claude-3-5-sonnet-20241022": + case "claude-3-5-sonnet-20240620": + case "claude-3-opus-20240229": + case "claude-3-sonnet-20240229": + case "claude-3-haiku-20240307": + case "claude-2.1": + return 200000; + case "claude-2.0": + case "claude-instant-1.2": + return 1e5; + case "gemini-1.5-pro": + case "gemini-1.5-pro-latest": + case "gemini-1.5-flash": + case "gemini-1.5-flash-latest": + return 1e6; + case "gemini-pro": + case "gemini-pro-vision": + return 32768; + default: + return 4097; } - equals(other) { - return this === other; +}, calculateMaxTokens = async ({ prompt, modelName }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + } catch { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + numTokens = Math.ceil(prompt.length / 4); } -}, IS_ONLY_BASE_CHANNEL; -var init_base15 = __esm(() => { - init_errors5(); - init_dist3(); - IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/binop.js -var isBinaryOperatorAggregate = (value) => { - return value != null && value.lc_graph_name === "BinaryOperatorAggregate"; -}, BinaryOperatorAggregate; -var init_binop = __esm(() => { - init_constants3(); - init_errors5(); - init_base15(); - BinaryOperatorAggregate = class BinaryOperatorAggregate2 extends BaseChannel { - lc_graph_name = "BinaryOperatorAggregate"; - value; - operator; - initialValueFactory; - constructor(operator, initialValueFactory) { - super(); - this.operator = operator; - this.initialValueFactory = initialValueFactory; - this.value = initialValueFactory?.(); + return getModelContextSize(modelName) - numTokens; +}, getVerbosity = () => false, BaseLangChain, BaseLanguageModel; +var init_base5 = __esm(() => { + init_runtime2(); + init_utils3(); + init_caches(); + init_async_caller2(); + init_base4(); + init_prompt_values(); + init_tiktoken(); + base_exports3 = /* @__PURE__ */ __exportAll({ + BaseLangChain: () => BaseLangChain, + BaseLanguageModel: () => BaseLanguageModel, + calculateMaxTokens: () => calculateMaxTokens, + getEmbeddingContextSize: () => getEmbeddingContextSize, + getModelContextSize: () => getModelContextSize, + getModelNameForTiktoken: () => getModelNameForTiktoken, + isOpenAITool: () => isOpenAITool + }); + BaseLangChain = class extends Runnable { + verbose; + callbacks; + tags; + metadata; + get lc_attributes() { + return { + callbacks: undefined, + verbose: undefined + }; } - fromCheckpoint(checkpoint) { - const empty = new BinaryOperatorAggregate2(this.operator, this.initialValueFactory); - if (typeof checkpoint !== "undefined") - empty.value = checkpoint; - return empty; + constructor(params) { + super(params); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + this._addVersion("@langchain/core", "1.1.48"); } - update(values) { - let newValues = values; - if (!newValues.length) - return false; - if (this.value === undefined) { - const first = newValues[0]; - const [isOverwrite, overwriteVal] = _getOverwriteValue(first); - if (isOverwrite) - this.value = overwriteVal; - else - this.value = first; - newValues = newValues.slice(1); - } - let seenOverwrite = false; - for (const incoming of newValues) - if (_isOverwriteValue(incoming)) { - if (seenOverwrite) - throw new InvalidUpdateError("Can receive only one Overwrite value per step."); - const [, val] = _getOverwriteValue(incoming); - this.value = val; - seenOverwrite = true; - continue; - } else if (!seenOverwrite && this.value !== undefined) - this.value = this.operator(this.value, incoming); - return true; + _addVersion(pkg, version5) { + const existing = this.metadata?.versions; + this.metadata = { + ...this.metadata, + versions: { + ...typeof existing === "object" && existing !== null ? existing : {}, + [pkg]: version5 + } + }; } - get() { - if (this.value === undefined) - throw new EmptyChannelError; - return this.value; + }; + BaseLanguageModel = class extends BaseLangChain { + get callKeys() { + return [ + "stop", + "timeout", + "signal", + "tags", + "metadata", + "callbacks" + ]; } - checkpoint() { - if (this.value === undefined) - throw new EmptyChannelError; - return this.value; + caller; + cache; + constructor({ callbacks, callbackManager, ...params }) { + const { cache: cache2, ...rest } = params; + super({ + callbacks: callbacks ?? callbackManager, + ...rest + }); + if (typeof cache2 === "object") + this.cache = cache2; + else if (cache2) + this.cache = InMemoryCache.global(); + else + this.cache = undefined; + this.caller = new AsyncCaller2(params ?? {}); } - isAvailable() { - return this.value !== undefined; + _encoding; + async getNumTokens(content) { + let textContent; + if (typeof content === "string") + textContent = content; + else + textContent = content.map((item) => { + if (typeof item === "string") + return item; + if (item.type === "text" && "text" in item) + return item.text; + return ""; + }).join(""); + let numTokens = Math.ceil(textContent.length / 4); + if (!this._encoding) + try { + this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); + } catch (error90) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error90); + } + if (this._encoding) + try { + numTokens = this._encoding.encode(textContent).length; + } catch (error90) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error90); + } + return numTokens; } - equals(other) { - if (this === other) - return true; - if (!isBinaryOperatorAggregate(other)) - return false; - return this.operator === other.operator; + static _convertInputToPromptValue(input) { + if (typeof input === "string") + return new StringPromptValue(input); + else if (Array.isArray(input)) + return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); + else + return input; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/last_value.js -var LastValue, LastValueAfterFinish; -var init_last_value = __esm(() => { - init_errors5(); - init_base15(); - LastValue = class LastValue2 extends BaseChannel { - lc_graph_name = "LastValue"; - value = []; - constructor(initialValueFactory) { - super(); - this.initialValueFactory = initialValueFactory; - if (initialValueFactory) - this.value = [initialValueFactory()]; + _identifyingParams() { + return {}; } - fromCheckpoint(checkpoint) { - const empty = new LastValue2(this.initialValueFactory); - if (typeof checkpoint !== "undefined") - empty.value = [checkpoint]; - return empty; + _getSerializedCacheKeyParametersForCall({ config: config3, ...callOptions }) { + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType() + }; + return Object.entries(params).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); } - update(values) { - if (values.length === 0) - return false; - if (values.length !== 1) - throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this.value = [values[values.length - 1]]; - return true; + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType() + }; } - get() { - if (this.value.length === 0) - throw new EmptyChannelError; - return this.value[0]; + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); } - checkpoint() { - if (this.value.length === 0) - throw new EmptyChannelError; - return this.value[0]; + get profile() { + return {}; } - isAvailable() { - return this.value.length !== 0; + _filterInvocationParamsForTracing(params) { + const { tools, functions, messages, response_format, ...rest } = params; + return rest; } }; - LastValueAfterFinish = class LastValueAfterFinish2 extends BaseChannel { - lc_graph_name = "LastValueAfterFinish"; - value = []; - finished = false; - fromCheckpoint(checkpoint) { - const empty = new LastValueAfterFinish2; - if (typeof checkpoint !== "undefined") { - const [value, finished] = checkpoint; - empty.value = [value]; - empty.finished = finished; - } - return empty; - } - update(values) { - if (values.length === 0) - return false; - this.finished = false; - this.value = [values[values.length - 1]]; - return true; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/utils.js +function castStandardMessageContent(message) { + const Cls = message.constructor; + return new Cls({ + ...message, + content: message.contentBlocks, + response_metadata: { + ...message.response_metadata, + output_version: "v1" } - get() { - if (this.value.length === 0 || !this.finished) - throw new EmptyChannelError; - return this.value[0]; + }); +} +var iife3 = (fn) => fn(); +var init_utils5 = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/passthrough.js +var RunnablePassthrough; +var init_passthrough = __esm(() => { + init_config(); + init_stream(); + init_base4(); + RunnablePassthrough = class extends Runnable { + static lc_name() { + return "RunnablePassthrough"; } - checkpoint() { - if (this.value.length === 0) - return; - return [this.value[0], this.finished]; + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + func; + constructor(fields) { + super(fields); + if (fields) + this.func = fields.func; } - consume() { - if (this.finished) { - this.finished = false; - this.value = []; - return true; - } - return false; + async invoke(input, options) { + const config3 = ensureConfig(options); + if (this.func) + await this.func(input, config3); + return this._callWithConfig((input2) => Promise.resolve(input2), input, config3); } - finish() { - if (!this.finished && this.value.length > 0) { - this.finished = true; - return true; + async* transform(generator, options) { + const config3 = ensureConfig(options); + let finalOutput; + let finalOutputSupported = true; + for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config3)) { + yield chunk; + if (finalOutputSupported) + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = undefined; + finalOutputSupported = false; + } } - return false; + if (this.func && finalOutput !== undefined) + await this.func(finalOutput, config3); } - isAvailable() { - return this.value.length !== 0 && this.finished; + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/annotation.js -function getChannel(reducer) { - if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) - return new BinaryOperatorAggregate(reducer.reducer, reducer.default); - if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) - return new BinaryOperatorAggregate(reducer.value, reducer.default); - return new LastValue; -} -var AnnotationRoot = class { - lc_graph_name = "AnnotationRoot"; - spec; - constructor(s) { - this.spec = s; - } - static isInstance(value) { - return typeof value === "object" && value !== null && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot"; - } -}, Annotation = function(annotation) { - if (annotation) - return getChannel(annotation); - else - return new LastValue; -}; -var init_annotation = __esm(() => { - init_binop(); - init_last_value(); - Annotation.Root = (sd) => new AnnotationRoot(sd); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/utils/config.js -function propagateConfigurableToMetadata(configurable, metadata) { - if (!configurable) - return metadata; - const result = metadata ?? {}; - for (const key of PROPAGATE_TO_METADATA) { - if (key in result) - continue; - const value = configurable[key]; - if (value !== undefined) - result[key] = value; - } - return result; -} -function ensureLangGraphConfig(...configs) { - const empty = { - tags: [], - metadata: {}, - callbacks: undefined, - recursionLimit: DEFAULT_RECURSION_LIMIT, - configurable: {} +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/router.js +var RouterRunnable; +var init_router = __esm(() => { + init_config(); + init_base4(); + RouterRunnable = class extends Runnable { + static lc_name() { + return "RouterRunnable"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnables; + constructor(fields) { + super(fields); + this.runnables = fields.runnables; + } + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) + throw new Error(`No runnable associated with key "${key}".`); + return runnable.invoke(actualInput, ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + if (keys.find((key) => this.runnables[key] === undefined) !== undefined) + throw new Error(`One or more keys do not have a corresponding runnable.`); + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0;i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i2) => runnables[i2].invoke(actualInput, optionsList[i2])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); + } + return batchResults.flat(); + } + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) + throw new Error(`No runnable associated with key "${key}".`); + return runnable.stream(actualInput, options); + } }; - const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (implicitConfig !== undefined) { - for (const [k, v] of Object.entries(implicitConfig)) - if (v !== undefined) - if (COPIABLE_KEYS.includes(k)) { - let copiedValue; - if (Array.isArray(v)) - copiedValue = [...v]; - else if (typeof v === "object") - if (k === "callbacks" && "copy" in v && typeof v.copy === "function") - copiedValue = v.copy(); - else - copiedValue = { ...v }; - else - copiedValue = v; - empty[k] = copiedValue; - } else - empty[k] = v; - } - for (const config2 of configs) { - if (config2 === undefined) - continue; - for (const [k, v] of Object.entries(config2)) - if (v !== undefined && CONFIG_KEYS.includes(k)) - empty[k] = v; - } - empty.metadata = propagateConfigurableToMetadata(empty.configurable, empty.metadata) ?? {}; - return empty; -} -function getStore(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(` -`)); - return runConfig?.store; -} -function getWriter(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join(` -`)); - return runConfig?.writer || runConfig?.configurable?.writer; -} -function getConfig() { - return AsyncLocalStorageProviderSingleton2.getRunnableConfig(); -} -function getCurrentTaskInput(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(` -`)); - if (runConfig.configurable?.["__pregel_scratchpad"]?.currentTaskInput === undefined) - throw new Error("BUG: internal scratchpad not initialized."); - return runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput; -} -function recastCheckpointNamespace(namespace) { - return namespace.split("|").filter((part) => !part.match(/^\d+$/)).map((part) => part.split(":")[0]).join("|"); -} -function getParentCheckpointNamespace(namespace) { - const parts = namespace.split("|"); - while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) - parts.pop(); - return parts.slice(0, -1).join("|"); -} -var COPIABLE_KEYS, CONFIG_KEYS, DEFAULT_RECURSION_LIMIT = 25, PROPAGATE_TO_METADATA; -var init_config2 = __esm(() => { - init_constants3(); - init_singletons(); - COPIABLE_KEYS = [ - "tags", - "metadata", - "callbacks", - "configurable" - ]; - CONFIG_KEYS = [ - "tags", - "metadata", - "callbacks", - "runName", - "maxConcurrency", - "recursionLimit", - "configurable", - "runId", - "outputKeys", - "streamMode", - "store", - "writer", - "interrupt", - "context", - "interruptBefore", - "interruptAfter", - "checkpointDuring", - "durability", - "signal", - "executionInfo", - "serverInfo" - ]; - PROPAGATE_TO_METADATA = new Set([ - "thread_id", - "checkpoint_id", - "checkpoint_ns", - "task_id", - "run_id", - "assistant_id", - "graph_id" - ]); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/stream-channel.js -function isStreamChannel(value) { - return StreamChannel.isInstance(value); -} -var STREAM_CHANNEL_BRAND, StreamChannel; -var init_stream_channel = __esm(() => { - STREAM_CHANNEL_BRAND = Symbol.for("langgraph.stream_channel"); - StreamChannel = class StreamChannel2 { - [STREAM_CHANNEL_BRAND] = true; - channelName; - #items = []; - #waiters = []; - #done = false; - #error; - #onPush; - constructor(name) { - this.channelName = name; - } - static local() { - return new StreamChannel2; - } - static remote(name) { - return new StreamChannel2(name); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/branch.js +var RunnableBranch; +var init_branch = __esm(() => { + init_config(); + init_stream(); + init_base4(); + RunnableBranch = class extends Runnable { + static lc_name() { + return "RunnableBranch"; } - static isInstance(value) { - return typeof value === "object" && value !== null && STREAM_CHANNEL_BRAND in value && value[STREAM_CHANNEL_BRAND] === true; + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + default; + branches; + constructor(fields) { + super(fields); + this.branches = fields.branches; + this.default = fields.default; } - push(item) { - this.#items.push(item); - this.#wake(); - this.#onPush?.(item); + static from(branches) { + if (branches.length < 1) + throw new Error("RunnableBranch requires at least one branch"); + const coercedBranches = branches.slice(0, -1).map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch + }); } - iterate(startAt = 0) { - let cursor = startAt; - return { next: async () => { - while (true) { - if (cursor < this.#items.length) - return { - value: this.#items[cursor++], - done: false - }; - if (this.#done) { - if (this.#error) - throw this.#error; - return { - value: undefined, - done: true - }; - } - await new Promise((resolve2) => this.#waiters.push(resolve2)); + async _invoke(input, config3, runManager) { + let result; + for (let i = 0;i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + if (await condition.invoke(input, patchConfig(config3, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { + result = await branchRunnable.invoke(input, patchConfig(config3, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); + break; } - } }; + } + if (!result) + result = await this.default.invoke(input, patchConfig(config3, { callbacks: runManager?.getChild("branch:default") })); + return result; } - toAsyncIterable(startAt = 0) { - return { [Symbol.asyncIterator]: () => this.iterate(startAt) }; + async invoke(input, config3 = {}) { + return this._callWithConfig(this._invoke, input, config3); } - toEventStream(options = {}) { - const encoder2 = new TextEncoder; - const iterator = this.iterate(options.startAt); - const event = options.event ?? this.channelName; - const serialize2 = options.serialize ?? ((item) => JSON.stringify(item) ?? "null"); - return new ReadableStream({ - async pull(controller) { - try { - const next = await iterator.next(); - if (next.done) { - controller.close(); - return; + async* _streamIterator(input, config3) { + const runManager = await (await getCallbackManagerForConfig(config3))?.handleChainStart(this.toJSON(), _coerceToDict2(input, "input"), config3?.runId, undefined, undefined, undefined, config3?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream2; + try { + for (let i = 0;i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + if (await condition.invoke(input, patchConfig(config3, { callbacks: runManager?.getChild(`condition:${i + 1}`) }))) { + stream2 = await branchRunnable.stream(input, patchConfig(config3, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); + for await (const chunk of stream2) { + yield chunk; + if (finalOutputSupported) + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = undefined; + finalOutputSupported = false; + } } - const lines = []; - if (event != null) - lines.push(`event: ${event}`); - for (const line of serialize2(next.value).split(/\r\n|\r|\n/)) - lines.push(`data: ${line}`); - controller.enqueue(encoder2.encode(`${lines.join(` -`)} - -`)); - } catch (error51) { - controller.error(error51); + break; + } + } + if (stream2 === undefined) { + stream2 = await this.default.stream(input, patchConfig(config3, { callbacks: runManager?.getChild("branch:default") })); + for await (const chunk of stream2) { + yield chunk; + if (finalOutputSupported) + if (finalOutput === undefined) + finalOutput = chunk; + else + try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = undefined; + finalOutputSupported = false; + } } - }, - async cancel() { - await iterator.return?.(); } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}); + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/history.js +var RunnableWithMessageHistory; +var init_history = __esm(() => { + init_base(); + init_ai(); + init_human(); + init_base4(); + init_messages(); + init_passthrough(); + RunnableWithMessageHistory = class extends RunnableBinding { + runnable; + inputMessagesKey; + outputMessagesKey; + historyMessagesKey; + getMessageHistory; + constructor(fields) { + let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) + historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); + const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run2, config4) => this._exitHistory(run2, config4 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); + const config3 = fields.config ?? {}; + super({ + ...fields, + config: config3, + bound }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; } - get(index2) { - if (index2 < 0 || index2 >= this.#items.length) - throw new RangeError(`StreamChannel index ${index2} out of bounds (size=${this.#items.length})`); - return this.#items[index2]; + _getInputMessages(inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) + key = this.inputMessagesKey; + else if (Object.keys(inputValue).length === 1) + key = Object.keys(inputValue)[0]; + else + key = "input"; + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) + parsedInputValue = inputValue[key][0]; + else + parsedInputValue = inputValue[key]; + } else + parsedInputValue = inputValue; + if (typeof parsedInputValue === "string") + return [new HumanMessage(parsedInputValue)]; + else if (Array.isArray(parsedInputValue)) + return parsedInputValue; + else if (isBaseMessage(parsedInputValue)) + return [parsedInputValue]; + else + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. +Got ${JSON.stringify(parsedInputValue, null, 2)}`); } - get size() { - return this.#items.length; + _getOutputMessages(outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== undefined) + key = this.outputMessagesKey; + else if (Object.keys(outputValue).length === 1) + key = Object.keys(outputValue)[0]; + else + key = "output"; + if (outputValue.generations !== undefined) + parsedOutputValue = outputValue.generations[0][0].message; + else + parsedOutputValue = outputValue[key]; + } else + parsedOutputValue = outputValue; + if (typeof parsedOutputValue === "string") + return [new AIMessage(parsedOutputValue)]; + else if (Array.isArray(parsedOutputValue)) + return parsedOutputValue; + else if (isBaseMessage(parsedOutputValue)) + return [parsedOutputValue]; + else + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); } - get done() { - return this.#done; + async _enterHistory(input, kwargs) { + const messages = await (kwargs?.configurable?.messageHistory).getMessages(); + if (this.historyMessagesKey === undefined) + return messages.concat(this._getInputMessages(input)); + return messages; } - close() { - this.#done = true; - this.#wake(); + async _exitHistory(run2, config3) { + const history = config3.configurable?.messageHistory; + let inputs; + if (Array.isArray(run2.inputs) && Array.isArray(run2.inputs[0])) + inputs = run2.inputs[0]; + else + inputs = run2.inputs; + let inputMessages = this._getInputMessages(inputs); + if (this.historyMessagesKey === undefined) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + const outputValue = run2.outputs; + if (!outputValue) + throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run2, null, 2)}`); + const outputMessages = this._getOutputMessages(outputValue); + await history.addMessages([...inputMessages, ...outputMessages]); } - fail(err) { - this.#error = err; - this.#done = true; - this.#wake(); + async _mergeConfig(...configs) { + const config3 = await super._mergeConfig(...configs); + if (!config3.configurable || !config3.configurable.sessionId) { + const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream() +eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify({ configurable: { sessionId: "123" } })})`); + } + const { sessionId } = config3.configurable; + config3.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config3; } - _wire(fn) { - this.#onPush = fn; + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/runnables/index.js +var runnables_exports; +var init_runnables = __esm(() => { + init_runtime2(); + init_config(); + init_signal(); + init_base4(); + init_passthrough(); + init_router(); + init_branch(); + init_history(); + runnables_exports = /* @__PURE__ */ __exportAll({ + RouterRunnable: () => RouterRunnable, + Runnable: () => Runnable, + RunnableAssign: () => RunnableAssign, + RunnableBinding: () => RunnableBinding, + RunnableBranch: () => RunnableBranch, + RunnableEach: () => RunnableEach, + RunnableLambda: () => RunnableLambda, + RunnableMap: () => RunnableMap, + RunnableParallel: () => RunnableParallel, + RunnablePassthrough: () => RunnablePassthrough, + RunnablePick: () => RunnablePick, + RunnableRetry: () => RunnableRetry, + RunnableSequence: () => RunnableSequence, + RunnableToolLike: () => RunnableToolLike, + RunnableWithFallbacks: () => RunnableWithFallbacks, + RunnableWithMessageHistory: () => RunnableWithMessageHistory, + _coerceToRunnable: () => _coerceToRunnable, + ensureConfig: () => ensureConfig, + getCallbackManagerForConfig: () => getCallbackManagerForConfig, + mergeConfigs: () => mergeConfigs, + patchConfig: () => patchConfig, + pickRunnableConfigKeys: () => pickRunnableConfigKeys, + raceWithSignal: () => raceWithSignal + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/base.js +var BaseLLMOutputParser, BaseOutputParser, OutputParserException; +var init_base6 = __esm(() => { + init_errors3(); + init_base4(); + init_runnables(); + BaseLLMOutputParser = class extends Runnable { + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); } - _close() { - this.close(); + _baseMessageToString(message) { + return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); } - _fail(err) { - this.fail(err); + _baseMessageContentToString(content) { + return JSON.stringify(content); } - [Symbol.asyncIterator]() { - return this.iterate(); + async invoke(input, options) { + if (typeof input === "string") + return this._callWithConfig(async (input2, options2) => this.parseResult([{ text: input2 }], options2?.callbacks), input, { + ...options, + runType: "parser" + }); + else + return this._callWithConfig(async (input2, options2) => this.parseResult([{ + message: input2, + text: this._baseMessageToString(input2) + }], options2?.callbacks), input, { + ...options, + runType: "parser" + }); } - #wake() { - const waiters = this.#waiters.splice(0); - for (const w of waiters) - w(); + }; + BaseOutputParser = class extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + _type() { + throw new Error("_type not implemented"); + } + }; + OutputParserException = class extends Error { + llmOutput; + observation; + sendToLLM; + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/convert.js -function unwrapMessagesPayload(payload) { - if (!Array.isArray(payload) || payload.length !== 2) - return { data: payload }; - const [data, metadata] = payload; - if (metadata == null || typeof metadata !== "object") - return { data: payload }; - const record2 = metadata; - const node = typeof record2.langgraph_node === "string" ? record2.langgraph_node : undefined; - const runId = typeof record2.run_id === "string" ? record2.run_id : undefined; - return { - data: runId != null && data != null && typeof data === "object" ? { - ...data, - run_id: runId - } : data, - node - }; -} -function convertToProtocolEvent({ namespace: ns3, mode, payload, seq, meta: meta3 }) { - const timestamp = Date.now(); - const base = { type: "event" }; - switch (mode) { - case "messages": { - const { data, node } = unwrapMessagesPayload(payload); - return [{ - ...base, - seq, - method: "messages", - params: { - namespace: ns3, - timestamp, - ...node ? { node } : {}, - data - } - }]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/transform.js +var BaseTransformOutputParser, BaseCumulativeTransformOutputParser; +var init_transform = __esm(() => { + init_base(); + init_utils3(); + init_outputs(); + init_base6(); + init_esm(); + BaseTransformOutputParser = class extends BaseOutputParser { + async* _transform(inputGenerator) { + for await (const chunk of inputGenerator) + if (typeof chunk === "string") + yield this.parseResult([{ text: chunk }]); + else + yield this.parseResult([{ + message: chunk, + text: this._baseMessageToString(chunk) + }]); } - case "tools": - return [{ - ...base, - seq, - method: "tools", - params: { - namespace: ns3, - timestamp, - data: convertToolsPayload(payload) - } - }]; - case "values": { - const events = []; - if (meta3?.checkpoint != null) - events.push({ - ...base, - seq, - method: "checkpoints", - params: { - namespace: ns3, - timestamp, - data: meta3.checkpoint - } - }); - events.push({ - ...base, - seq: meta3?.checkpoint != null ? seq + 1 : seq, - method: "values", - params: { - namespace: ns3, - timestamp, - data: payload - } + async* transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser" }); - return events; } - case "updates": { - const data = convertUpdatesPayload(payload); - return [{ - ...base, - seq, - method: "updates", - params: { - namespace: ns3, - timestamp, - ...typeof data.node === "string" ? { node: data.node } : {}, - data - } - }]; + }; + BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { + diff = false; + constructor(fields) { + super(fields); + this.diff = fields?.diff ?? this.diff; } - case "custom": { - const data = typeof payload === "object" && payload !== null && !Array.isArray(payload) && "name" in payload ? payload : { payload }; - return [{ - ...base, - seq, - method: "custom", - params: { - namespace: ns3, - timestamp, - data + async* _transform(inputGenerator) { + let prevParsed; + let accGen; + for await (const chunk of inputGenerator) { + if (typeof chunk !== "string" && typeof chunk.content !== "string") + throw new Error("Cannot handle non-string output."); + let chunkGen; + if (isBaseMessageChunk(chunk)) { + if (typeof chunk.content !== "string") + throw new Error("Cannot handle non-string message output."); + chunkGen = new ChatGenerationChunk({ + message: chunk, + text: chunk.content + }); + } else if (isBaseMessage(chunk)) { + if (typeof chunk.content !== "string") + throw new Error("Cannot handle non-string message output."); + chunkGen = new ChatGenerationChunk({ + message: convertToChunk(chunk), + text: chunk.content + }); + } else + chunkGen = new GenerationChunk({ text: chunk }); + if (accGen === undefined) + accGen = chunkGen; + else + accGen = accGen.concat(chunkGen); + const parsed = await this.parsePartialResult([accGen]); + if (parsed !== undefined && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { + if (this.diff) + yield this._diff(prevParsed, parsed); + else + yield parsed; + prevParsed = parsed; } - }]; + } } - case "tasks": - return [{ - ...base, - seq, - method: "tasks", - params: { - namespace: ns3, - timestamp, - data: payload - } - }]; - default: - return []; - } -} -function convertToolsPayload(payload) { - if (typeof payload !== "object" || payload === null) - return { - event: "tool-error", - tool_call_id: "", - message: "Unexpected tools payload shape" - }; - const p = payload; - const tool_call_id = String(p.toolCallId ?? ""); - switch (p.event) { - case "on_tool_start": - return { - event: "tool-started", - tool_call_id, - tool_name: String(p.name ?? "unknown"), - input: p.input - }; - case "on_tool_event": - return { - event: "tool-output-delta", - tool_call_id, - delta: typeof p.data === "string" ? p.data : JSON.stringify(p.data ?? "") - }; - case "on_tool_end": - return { - event: "tool-finished", - tool_call_id, - output: p.output - }; - case "on_tool_error": { - const err = p.error; - return { - event: "tool-error", - tool_call_id, - message: typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err ?? "unknown error") - }; + getFormatInstructions() { + return ""; } - default: - return { - event: "tool-error", - tool_call_id: "", - message: `Unknown tool event: ${String(p.event)}` - }; - } -} -function convertUpdatesPayload(payload) { - if (typeof payload !== "object" || payload === null) - return { values: {} }; - const entries = Object.entries(payload); - if (entries.length === 0) - return { values: {} }; - const [node, values] = entries[0]; - return { - node, - values: typeof values === "object" && values !== null ? values : { value: values } }; -} -var STREAM_EVENTS_V3_MODES; -var init_convert = __esm(() => { - STREAM_EVENTS_V3_MODES = [ - "values", - "updates", - "messages", - "tools", - "custom", - "tasks" - ]; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/mux.js -function isPromiseLike(value) { - return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; -} -async function pump(source, mux) { - let seq = 0; - try { - for await (const chunk of source) { - const [ns3, mode, payload, meta3] = chunk; - if (mode === "values" && isInterrupted(payload)) { - const interrupts = payload[INTERRUPT]; - mux.markInterrupted(interrupts.map((i) => ({ - interruptId: i.id ?? "", - payload: i.value - }))); - } - const events = convertToProtocolEvent({ - namespace: ns3, - mode, - payload, - seq, - meta: meta3 - }); - seq += events.length; - for (const event of events) - mux.push(ns3, event); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/json_patch.js +var json_patch_exports; +var init_json_patch = __esm(() => { + init_runtime2(); + init_core5(); + init_duplex(); + init_fast_json_patch(); + json_patch_exports = /* @__PURE__ */ __exportAll({ + applyPatch: () => applyPatch, + compare: () => compare + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/json.js +var JsonOutputParser; +var init_json2 = __esm(() => { + init_json(); + init_duplex(); + init_transform(); + init_json_patch(); + JsonOutputParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputParser"; } - } catch (err) { - mux.fail(err); - return; - } - mux.close(); -} -function nsKey(ns3) { - return ns3.join("\x00"); -} -function hasPrefix(ns3, prefix) { - if (prefix.length > ns3.length) - return false; - for (let i = 0;i < prefix.length; i += 1) - if (ns3[i] !== prefix[i]) - return false; - return true; -} -var RESOLVE_VALUES, REJECT_VALUES, StreamMux = class { - _events = StreamChannel.local(); - _discoveries = StreamChannel.local(); - #nextEmitSeq = 0; - #closed = false; - #error; - #interrupted = false; - #currentNamespace = []; - #transformers = []; - #channels = []; - #streamMap = /* @__PURE__ */ new Map; - #latestValues = /* @__PURE__ */ new Map; - #interrupts = []; - #finalValues = []; - register(path2, stream2) { - this.#streamMap.set(nsKey(path2), stream2); - } - addTransformer(transformer) { - const snapshot = this._events.size; - this.#transformers.push(transformer); - if (transformer.onRegister) - transformer.onRegister({ push: (ns3, event) => this.push(ns3, event) }); - for (let i = 0;i < snapshot; i += 1) - transformer.process(this._events.get(i)); - if (this.#closed) - if (this.#error !== undefined) - transformer.fail?.(this.#error); - else - transformer.finalize?.(); - } - wireChannels(projection) { - for (const [key, value] of Object.entries(projection)) { - if (isStreamChannel(value)) { - this.#channels.push(value); - if (typeof value.channelName !== "string") - continue; - value._wire((item) => { - this._events.push({ - type: "event", - seq: this.#nextEmitSeq++, - method: value.channelName, - params: { - namespace: this.#currentNamespace, - timestamp: Date.now(), - data: item - } - }); - }); - continue; - } - if (isPromiseLike(value)) - this.#finalValues.push({ - name: key, - promise: Promise.resolve(value) - }); + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + _concatOutputChunks(first, second) { + if (this.diff) + return super._concatOutputChunks(first, second); + return second; } - } - push(ns3, event) { - if (event.method === "values") - this.#latestValues.set(nsKey(ns3), event.params.data); - const outerNamespace = this.#currentNamespace; - this.#currentNamespace = ns3; - let keep = true; - for (const transformer of this.#transformers) - if (!transformer.process(event)) - keep = false; - this.#currentNamespace = outerNamespace; - if (keep) - this._events.push({ - ...event, - seq: this.#nextEmitSeq++ - }); - } - close() { - this.#closed = true; - for (const [key, values] of this.#latestValues.entries()) { - const ns3 = key ? key.split("\x00") : []; - this.#streamMap.get(nsKey(ns3))?.[RESOLVE_VALUES](values); + _diff(prev, next) { + if (!next) + return; + if (!prev) + return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); } - const finalizePromises = []; - for (const transformer of this.#transformers) { - const result = transformer.finalize?.(); - if (result != null && typeof result.then === "function") - finalizePromises.push(result); + async parsePartialResult(generations) { + return parseJsonMarkdown(generations[0].text); } - for (const channel of this.#channels) - channel._close(); - const finalValues = this.#finalValues; - if (finalValues.length === 0 && finalizePromises.length === 0) { - this._events.close(); - this._discoveries.close(); - } else - Promise.allSettled([...finalizePromises, ...finalValues.map(async ({ name, promise: promise2 }) => { - try { - const resolved = await promise2; - if (!this._events.done) - this._events.push({ - type: "event", - seq: this.#nextEmitSeq++, - method: "custom", - params: { - namespace: [], - timestamp: Date.now(), - data: { - name, - payload: resolved - } - } - }); - } catch {} - })]).then(() => { - this._events.close(); - this._discoveries.close(); - }); - for (const stream2 of this.#streamMap.values()) - stream2[RESOLVE_VALUES](undefined); - } - fail(err) { - this.#closed = true; - this.#error = err; - for (const transformer of this.#transformers) - transformer.fail?.(err); - for (const channel of this.#channels) - channel._fail(err); - this._events.fail(err); - this._discoveries.fail(err); - for (const stream2 of this.#streamMap.values()) - stream2[REJECT_VALUES](err); - } - markInterrupted(interrupts) { - this.#interrupted = true; - this.#interrupts.push(...interrupts); - } - get interrupted() { - return this.#interrupted; - } - get interrupts() { - return this.#interrupts; - } - subscribeEvents(path2, startAt = 0) { - const base = this._events.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return result; - if (hasPrefix(result.value.params.namespace, path2)) - return result; - } - } }; - } -}; -var init_mux = __esm(() => { - init_constants3(); - init_stream_channel(); - init_convert(); - RESOLVE_VALUES = Symbol("resolveValues"); - REJECT_VALUES = Symbol("rejectValues"); + async parse(text) { + return parseJsonMarkdown(text, JSON.parse); + } + getFormatInstructions() { + return ""; + } + _baseMessageToString(message) { + return message.text; + } + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/transformers/lifecycle.js -function filterLifecycleEntries(log, path2, startAt = 0) { - return { [Symbol.asyncIterator]() { - const base = log.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - if (hasPrefix(result.value.namespace, path2)) - return { - value: result.value, - done: false - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/standard_schema.js +var StandardSchemaOutputParser; +var init_standard_schema2 = __esm(() => { + init_json(); + init_base6(); + init_json2(); + StandardSchemaOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StandardSchemaOutputParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "standard_schema" + ]; + schema; + constructor(schema) { + super(); + this.schema = schema; + } + static fromSerializableSchema(schema) { + return new this(schema); + } + async parse(text) { + try { + const json2 = parseJsonMarkdown(text, JSON.parse); + const result = await this.schema["~standard"].validate(json2); + if (result.issues) + throw new Error(`Validation failed: ${JSON.stringify(result.issues)}`); + return result.value; + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); } - } }; - } }; -} -function defaultGuessGraphName(ns3) { - if (ns3.length === 0) - return DEFAULT_ROOT_GRAPH_NAME; - const last = ns3[ns3.length - 1]; - const colon = last.indexOf(":"); - return colon === -1 ? last : last.slice(0, colon); -} -function defaultSerializeError(err) { - if (err instanceof Error) - return err.message; - if (typeof err === "string") - return err; - try { - return JSON.stringify(err); - } catch { - return String(err); - } -} -function isRecord(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function extractCause(data) { - if (!isRecord(data)) - return; - if (data.event !== "started") - return; - const cause = data.cause; - if (!isRecord(cause)) - return; - if (typeof cause.type !== "string") - return; - return cause; -} -function extractTaskResultCompletion(data) { - if (!isRecord(data)) - return; - if (!("result" in data)) - return; - if (typeof data.name !== "string") - return; - if (typeof data.id !== "string") - return; - if (data.name.startsWith("__")) - return; - return { - name: data.name, - id: data.id - }; -} -function createLifecycleTransformer(options = {}) { - const rootGraphName = options.rootGraphName ?? DEFAULT_ROOT_GRAPH_NAME; - const initialStatus = options.initialStatus ?? "running"; - const emitRootOnRegister = options.emitRootOnRegister ?? true; - const getGraphName = options.getGraphName ?? defaultGuessGraphName; - const serializeError = options.serializeError ?? defaultSerializeError; - const getTerminalStatusOverride = options.getTerminalStatusOverride; - const log = StreamChannel.local(); - const namespaces = /* @__PURE__ */ new Map; - const namespaceCause = /* @__PURE__ */ new Map; - const pendingInterruptIds = /* @__PURE__ */ new Set; - const pendingCompletions = []; - let emitter; - let inSelfEmit = 0; - let finalized = false; - const resolveGraphName = (ns3) => ns3.length === 0 ? rootGraphName : getGraphName(ns3); - const emit = (ns3, status, extras) => { - const key = nsKey(ns3); - let current = namespaces.get(key); - const graphName = current?.graphName ?? resolveGraphName(ns3); - if (current != null && current.status === status && current.graphName === graphName && extras?.error == null) - return; - if (current == null) { - current = { - namespace: ns3, - graphName, - status - }; - namespaces.set(key, current); - } else - current.status = status; - const data = { - event: status, - graph_name: graphName, - ...extras?.cause != null ? { cause: extras.cause } : {}, - ...extras?.error != null ? { error: extras.error } : {} - }; - const timestamp = Date.now(); - log.push({ - namespace: ns3, - timestamp, - ...data - }); - if (ns3.length === 0 && !emitRootOnRegister) - return; - if (emitter == null) - return; - inSelfEmit += 1; - try { - emitter.push(ns3, { - type: "event", - seq: 0, - method: "lifecycle", - params: { - namespace: ns3, - timestamp, - data - } - }); - } finally { - inSelfEmit -= 1; } - }; - const trackNamespace = (ns3) => { - const key = nsKey(ns3); - let rec = namespaces.get(key); - if (rec == null) { - rec = { - namespace: ns3, - graphName: resolveGraphName(ns3), - status: undefined - }; - namespaces.set(key, rec); + _baseMessageToString(message) { + return message.text; } - return rec; - }; - const flushPendingCompletions = () => { - if (pendingCompletions.length === 0) - return; - const toFlush = pendingCompletions.splice(0, pendingCompletions.length); - for (const completion of toFlush) { - const key = nsKey(completion.namespace); - const rec = namespaces.get(key); - if (rec == null || rec.status !== "started") - continue; - emit(completion.namespace, "completed"); + getFormatInstructions() { + return ""; } }; - const enqueueCompletion = (completion) => { - const key = nsKey(completion.namespace); - const rec = namespaces.get(key); - if (rec == null || rec.status !== "started") - return; - if (pendingCompletions.some((pending) => nsKey(pending.namespace) === key)) - return; - pendingCompletions.push(completion); - }; - const removePendingNodeCompletions = (parent, node) => { - for (let index2 = pendingCompletions.length - 1;index2 >= 0; index2 -= 1) { - const pending = pendingCompletions[index2]; - if (pending.source.type !== "node") - continue; - if (pending.source.node !== node) - continue; - if (nsKey(pending.source.parent) !== nsKey(parent)) - continue; - pendingCompletions.splice(index2, 1); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/structured.js +var StructuredOutputParser, JsonMarkdownStructuredOutputParser, AsymmetricStructuredOutputParser; +var init_structured = __esm(() => { + init_zod2(); + init_json_schema3(); + init_base6(); + init_v3(); + StructuredOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StructuredOutputParser"; } - }; - const ensureStarted = (ns3) => { - for (let length = 1;length <= ns3.length; length += 1) { - const prefix = ns3.slice(0, length); - const key = nsKey(prefix); - if (namespaces.has(key)) - continue; - trackNamespace(prefix); - const cause = namespaceCause.get(key); - emit(prefix, "started", cause != null ? { cause } : undefined); + lc_namespace = [ + "langchain", + "output_parsers", + "structured" + ]; + toJSON() { + return this.toJSONNotImplemented(); } - }; - const defaultTerminalStatus = () => pendingInterruptIds.size > 0 ? "interrupted" : "completed"; - const cascadeTerminalStatus = (status) => { - for (const rec of namespaces.values()) { - if (rec.namespace.length === 0) - continue; - if (rec.status !== "started") - continue; - emit(rec.namespace, status); + constructor(schema) { + super(schema); + this.schema = schema; } - emit([], status); - log.close(); - }; - const resolveTerminalStatusOverride = async () => { - if (getTerminalStatusOverride == null) - return defaultTerminalStatus(); - try { - return await getTerminalStatusOverride() ?? defaultTerminalStatus(); - } catch { - return defaultTerminalStatus(); + static fromZodSchema(schema) { + return new this(schema); } - }; - const findStartedChildForNode = (parentNamespace, node) => { - const prefix = `${node}:`; - for (const rec of namespaces.values()) { - if (rec.namespace.length !== parentNamespace.length + 1) - continue; - if (rec.status !== "started") - continue; - if (!hasPrefix(rec.namespace, parentNamespace)) - continue; - const last = rec.namespace[rec.namespace.length - 1]; - if (last === node || last.startsWith(prefix)) - return rec.namespace; + static fromNamesAndDescriptions(schemas4) { + const zodSchema = exports_external2.object(Object.fromEntries(Object.entries(schemas4).map(([name, description]) => [name, exports_external2.string().describe(description)]))); + return new this(zodSchema); } - }; - const findStartedChildForTask = (parentNamespace, task) => { - const namespace = [...parentNamespace, `${task.name}:${task.id}`]; - return namespaces.get(nsKey(namespace))?.status === "started" ? namespace : undefined; - }; - return { - __native: true, - init() { - return { - _lifecycleLog: log, - lifecycle: filterLifecycleEntries(log, [], 0) - }; - }, - onRegister(handle) { - emitter = handle; - trackNamespace([]); - if (emitRootOnRegister) - emit([], initialStatus); - }, - process(event) { - const ns3 = event.params.namespace; - if (inSelfEmit > 0) - return true; - const taskCompletion = event.method === "tasks" ? extractTaskResultCompletion(event.params.data) : undefined; - if (taskCompletion != null) - removePendingNodeCompletions(ns3, taskCompletion.name); - flushPendingCompletions(); - if (event.method === "lifecycle") { - const cause = extractCause(event.params.data); - if (cause != null) - namespaceCause.set(nsKey(ns3), cause); - ensureStarted(ns3); - return false; - } - ensureStarted(ns3); - if (event.method === "input" && isRecord(event.params.data) && event.params.data.event === "requested") { - const id = event.params.data.id; - if (typeof id === "string") - pendingInterruptIds.add(id); - } - if (taskCompletion != null) { - const childNamespace = findStartedChildForTask(ns3, taskCompletion); - if (childNamespace != null) - enqueueCompletion({ - namespace: childNamespace, - source: { type: "task" } - }); - } - if (event.method === "updates") { - const node = event.params.node; - if (typeof node === "string" && !node.startsWith("__")) { - const childNamespace = findStartedChildForNode(ns3, node); - if (childNamespace != null) - enqueueCompletion({ - namespace: childNamespace, - source: { - type: "node", - parent: ns3, - node - } - }); - } - } - return true; - }, - finalize() { - if (finalized) - return; - finalized = true; - flushPendingCompletions(); - if (getTerminalStatusOverride == null) { - cascadeTerminalStatus(defaultTerminalStatus()); - return; - } - return resolveTerminalStatusOverride().then(cascadeTerminalStatus).catch((err) => { - log.fail(err); - }); - }, - fail(err) { - if (finalized) - return; - finalized = true; - const errorMessage = serializeError(err); - for (const rec of namespaces.values()) { - if (rec.namespace.length === 0) - continue; - if (rec.status !== "started") - continue; - emit(rec.namespace, "failed"); + getFormatInstructions() { + return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. + +"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. + +For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} +would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. +Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. + +Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! + +Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: +\`\`\`json +${JSON.stringify(toJsonSchema(this.schema))} +\`\`\` +`; + } + async parse(text) { + try { + const trimmedText = text.trim(); + const escapedJson = (trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { + return `"${capturedGroup.replace(/\n/g, "\\n")}"`; + }).replace(/\n/g, ""); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); } - emit([], "failed", { error: errorMessage }); - log.fail(err); + } + _baseMessageToString(message) { + return message.text; } }; -} -var DEFAULT_ROOT_GRAPH_NAME = "root"; -var init_lifecycle = __esm(() => { - init_stream_channel(); - init_mux(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/transformers/messages.js -function getMessageStreamKey(data) { - const record2 = data; - if (typeof record2.run_id === "string") - return `run:${record2.run_id}`; - if (data.event === "message-start" && typeof record2.id === "string") - return `message:${record2.id}`; - return "__default__"; -} -function createMessagesTransformer(path2, nodeFilter) { - const log = StreamChannel.local(); - const active = /* @__PURE__ */ new Map; - return { - init: () => ({ messages: log.toAsyncIterable() }), - process(event) { - if (event.method !== "messages") - return true; - if (!hasPrefix(event.params.namespace, path2)) - return true; - if (event.params.namespace.length !== path2.length + 1) - return true; - if (nodeFilter !== undefined && event.params.node !== nodeFilter) - return true; - const data = event.params.data; - switch (data.event) { - case "message-start": { - const key = getMessageStreamKey(data); - const source = StreamChannel.local(); - const stream2 = Object.assign(new ChatModelStream(source.toAsyncIterable()), { - namespace: event.params.namespace, - node: event.params.node - }); - active.set(key, { - source, - stream: stream2 - }); - source.push(data); - log.push(stream2); - break; - } - case "content-block-start": - case "content-block-delta": - case "content-block-finish": - active.get(getMessageStreamKey(data))?.source.push(data); - break; - case "message-finish": { - const key = getMessageStreamKey(data); - const stream2 = active.get(key); - if (stream2) { - stream2.source.push(data); - stream2.source.close(); - active.delete(key); + JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { + static lc_name() { + return "JsonMarkdownStructuredOutputParser"; + } + getFormatInstructions(options) { + const interpolationDepth = options?.interpolationDepth ?? 1; + if (interpolationDepth < 1) + throw new Error("f string interpolation depth must be at least 1"); + return `Return a markdown code snippet with a JSON object formatted to look like: +\`\`\`json +${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))} +\`\`\``; + } + _schemaToInstruction(schemaInput, indent = 2) { + const schema = schemaInput; + if ("type" in schema) { + let nullable2 = false; + let type; + if (Array.isArray(schema.type)) { + const nullIdx = schema.type.findIndex((type2) => type2 === "null"); + if (nullIdx !== -1) { + nullable2 = true; + schema.type.splice(nullIdx, 1); } - break; + type = schema.type.join(" | "); + } else + type = schema.type; + if (schema.type === "object" && schema.properties) { + const description2 = schema.description ? ` // ${schema.description}` : ""; + return `{ +${Object.entries(schema.properties).map(([key, value]) => { + const isOptional = schema.required?.includes(key) ? "" : " (optional)"; + return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; + }).join(` +`)} +${" ".repeat(indent - 2)}}${description2}`; } - case "error": - active.get(getMessageStreamKey(data))?.source.push(data); - break; - } - return true; - }, - finalize() { - for (const [key, stream2] of active) { - stream2.source.push({ event: "message-finish" }); - stream2.source.close(); - active.delete(key); - } - log.close(); - }, - fail(err) { - for (const [key, stream2] of active) { - stream2.source.fail(err); - active.delete(key); + if (schema.type === "array" && schema.items) { + const description2 = schema.description ? ` // ${schema.description}` : ""; + return `array[ +${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)} +${" ".repeat(indent - 2)}] ${description2}`; + } + const isNullable = nullable2 ? " (nullable)" : ""; + const description = schema.description ? ` // ${schema.description}` : ""; + return `${type}${description}${isNullable}`; } - log.fail(err); + if ("anyOf" in schema) + return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(` +${" ".repeat(indent - 2)}`); + throw new Error("unsupported schema type"); + } + static fromZodSchema(schema) { + return new this(schema); + } + static fromNamesAndDescriptions(schemas4) { + const zodSchema = exports_external2.object(Object.fromEntries(Object.entries(schemas4).map(([name, description]) => [name, exports_external2.string().describe(description)]))); + return new this(zodSchema); } }; -} -var init_messages2 = __esm(() => { - init_stream_channel(); - init_mux(); - init_stream2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/transformers/subgraphs.js -function filterSubgraphHandles(log, path2, startAt = 0) { - const targetDepth = path2.length + 1; - return { [Symbol.asyncIterator]() { - const base = log.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - const { ns: ns3, stream: stream2 } = result.value; - if (ns3.length === targetDepth && hasPrefix(ns3, path2)) - return { - value: stream2, - done: false - }; + AsymmetricStructuredOutputParser = class extends BaseOutputParser { + structuredInputParser; + constructor({ inputSchema }) { + super(...arguments); + this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); + } + async parse(text) { + let parsedInput; + try { + parsedInput = await this.structuredInputParser.parse(text); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); } - } }; - } }; -} -function createSubgraphDiscoveryTransformer(mux, options) { - const { createStream } = options; - const seen = /* @__PURE__ */ new Set; - return { - __native: true, - init() { - return { - _discoveries: mux._discoveries, - subgraphs: filterSubgraphHandles(mux._discoveries, [], 0) - }; - }, - process(event) { - const ns3 = event.params.namespace; - if (ns3.length === 0) - return true; - const topNs = ns3.slice(0, 1); - const topKey = nsKey(topNs); - if (seen.has(topKey)) - return true; - seen.add(topKey); - const stream2 = createStream(topNs, mux._discoveries.size, mux._events.size); - mux.register(topNs, stream2); - mux._discoveries.push({ - ns: topNs, - stream: stream2 - }); - return true; + return this.outputProcessor(parsedInput); + } + getFormatInstructions() { + return this.structuredInputParser.getFormatInstructions(); } }; -} -var init_subgraphs = __esm(() => { - init_mux(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/transformers/values.js -function createValuesTransformer(path2) { - const valuesLog = StreamChannel.local(); - return { - init: () => ({ _valuesLog: valuesLog }), - process(event) { - if (event.method !== "values") - return true; - if (event.params.namespace.length !== path2.length) - return true; - if (!hasPrefix(event.params.namespace, path2)) - return true; - valuesLog.push(event.params.data); - return true; - }, - finalize() { - valuesLog.close(); - }, - fail(err) { - valuesLog.fail(err); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/bytes.js +var BytesOutputParser; +var init_bytes = __esm(() => { + init_transform(); + BytesOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "BytesOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "bytes" + ]; + lc_serializable = true; + textEncoder = new TextEncoder; + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; } }; -} -var init_values = __esm(() => { - init_stream_channel(); - init_mux(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/types.js -function isNativeTransformer(t) { - return "__native" in t && t.__native === true; -} -var init_types6 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/transformers/index.js -var init_transformers3 = __esm(() => { - init_lifecycle(); - init_messages2(); - init_subgraphs(); - init_values(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/run-stream.js -function createGraphRunStream(source, transformers = [], optionsOrAbortController) { - const { abortController } = optionsOrAbortController instanceof AbortController ? { abortController: optionsOrAbortController } : optionsOrAbortController ?? {}; - const mux = new StreamMux; - const lifecycleTransformer = createLifecycleTransformer(); - const lifecycleProjection = lifecycleTransformer.init(); - const lifecycleLog = lifecycleProjection._lifecycleLog; - const subgraphDiscoveryTransformer = createSubgraphDiscoveryTransformer(mux, { createStream: (path2, discoveryStart, eventStart) => { - const sub = new SubgraphRunStream(path2, mux, discoveryStart, eventStart); - sub[SET_SUBGRAPHS_ITERABLE](filterSubgraphHandles(mux._discoveries, path2, discoveryStart)); - sub[SET_LIFECYCLE_ITERABLE](filterLifecycleEntries(lifecycleLog, path2, lifecycleLog.size)); - return sub; - } }); - const subgraphsProjection = subgraphDiscoveryTransformer.init(); - mux.addTransformer(subgraphDiscoveryTransformer); - mux.addTransformer(lifecycleTransformer); - const valuesTransformer = createValuesTransformer([]); - const messagesTransformer = createMessagesTransformer([]); - mux.addTransformer(valuesTransformer); - mux.addTransformer(messagesTransformer); - const extensions = {}; - const nativeProjections = []; - for (const factory of transformers) { - const transformer = factory(); - mux.addTransformer(transformer); - const projection = transformer.init(); - if (isNativeTransformer(transformer)) - nativeProjections.push(projection); - else - Object.assign(extensions, projection); - if (typeof projection === "object" && projection !== null && !isNativeTransformer(transformer)) - mux.wireChannels(projection); - } - const root = new GraphRunStream([], mux, 0, 0, extensions, abortController); - for (const proj of nativeProjections) - Object.assign(root, proj); - const valuesProjection = valuesTransformer.init(); - root[SET_VALUES_LOG](valuesProjection._valuesLog); - const messagesProjection = messagesTransformer.init(); - root[SET_MESSAGES_ITERABLE](messagesProjection.messages); - root[SET_LIFECYCLE_ITERABLE](lifecycleProjection.lifecycle); - root[SET_SUBGRAPHS_ITERABLE](subgraphsProjection.subgraphs); - mux.register([], root); - pump(source, mux).catch((err) => {}); - return root; -} -var SET_VALUES_LOG, SET_MESSAGES_ITERABLE, SET_LIFECYCLE_ITERABLE, SET_SUBGRAPHS_ITERABLE, EMPTY_ASYNC_ITERABLE, GraphRunStream, SubgraphRunStream; -var init_run_stream = __esm(() => { - init_mux(); - init_lifecycle(); - init_messages2(); - init_subgraphs(); - init_values(); - init_transformers3(); - init_types6(); - SET_VALUES_LOG = Symbol("setValuesLog"); - SET_MESSAGES_ITERABLE = Symbol("setMessagesIterable"); - SET_LIFECYCLE_ITERABLE = Symbol("setLifecycleIterable"); - SET_SUBGRAPHS_ITERABLE = Symbol("setSubgraphsIterable"); - EMPTY_ASYNC_ITERABLE = { [Symbol.asyncIterator]() { - return { next: () => Promise.resolve({ - value: undefined, - done: true - }) }; - } }; - GraphRunStream = class { - path; - extensions; - _mux; - #eventStart; - #discoveryStart; - #abortController; - #resolveValuesFn; - #rejectValuesFn; - #valuesDone; - #valuesLog; - #messagesIterable; - #lifecycleIterable; - #subgraphsIterable; - constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { - this.path = path2; - this._mux = mux; - this.#discoveryStart = discoveryStart; - this.#eventStart = eventStart; - this.extensions = extensions ?? {}; - this.#abortController = abortController ?? new AbortController; - this.#valuesDone = new Promise((resolve2, reject) => { - this.#resolveValuesFn = resolve2; - this.#rejectValuesFn = reject; - }); - this.#valuesDone.catch(() => {}); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/list.js +var ListOutputParser, CommaSeparatedListOutputParser, CustomListOutputParser, NumberedListOutputParser, MarkdownListOutputParser; +var init_list = __esm(() => { + init_base6(); + init_transform(); + ListOutputParser = class extends BaseTransformOutputParser { + re; + async* _transform(inputGenerator) { + let buffer = ""; + for await (const input of inputGenerator) { + if (typeof input === "string") + buffer += input; + else + buffer += input.content; + if (!this.re) { + const parts = await this.parse(buffer); + if (parts.length > 1) { + for (const part of parts.slice(0, -1)) + yield [part]; + buffer = parts[parts.length - 1]; + } + } else { + const matches = [...buffer.matchAll(this.re)]; + if (matches.length > 1) { + let doneIdx = 0; + for (const match2 of matches.slice(0, -1)) { + yield [match2[1]]; + doneIdx += (match2.index ?? 0) + match2[0].length; + } + buffer = buffer.slice(doneIdx); + } + } + } + for (const part of await this.parse(buffer)) + yield [part]; } - [Symbol.asyncIterator]() { - return this._mux.subscribeEvents(this.path, this.#eventStart); + }; + CommaSeparatedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "CommaSeparatedListOutputParser"; } - get subgraphs() { - if (this.#subgraphsIterable) - return this.#subgraphsIterable; - return filterSubgraphHandles(this._mux._discoveries, this.path, this.#discoveryStart); + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + async parse(text) { + try { + return text.trim().split(",").map((s) => s.trim()); + } catch { + throw new OutputParserException(`Could not parse output: ${text}`, text); + } } - get values() { - const log = this.#valuesLog; - const done = this.#valuesDone; - const mux = this._mux; - const eventStart = this.#eventStart; - const path2 = this.path; - const iterable = log ? log.toAsyncIterable() : { [Symbol.asyncIterator]: () => { - const base = mux.subscribeEvents(path2, eventStart); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - if (result.value.method === "values" && result.value.params.namespace.length === path2.length) - return { - value: result.value.params.data, - done: false - }; - } - } }; - } }; - return { - [Symbol.asyncIterator]: () => iterable[Symbol.asyncIterator](), - then: done.then.bind(done) - }; + getFormatInstructions() { + return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; } - get messages() { - if (this.#messagesIterable) - return this.#messagesIterable; - const transformer = createMessagesTransformer(this.path); - const projection = transformer.init(); - this._mux.addTransformer(transformer); - this.#messagesIterable = projection.messages; - return this.#messagesIterable; + }; + CustomListOutputParser = class extends ListOutputParser { + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + length; + separator; + constructor({ length, separator }) { + super(...arguments); + this.length = length; + this.separator = separator || ","; } - get lifecycle() { - return this.#lifecycleIterable ?? EMPTY_ASYNC_ITERABLE; + async parse(text) { + try { + const items = text.trim().split(this.separator).map((s) => s.trim()); + if (this.length !== undefined && items.length !== this.length) + throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); + return items; + } catch (e) { + if (Object.getPrototypeOf(e) === OutputParserException.prototype) + throw e; + throw new OutputParserException(`Could not parse output: ${text}`); + } } - messagesFrom(node) { - const transformer = createMessagesTransformer(this.path, node); - const projection = transformer.init(); - this._mux.addTransformer(transformer); - return projection.messages; + getFormatInstructions() { + return `Your response should be a list of ${this.length === undefined ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; } - get output() { - return this.#valuesDone; + }; + NumberedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; } - get interrupted() { - return this._mux.interrupted; + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: + +1. foo + +2. bar + +3. baz`; } - get interrupts() { - return this._mux.interrupts; + re = /\d+\.\s([^\n]+)/g; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); } - abort(reason) { - this.#abortController.abort(reason); + }; + MarkdownListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; } - get signal() { - return this.#abortController.signal; + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: + +1. foo + +2. bar + +3. baz`; } - [RESOLVE_VALUES](values) { - this.#resolveValuesFn?.(values); - this.#resolveValuesFn = undefined; + re = /^\s*[-*]\s([^\n]+)$/gm; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); } - [REJECT_VALUES](err) { - this.#rejectValuesFn?.(err); - this.#rejectValuesFn = undefined; + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/string.js +var StringOutputParser; +var init_string2 = __esm(() => { + init_transform(); + StringOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "StrOutputParser"; } - [SET_VALUES_LOG](log) { - this.#valuesLog = log; + lc_namespace = [ + "langchain_core", + "output_parsers", + "string" + ]; + lc_serializable = true; + parse(text) { + return Promise.resolve(text); } - [SET_MESSAGES_ITERABLE](iterable) { - this.#messagesIterable = iterable; + getFormatInstructions() { + return ""; } - [SET_LIFECYCLE_ITERABLE](iterable) { - this.#lifecycleIterable = iterable; + _textContentToString(content) { + return content.text; } - [SET_SUBGRAPHS_ITERABLE](iterable) { - this.#subgraphsIterable = iterable; + _imageUrlContentToString(_content) { + throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); } - }; - SubgraphRunStream = class extends GraphRunStream { - name; - index; - constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { - super(path2, mux, discoveryStart, eventStart, extensions, abortController); - const lastSegment = path2[path2.length - 1] ?? ""; - const colonIdx = lastSegment.lastIndexOf(":"); - if (colonIdx >= 0) { - this.name = lastSegment.slice(0, colonIdx); - const suffix = lastSegment.slice(colonIdx + 1); - this.index = /^\d+$/.test(suffix) ? Number(suffix) : 0; - } else { - this.name = lastSegment; - this.index = 0; + _messageContentToString(content) { + switch (content.type) { + case "text": + case "text_delta": + if ("text" in content) + return this._textContentToString(content); + break; + case "image_url": + if ("image_url" in content) + return this._imageUrlContentToString(content); + break; + case "reasoning": + case "thinking": + case "redacted_thinking": + return ""; + default: + throw new Error(`Cannot coerce "${content.type}" message part into a string.`); } + throw new Error(`Invalid content type: ${content.type}`); + } + _baseMessageContentToString(content) { + return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/stream/index.js -var init_stream4 = __esm(() => { - init_stream_channel(); - init_convert(); - init_mux(); - init_lifecycle(); - init_messages2(); - init_subgraphs(); - init_values(); - init_transformers3(); - init_types6(); - init_run_stream(); - init_stream2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/hash.js -function assert3(a) { - if (!a) - throw new Error("Assert failed"); -} -function bswap642(a) { - const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); - scratchbuf.setBigUint64(0, a, true); - return scratchbuf.getBigUint64(0, false); -} -function bswap322(input) { - let a = input; - a = (a & n2(65535)) << n2(16) | (a & n2(4294901760)) >> n2(16); - a = (a & n2(16711935)) << n2(8) | (a & n2(4278255360)) >> n2(8); - return a; -} -function XXH_mult32to642(a, b) { - return (a & mask322) * (b & mask322) & mask642; -} -function rotl322(a, b) { - return (a << b | a >> n2(32) - b) & mask322; -} -function XXH3_accumulate_5122(acc, dataView, keyView) { - for (let i = 0;i < ACC_NB2; i += 1) { - const data_val = dataView.getBigUint64(i * 8, true); - const data_key = data_val ^ keyView.getBigUint64(i * 8, true); - acc[i ^ 1] += data_val; - acc[i] += XXH_mult32to642(data_key, data_key >> n2(32)); - } - return acc; -} -function XXH3_accumulate2(acc, dataView, keyView, nbStripes) { - for (let n3 = 0;n3 < nbStripes; n3 += 1) - XXH3_accumulate_5122(acc, view(dataView, n3 * STRIPE_LEN2), view(keyView, n3 * 8)); - return acc; -} -function XXH3_scrambleAcc2(acc, key) { - for (let i = 0;i < ACC_NB2; i += 1) { - const key64 = key.getBigUint64(i * 8, true); - let acc64 = acc[i]; - acc64 = xorshift642(acc64, n2(47)); - acc64 ^= key64; - acc64 *= PRIME32_12; - acc[i] = acc64 & mask642; - } - return acc; -} -function XXH3_mix2Accs2(acc, key) { - return XXH3_mul128_fold642(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U642, true)); -} -function XXH3_mergeAccs2(acc, key, start) { - let result64 = start; - result64 += XXH3_mix2Accs2(acc.slice(0), view(key, 0 * _U322)); - result64 += XXH3_mix2Accs2(acc.slice(2), view(key, 4 * _U322)); - result64 += XXH3_mix2Accs2(acc.slice(4), view(key, 8 * _U322)); - result64 += XXH3_mix2Accs2(acc.slice(6), view(key, 12 * _U322)); - return XXH3_avalanche2(result64 & mask642); -} -function XXH3_hashLong2(input, data, secret, f_acc, f_scramble) { - let acc = input; - const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN2) / 8); - const block_len = STRIPE_LEN2 * nbStripesPerBlock; - const nb_blocks = Math.floor((data.byteLength - 1) / block_len); - for (let n3 = 0;n3 < nb_blocks; n3 += 1) { - acc = XXH3_accumulate2(acc, view(data, n3 * block_len), secret, nbStripesPerBlock); - acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN2)); - } - { - const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN2); - acc = XXH3_accumulate2(acc, view(data, nb_blocks * block_len), secret, nbStripes); - acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN2), view(secret, secret.byteLength - STRIPE_LEN2 - 7)); - } - return acc; -} -function XXH3_hashLong_128b2(data, secret) { - let acc = new BigUint64Array([ - PRIME32_32, - PRIME64_12, - PRIME64_22, - PRIME64_32, - PRIME64_42, - PRIME32_22, - PRIME64_52, - PRIME32_12 - ]); - assert3(data.byteLength > 128); - acc = XXH3_hashLong2(acc, data, secret, XXH3_accumulate_5122, XXH3_scrambleAcc2); - assert3(acc.length * 8 === 64); - { - const low64 = XXH3_mergeAccs2(acc, view(secret, 11), n2(data.byteLength) * PRIME64_12 & mask642); - return XXH3_mergeAccs2(acc, view(secret, secret.byteLength - STRIPE_LEN2 - 11), ~(n2(data.byteLength) * PRIME64_22) & mask642) << n2(64) | low64; - } -} -function XXH3_mul128_fold642(a, b) { - const lll = a * b & mask1282; - return lll & mask642 ^ lll >> n2(64); -} -function XXH3_mix16B2(dataView, keyView, seed) { - return XXH3_mul128_fold642((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask642, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask642); -} -function XXH3_mix32B2(acc, data1, data2, key, seed) { - let accl = acc & mask642; - let acch = acc >> n2(64) & mask642; - accl += XXH3_mix16B2(data1, key, seed); - accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); - accl &= mask642; - acch += XXH3_mix16B2(data2, view(key, 16), seed); - acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); - acch &= mask642; - return acch << n2(64) | accl; -} -function XXH3_avalanche2(input) { - let h64 = input; - h64 ^= h64 >> n2(37); - h64 *= PRIME_MX12; - h64 &= mask642; - h64 ^= h64 >> n2(32); - return h64; -} -function XXH3_avalanche642(input) { - let h64 = input; - h64 ^= h64 >> n2(33); - h64 *= PRIME64_22; - h64 &= mask642; - h64 ^= h64 >> n2(29); - h64 *= PRIME64_32; - h64 &= mask642; - h64 ^= h64 >> n2(32); - return h64; -} -function XXH3_len_1to3_128b2(data, key32, seed) { - const len = data.byteLength; - assert3(len > 0 && len <= 3); - const combined = n2(data.getUint8(len - 1)) | n2(len << 8) | n2(data.getUint8(0) << 16) | n2(data.getUint8(len >> 1) << 24); - const low = (combined ^ (n2(key32.getUint32(0, true)) ^ n2(key32.getUint32(4, true))) + seed) & mask642; - const bhigh = (n2(key32.getUint32(8, true)) ^ n2(key32.getUint32(12, true))) - seed; - return (XXH3_avalanche642((rotl322(bswap322(combined), n2(13)) ^ bhigh) & mask642) & mask642) << n2(64) | XXH3_avalanche642(low); -} -function xorshift642(b, shift) { - return b ^ b >> shift; -} -function XXH3_len_4to8_128b2(data, key32, seed) { - const len = data.byteLength; - assert3(len >= 4 && len <= 8); - { - const l1 = data.getUint32(0, true); - const l2 = data.getUint32(len - 4, true); - let m128 = ((n2(l1) | n2(l2) << n2(32)) ^ (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask642) * (PRIME64_12 + (n2(len) << n2(2))) & mask1282; - m128 += (m128 & mask642) << n2(65); - m128 &= mask1282; - m128 ^= m128 >> n2(67); - return xorshift642(xorshift642(m128 & mask642, n2(35)) * PRIME_MX22 & mask642, n2(28)) | XXH3_avalanche2(m128 >> n2(64)) << n2(64); - } -} -function XXH3_len_9to16_128b2(data, key64, seed) { - const len = data.byteLength; - assert3(len >= 9 && len <= 16); - { - const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask642; - const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask642; - const ll1 = data.getBigUint64(0, true); - let ll2 = data.getBigUint64(len - 8, true); - let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_12; - const m128_l = (m128 & mask642) + (n2(len - 1) << n2(54)); - m128 = m128 & (mask1282 ^ mask642) | m128_l; - ll2 ^= bitfliph; - m128 += ll2 + (ll2 & mask322) * (PRIME32_22 - n2(1)) << n2(64); - m128 &= mask1282; - m128 ^= bswap642(m128 >> n2(64)); - let h128 = (m128 & mask642) * PRIME64_22; - h128 += (m128 >> n2(64)) * PRIME64_22 << n2(64); - h128 &= mask1282; - return XXH3_avalanche2(h128 & mask642) | XXH3_avalanche2(h128 >> n2(64)) << n2(64); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/sax-js/sax.js +var initializeSax = function() { + const sax = {}; + sax.parser = function(strict, opt) { + return new SAXParser(strict, opt); + }; + sax.SAXParser = SAXParser; + sax.SAXStream = SAXStream; + sax.createStream = createStream; + sax.MAX_BUFFER_LENGTH = 64 * 1024; + const buffers = [ + "comment", + "sgmlDecl", + "textNode", + "tagName", + "doctype", + "procInstName", + "procInstBody", + "entity", + "attribName", + "attribValue", + "cdata", + "script" + ]; + sax.EVENTS = [ + "text", + "processinginstruction", + "sgmldeclaration", + "doctype", + "comment", + "opentagstart", + "attribute", + "opentag", + "closetag", + "opencdata", + "cdata", + "closecdata", + "error", + "end", + "ready", + "script", + "opennamespace", + "closenamespace" + ]; + function SAXParser(strict, opt) { + if (!(this instanceof SAXParser)) + return new SAXParser(strict, opt); + var parser = this; + clearBuffers(parser); + parser.q = parser.c = ""; + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH; + parser.opt = opt || {}; + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; + parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; + parser.tags = []; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.strict = !!strict; + parser.noscript = !!(strict || parser.opt.noscript); + parser.state = S.BEGIN; + parser.strictEntities = parser.opt.strictEntities; + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES); + parser.attribList = []; + if (parser.opt.xmlns) + parser.ns = Object.create(rootNS); + parser.trackPosition = parser.opt.position !== false; + if (parser.trackPosition) + parser.position = parser.line = parser.column = 0; + emit(parser, "onready"); } -} -function XXH3_len_0to16_128b2(data, seed) { - const len = data.byteLength; - assert3(len <= 16); - if (len > 8) - return XXH3_len_9to16_128b2(data, kkey2, seed); - if (len >= 4) - return XXH3_len_4to8_128b2(data, kkey2, seed); - if (len > 0) - return XXH3_len_1to3_128b2(data, kkey2, seed); - return XXH3_avalanche642(seed ^ kkey2.getBigUint64(64, true) ^ kkey2.getBigUint64(72, true)) | XXH3_avalanche642(seed ^ kkey2.getBigUint64(80, true) ^ kkey2.getBigUint64(88, true)) << n2(64); -} -function inv642(x) { - return ~x + n2(1) & mask642; -} -function XXH3_len_17to128_128b2(data, secret, seed) { - let acc = n2(data.byteLength) * PRIME64_12 & mask642; - let i = n2(data.byteLength - 1) / n2(32); - while (i >= 0) { - const ni = Number(i); - acc = XXH3_mix32B2(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); - i -= n2(1); + if (!Object.create) + Object.create = function(o) { + function F() {} + F.prototype = o; + return new F; + }; + if (!Object.keys) + Object.keys = function(o) { + var a = []; + for (var i in o) + if (o.hasOwnProperty(i)) + a.push(i); + return a; + }; + function checkBufferLength(parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10); + var maxActual = 0; + for (var i = 0, l = buffers.length;i < l; i++) { + var len = parser[buffers[i]].length; + if (len > maxAllowed) + switch (buffers[i]) { + case "textNode": + closeText(parser); + break; + case "cdata": + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + break; + case "script": + emitNode(parser, "onscript", parser.script); + parser.script = ""; + break; + default: + error90(parser, "Max buffer length exceeded: " + buffers[i]); + } + maxActual = Math.max(maxActual, len); + } + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - maxActual + parser.position; } - let h128l = acc + (acc >> n2(64)) & mask642; - h128l = XXH3_avalanche2(h128l); - let h128h = (acc & mask642) * PRIME64_12 + (acc >> n2(64)) * PRIME64_42 + (n2(data.byteLength) - seed & mask642) * PRIME64_22; - h128h &= mask642; - h128h = inv642(XXH3_avalanche2(h128h)); - return h128l | h128h << n2(64); -} -function XXH3_len_129to240_128b2(data, secret, seed) { - let acc = n2(data.byteLength) * PRIME64_12 & mask642; - for (let i = 32;i < 160; i += 32) - acc = XXH3_mix32B2(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); - acc = XXH3_avalanche2(acc & mask642) | XXH3_avalanche2(acc >> n2(64)) << n2(64); - for (let i = 160;i <= data.byteLength; i += 32) - acc = XXH3_mix32B2(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); - acc = XXH3_mix32B2(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv642(seed)); - let h128l = acc + (acc >> n2(64)) & mask642; - h128l = XXH3_avalanche2(h128l); - let h128h = (acc & mask642) * PRIME64_12 + (acc >> n2(64)) * PRIME64_42 + (n2(data.byteLength) - seed & mask642) * PRIME64_22; - h128h &= mask642; - h128h = inv642(XXH3_avalanche2(h128h)); - return h128l | h128h << n2(64); -} -function XXH3(input, seed = n2(0)) { - const encoder2 = new TextEncoder; - const data = view(typeof input === "string" ? encoder2.encode(input) : input); - const len = data.byteLength; - const hexDigest = (data2) => data2.toString(16).padStart(32, "0"); - if (len <= 16) - return hexDigest(XXH3_len_0to16_128b2(data, seed)); - if (len <= 128) - return hexDigest(XXH3_len_17to128_128b2(data, kkey2, seed)); - if (len <= 240) - return hexDigest(XXH3_len_129to240_128b2(data, kkey2, seed)); - return hexDigest(XXH3_hashLong_128b2(data, kkey2)); -} -function isXXH3(value) { - return /^[0-9a-f]{32}$/.test(value); -} -var n2 = (n3) => BigInt(n3), view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset), PRIME32_12, PRIME32_22, PRIME32_32, PRIME64_12, PRIME64_22, PRIME64_32, PRIME64_42, PRIME64_52, PRIME_MX12, PRIME_MX22, hexToUint8Array2 = (hex3) => { - const strLen = hex3.length; - if (strLen % 2 !== 0) - throw new Error("String should have an even number of characters"); - const maxLength = strLen / 2; - const bytes = new Uint8Array(maxLength); - let read = 0; - let write = 0; - while (write < maxLength) { - const slice = hex3.slice(read, read += 2); - bytes[write] = Number.parseInt(slice, 16); - write += 1; + function clearBuffers(parser) { + for (var i = 0, l = buffers.length;i < l; i++) + parser[buffers[i]] = ""; } - return view(bytes); -}, kkey2, mask1282, mask642, mask322, STRIPE_LEN2 = 64, ACC_NB2, _U642 = 8, _U322 = 4; -var init_hash3 = __esm(() => { - PRIME32_12 = n2("0x9E3779B1"); - PRIME32_22 = n2("0x85EBCA77"); - PRIME32_32 = n2("0xC2B2AE3D"); - PRIME64_12 = n2("0x9E3779B185EBCA87"); - PRIME64_22 = n2("0xC2B2AE3D27D4EB4F"); - PRIME64_32 = n2("0x165667B19E3779F9"); - PRIME64_42 = n2("0x85EBCA77C2B2AE63"); - PRIME64_52 = n2("0x27D4EB2F165667C5"); - PRIME_MX12 = n2("0x165667919E3779F9"); - PRIME_MX22 = n2("0x9FB21C651E98DF25"); - kkey2 = hexToUint8Array2("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); - mask1282 = (n2(1) << n2(128)) - n2(1); - mask642 = (n2(1) << n2(64)) - n2(1); - mask322 = (n2(1) << n2(32)) - n2(1); - ACC_NB2 = STRIPE_LEN2 / 8; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/interrupt.js -function interrupt(value) { - const config2 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (!config2) - throw new Error("Called interrupt() outside the context of a graph."); - const conf = config2.configurable; - if (!conf) - throw new Error("No configurable found in config"); - if (!conf["__pregel_checkpointer"]) - throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const scratchpad = conf[CONFIG_KEY_SCRATCHPAD]; - scratchpad.interruptCounter += 1; - const idx = scratchpad.interruptCounter; - if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { - conf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]); - return scratchpad.resume[idx]; + function flushBuffers(parser) { + closeText(parser); + if (parser.cdata !== "") { + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + } + if (parser.script !== "") { + emitNode(parser, "onscript", parser.script); + parser.script = ""; + } } - if (scratchpad.nullResume !== undefined) { - if (scratchpad.resume.length !== idx) - throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); - const v = scratchpad.consumeNullResume(); - scratchpad.resume.push(v); - conf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]); - return v; + SAXParser.prototype = { + end: function() { + end(this); + }, + write, + resume: function() { + this.error = null; + return this; + }, + close: function() { + return this.write(null); + }, + flush: function() { + flushBuffers(this); + } + }; + var Stream = ReadableStream; + if (!Stream) + Stream = function() {}; + var streamWraps = sax.EVENTS.filter(function(ev) { + return ev !== "error" && ev !== "end"; + }); + function createStream(strict, opt) { + return new SAXStream(strict, opt); } - const ns3 = conf[CONFIG_KEY_CHECKPOINT_NS]?.split("|"); - throw new GraphInterrupt([{ - id: ns3 ? XXH3(ns3.join("|")) : undefined, - value - }]); -} -var init_interrupt = __esm(() => { - init_constants3(); - init_errors5(); - init_hash3(); - init_singletons(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/utils.js -function* prefixGenerator(generator, prefix) { - if (prefix === undefined) - yield* generator; - else - for (const value of generator) - yield [prefix, value]; -} -async function gatherIterator(i) { - const out = []; - for await (const item of await i) - out.push(item); - return out; -} -function gatherIteratorSync(i) { - const out = []; - for (const item of i) - out.push(item); - return out; -} -function patchConfigurable(config2, patch) { - if (!config2) - return { configurable: patch }; - else if (!("configurable" in config2)) - return { - ...config2, - configurable: patch + function SAXStream(strict, opt) { + if (!(this instanceof SAXStream)) + return new SAXStream(strict, opt); + Stream.apply(this); + this._parser = new SAXParser(strict, opt); + this.writable = true; + this.readable = true; + var me = this; + this._parser.onend = function() { + me.emit("end"); }; - else - return { - ...config2, - configurable: { - ...config2.configurable, - ...patch - } + this._parser.onerror = function(er) { + me.emit("error", er); + me._parser.error = null; }; -} -function isAsyncGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; -} -function isGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; -} -var RunnableCallable; -var init_utils8 = __esm(() => { - init_config2(); - init_singletons(); - init_runnables(); - RunnableCallable = class extends Runnable { - lc_namespace = ["langgraph"]; - func; - tags; - config; - trace = true; - recurse = true; - constructor(fields) { - super(); - this.name = fields.name ?? fields.func.name; - this.func = fields.func; - this.config = fields.tags ? { tags: fields.tags } : undefined; - this.trace = fields.trace ?? this.trace; - this.recurse = fields.recurse ?? this.recurse; - } - async _tracedInvoke(input, config2, runManager) { - return new Promise((resolve2, reject) => { - const childConfig = patchConfig(config2, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { - try { - resolve2(await this.func(input, childConfig)); - } catch (e) { - reject(e); + this._decoder = null; + streamWraps.forEach(function(ev) { + Object.defineProperty(me, "on" + ev, { + get: function() { + return me._parser["on" + ev]; + }, + set: function(h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on" + ev] = h; + return h; } - }); + me.on(ev, h); + }, + enumerable: true, + configurable: false }); - } - async invoke(input, options) { - let returnValue; - const config2 = ensureLangGraphConfig(options); - const mergedConfig = mergeConfigs(this.config, config2); - if (this.trace) - returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); - else - returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); - if (Runnable.isRunnable(returnValue) && this.recurse) - return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); - return returnValue; - } + }); + } + SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }); + SAXStream.prototype.write = function(data) { + this._parser.write(data.toString()); + this.emit("data", data); + return true; }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/write.js -function _isSkipWrite(x) { - return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== undefined; -} -function _isPassthrough(x) { - return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== undefined; -} -function _isChannelWriteEntry(x) { - return x !== undefined && typeof x.channel === "string"; -} -function _isChannelWriteTupleEntry(x) { - return x !== undefined && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); -} -var PASSTHROUGH, IS_WRITER, ChannelWrite; -var init_write = __esm(() => { - init_constants3(); - init_errors5(); - init_utils8(); - init_runnables(); - PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; - IS_WRITER = Symbol("IS_WRITER"); - ChannelWrite = class ChannelWrite2 extends RunnableCallable { - writes; - constructor(writes, tags) { - const name = `ChannelWrite<${writes.map((packet) => { - if (_isSend(packet)) - return packet.node; - else if ("channel" in packet) - return packet.channel; - return "..."; - }).join(",")}>`; - super({ - writes, - name, - tags, - trace: false, - func: async (input, config2) => { - return this._write(input, config2 ?? {}); - } - }); - this.writes = writes; - } - async _write(input, config2) { - const writes = this.writes.map((write) => { - if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) - return { - mapper: write.mapper, - value: input - }; - else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) - return { - channel: write.channel, - value: input, - skipNone: write.skipNone, - mapper: write.mapper - }; - else - return write; - }); - await ChannelWrite2.doWrite(config2, writes); - return input; - } - static async doWrite(config2, writes) { - for (const w of writes) { - if (_isChannelWriteEntry(w)) { - if (w.channel === "__pregel_tasks") - throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); - if (_isPassthrough(w.value)) - throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - if (_isChannelWriteTupleEntry(w)) { - if (_isPassthrough(w.value)) - throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - } - const writeEntries = []; - for (const w of writes) - if (_isSend(w)) - writeEntries.push([TASKS, w]); - else if (_isChannelWriteTupleEntry(w)) { - const mappedResult = await w.mapper.invoke(w.value, config2); - if (mappedResult != null && mappedResult.length > 0) - writeEntries.push(...mappedResult); - } else if (_isChannelWriteEntry(w)) { - const mappedValue = w.mapper !== undefined ? await w.mapper.invoke(w.value, config2) : w.value; - if (_isSkipWrite(mappedValue)) - continue; - if (w.skipNone && mappedValue === undefined) - continue; - writeEntries.push([w.channel, mappedValue]); - } else - throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); - const write = config2.configurable?.[CONFIG_KEY_SEND]; - write(writeEntries); - } - static isWriter(runnable) { - return runnable instanceof ChannelWrite2 || IS_WRITER in runnable && !!runnable[IS_WRITER]; - } - static registerWriter(runnable) { - return Object.defineProperty(runnable, IS_WRITER, { value: true }); - } + SAXStream.prototype.end = function(chunk) { + if (chunk && chunk.length) + this.write(chunk); + this._parser.end(); + return true; }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/read.js -var ChannelRead, defaultRunnableBound, PregelNode; -var init_read = __esm(() => { - init_constants3(); - init_utils8(); - init_write(); - init_runnables(); - ChannelRead = class ChannelRead2 extends RunnableCallable { - lc_graph_name = "ChannelRead"; - channel; - fresh = false; - mapper; - constructor(channel, mapper, fresh = false) { - super({ - trace: false, - func: (_, config2) => ChannelRead2.doRead(config2, this.channel, this.fresh, this.mapper) - }); - this.fresh = fresh; - this.mapper = mapper; - this.channel = channel; - this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; - } - static doRead(config2, channel, fresh, mapper) { - const read = config2.configurable?.[CONFIG_KEY_READ]; - if (!read) - throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); - if (mapper) - return mapper(read(channel, fresh)); - else - return read(channel, fresh); - } + SAXStream.prototype.on = function(ev, handler) { + var me = this; + if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) + me._parser["on" + ev] = function() { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + return Stream.prototype.on.call(me, ev, handler); }; - defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough; - PregelNode = class PregelNode2 extends RunnableBinding { - lc_graph_name = "PregelNode"; - channels; - triggers = []; - mapper; - writers = []; - bound = defaultRunnableBound; - kwargs = {}; - metadata = {}; - tags = []; - retryPolicy; - cachePolicy; - subgraphs; - ends; - constructor(fields) { - const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; - const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; - super({ - ...fields, - bound: fields.bound ?? defaultRunnableBound, - config: { - ...fields.config ? fields.config : {}, - tags: mergedTags - } - }); - this.channels = channels; - this.triggers = triggers; - this.mapper = mapper; - this.writers = writers ?? this.writers; - this.bound = bound ?? this.bound; - this.kwargs = kwargs ?? this.kwargs; - this.metadata = metadata ?? this.metadata; - this.tags = mergedTags; - this.retryPolicy = retryPolicy; - this.cachePolicy = cachePolicy; - this.subgraphs = subgraphs; - this.ends = ends; - } - getWriters() { - const newWriters = [...this.writers]; - while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { - const endWriters = newWriters.slice(-2); - const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); - newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); - newWriters.pop(); - } - return newWriters; - } - getNode() { - const writers = this.getWriters(); - if (this.bound === defaultRunnableBound && writers.length === 0) - return; - else if (this.bound === defaultRunnableBound && writers.length === 1) - return writers[0]; - else if (this.bound === defaultRunnableBound) - return new RunnableSequence({ - first: writers[0], - middle: writers.slice(1, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else if (writers.length > 0) - return new RunnableSequence({ - first: this.bound, - middle: writers.slice(0, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else - return this.bound; - } - join(channels) { - if (!Array.isArray(channels)) - throw new Error("channels must be a list"); - if (typeof this.channels !== "object") - throw new Error("all channels must be named when using .join()"); - return new PregelNode2({ - channels: { - ...this.channels, - ...Object.fromEntries(channels.map((chan) => [chan, chan])) - }, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } - pipe(coerceable) { - if (ChannelWrite.isWriter(coerceable)) - return new PregelNode2({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: [...this.writers, coerceable], - bound: this.bound, - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else if (this.bound === defaultRunnableBound) - return new PregelNode2({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: _coerceToRunnable(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else - return new PregelNode2({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound.pipe(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } + var CDATA = "[CDATA["; + var DOCTYPE = "DOCTYPE"; + var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; + var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; + var rootNS = { + xml: XML_NAMESPACE, + xmlns: XMLNS_NAMESPACE }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js -function isRunnableSequence(x) { - return "steps" in x && Array.isArray(x.steps); -} -function isPregelLike(x) { - return "lg_is_pregel" in x && x.lg_is_pregel === true; -} -function findSubgraphPregel(candidate) { - const candidates = [candidate]; - for (const candidate2 of candidates) - if (isPregelLike(candidate2)) - return candidate2; - else if (isRunnableSequence(candidate2)) - candidates.push(...candidate2.steps); -} -var init_subgraph = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/io.js -function readChannel(channels, chan, catchErrors = true, returnException = false) { - try { - return channels[chan].get(); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) { - if (returnException) - return e; - else if (catchErrors) - return null; - } - throw e; + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + function isWhitespace(c) { + return c === " " || c === ` +` || c === "\r" || c === "\t"; } -} -function readChannels(channels, select, skipEmpty = true) { - if (Array.isArray(select)) { - const values = {}; - for (const k of select) - try { - values[k] = readChannel(channels, k, !skipEmpty); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) - continue; - } - return values; - } else - return readChannel(channels, select); -} -function* mapCommand(cmd, pendingWrites) { - if (cmd.graph === Command.PARENT) - throw new InvalidUpdateError("There is no parent graph."); - if (cmd.goto) { - let sends; - if (Array.isArray(cmd.goto)) - sends = cmd.goto; - else - sends = [cmd.goto]; - for (const send of sends) - if (_isSend(send)) - yield [ - NULL_TASK_ID, - TASKS, - send - ]; - else if (typeof send === "string") - yield [ - NULL_TASK_ID, - `branch:to:${send}`, - "__start__" - ]; - else - throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); + function isQuote(c) { + return c === '"' || c === "'"; } - if (cmd.resume) - if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) - for (const [tid, resume] of Object.entries(cmd.resume)) { - const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === "__resume__").map((w) => w[2]).slice(0, 1) ?? []; - existing.push(resume); - yield [ - tid, - RESUME, - existing - ]; - } - else - yield [ - NULL_TASK_ID, - RESUME, - cmd.resume - ]; - if (cmd.update) { - if (typeof cmd.update !== "object" || !cmd.update) - throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); - if (Array.isArray(cmd.update)) - for (const [k, v] of cmd.update) - yield [ - NULL_TASK_ID, - k, - v - ]; - else - for (const [k, v] of Object.entries(cmd.update)) - yield [ - NULL_TASK_ID, - k, - v - ]; + function isAttribEnd(c) { + return c === ">" || isWhitespace(c); } -} -function* mapInput(inputChannels, chunk) { - if (chunk !== undefined && chunk !== null) - if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { - for (const k in chunk) - if (inputChannels.includes(k)) - yield [k, chunk[k]]; - } else if (Array.isArray(inputChannels)) - throw new Error(`Input chunk must be an object when "inputChannels" is an array`); - else - yield [inputChannels, chunk]; -} -function* mapOutputValues(outputChannels, pendingWrites, channels) { - if (Array.isArray(outputChannels)) { - if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) - yield readChannels(channels, outputChannels); - } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) - yield readChannel(channels, outputChannels); -} -function* mapOutputUpdates(outputChannels, tasks, cached2) { - const outputTasks = tasks.filter(([task, ww]) => { - return (task.config === undefined || !task.config.tags?.includes("langsmith:hidden")) && ww[0][0] !== "__error__" && ww[0][0] !== "__interrupt__"; - }); - if (!outputTasks.length) - return; - let updated; - if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === "__return__"))) - updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); - else if (!Array.isArray(outputChannels)) - updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); - else - updated = outputTasks.flatMap(([task]) => { - const { writes } = task; - const counts = {}; - for (const [chan] of writes) - if (outputChannels.includes(chan)) - counts[chan] = (counts[chan] || 0) + 1; - if (Object.values(counts).some((count) => count > 1)) - return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); - else - return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; - }); - const grouped = {}; - for (const [node, value] of updated) { - if (!(node in grouped)) - grouped[node] = []; - grouped[node].push(value); + function isMatch(regex2, c) { + return regex2.test(c); } - const flattened = {}; - for (const node in grouped) - if (grouped[node].length === 1) { - const [write] = grouped[node]; - flattened[node] = write; - } else - flattened[node] = grouped[node]; - if (cached2) - flattened["__metadata__"] = { cached: cached2 }; - yield flattened; -} -var init_io = __esm(() => { - init_constants3(); - init_errors5(); - init_hash3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/utils/index.js -function getNullChannelVersion(currentVersions) { - const startVersion = typeof currentVersions[START]; - if (startVersion === "number") - return 0; - if (startVersion === "string") - return ""; - for (const key in currentVersions) { - if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) - continue; - const versionType = typeof currentVersions[key]; - if (versionType === "number") - return 0; - if (versionType === "string") - return ""; - break; + function notMatch(regex2, c) { + return !isMatch(regex2, c); } -} -function getNewChannelVersions(previousVersions, currentVersions) { - if (Object.keys(previousVersions).length > 0) { - const nullVersion = getNullChannelVersion(currentVersions); - return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); - } else - return currentVersions; -} -function _coerceToDict3(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function patchConfigurable2(config2, patch) { - if (config2 === null) - return { configurable: patch }; - else if (config2?.configurable === undefined) - return { - ...config2, - configurable: patch - }; - else - return { - ...config2, - configurable: { - ...config2.configurable, - ...patch - } - }; -} -function patchCheckpointMap(config2, metadata) { - const parents = metadata?.parents ?? {}; - if (Object.keys(parents).length > 0) - return patchConfigurable2(config2, { [CONFIG_KEY_CHECKPOINT_MAP]: { - ...parents, - [config2.configurable?.checkpoint_ns ?? ""]: config2.configurable?.checkpoint_id - } }); - else - return config2; -} -function combineAbortSignals(...x) { - const signals = [...new Set(x.filter(Boolean))]; - if (signals.length === 0) - return { - signal: undefined, - dispose: undefined - }; - if (signals.length === 1) - return { - signal: signals[0], - dispose: undefined - }; - const combinedController = new AbortController; - const listener = () => { - const reason = signals.find((s) => s.aborted)?.reason; - combinedController.abort(reason); - signals.forEach((s) => s.removeEventListener("abort", listener)); - }; - signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); - const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); - if (hasAlreadyAbortedSignal) - combinedController.abort(hasAlreadyAbortedSignal.reason); - return { - signal: combinedController.signal, - dispose: () => { - signals.forEach((s) => s.removeEventListener("abort", listener)); - } + var S = 0; + sax.STATE = { + BEGIN: S++, + BEGIN_WHITESPACE: S++, + TEXT: S++, + TEXT_ENTITY: S++, + OPEN_WAKA: S++, + SGML_DECL: S++, + SGML_DECL_QUOTED: S++, + DOCTYPE: S++, + DOCTYPE_QUOTED: S++, + DOCTYPE_DTD: S++, + DOCTYPE_DTD_QUOTED: S++, + COMMENT_STARTING: S++, + COMMENT: S++, + COMMENT_ENDING: S++, + COMMENT_ENDED: S++, + CDATA: S++, + CDATA_ENDING: S++, + CDATA_ENDING_2: S++, + PROC_INST: S++, + PROC_INST_BODY: S++, + PROC_INST_ENDING: S++, + OPEN_TAG: S++, + OPEN_TAG_SLASH: S++, + ATTRIB: S++, + ATTRIB_NAME: S++, + ATTRIB_NAME_SAW_WHITE: S++, + ATTRIB_VALUE: S++, + ATTRIB_VALUE_QUOTED: S++, + ATTRIB_VALUE_CLOSED: S++, + ATTRIB_VALUE_UNQUOTED: S++, + ATTRIB_VALUE_ENTITY_Q: S++, + ATTRIB_VALUE_ENTITY_U: S++, + CLOSE_TAG: S++, + CLOSE_TAG_SAW_WHITE: S++, + SCRIPT: S++, + SCRIPT_ENDING: S++ }; -} -var combineCallbacks = (callback1, callback2) => { - if (!callback1 && !callback2) - return; - if (!callback1) - return callback2; - if (!callback2) - return callback1; - if (Array.isArray(callback1) && Array.isArray(callback2)) - return [...callback1, ...callback2]; - if (Array.isArray(callback1)) - return [...callback1, callback2]; - if (Array.isArray(callback2)) - return [callback1, ...callback2]; - return [callback1, callback2]; -}; -var init_utils9 = __esm(() => { - init_constants3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/types.js -function isCall(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; -} -var Call = class { - func; - name; - input; - retry; - cache; - callbacks; - __lg_type = "call"; - constructor({ func, name, input, retry, cache: cache2, callbacks }) { - this.func = func; - this.name = name; - this.input = input; - this.retry = retry; - this.cache = cache2; - this.callbacks = callbacks; - } -}; -var init_types7 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/call.js -function getRunnableForFunc(name, func) { - return new RunnableSequence({ - name, - first: new RunnableCallable({ - func: (input) => func(...input), - name, - trace: false, - recurse: false - }), - last: new ChannelWrite([{ - channel: RETURN, - value: PASSTHROUGH - }], [TAG_HIDDEN]) - }); -} -function getRunnableForEntrypoint(name, func) { - return new RunnableCallable({ - func: (input, config2) => { - return func(input, config2); - }, - name, - trace: false, - recurse: false + sax.XML_ENTITIES = { + amp: "&", + gt: ">", + lt: "<", + quot: '"', + apos: "'" + }; + sax.ENTITIES = { + amp: "&", + gt: ">", + lt: "<", + quot: '"', + apos: "'", + AElig: 198, + Aacute: 193, + Acirc: 194, + Agrave: 192, + Aring: 197, + Atilde: 195, + Auml: 196, + Ccedil: 199, + ETH: 208, + Eacute: 201, + Ecirc: 202, + Egrave: 200, + Euml: 203, + Iacute: 205, + Icirc: 206, + Igrave: 204, + Iuml: 207, + Ntilde: 209, + Oacute: 211, + Ocirc: 212, + Ograve: 210, + Oslash: 216, + Otilde: 213, + Ouml: 214, + THORN: 222, + Uacute: 218, + Ucirc: 219, + Ugrave: 217, + Uuml: 220, + Yacute: 221, + aacute: 225, + acirc: 226, + aelig: 230, + agrave: 224, + aring: 229, + atilde: 227, + auml: 228, + ccedil: 231, + eacute: 233, + ecirc: 234, + egrave: 232, + eth: 240, + euml: 235, + iacute: 237, + icirc: 238, + igrave: 236, + iuml: 239, + ntilde: 241, + oacute: 243, + ocirc: 244, + ograve: 242, + oslash: 248, + otilde: 245, + ouml: 246, + szlig: 223, + thorn: 254, + uacute: 250, + ucirc: 251, + ugrave: 249, + uuml: 252, + yacute: 253, + yuml: 255, + copy: 169, + reg: 174, + nbsp: 160, + iexcl: 161, + cent: 162, + pound: 163, + curren: 164, + yen: 165, + brvbar: 166, + sect: 167, + uml: 168, + ordf: 170, + laquo: 171, + not: 172, + shy: 173, + macr: 175, + deg: 176, + plusmn: 177, + sup1: 185, + sup2: 178, + sup3: 179, + acute: 180, + micro: 181, + para: 182, + middot: 183, + cedil: 184, + ordm: 186, + raquo: 187, + frac14: 188, + frac12: 189, + frac34: 190, + iquest: 191, + times: 215, + divide: 247, + OElig: 338, + oelig: 339, + Scaron: 352, + scaron: 353, + Yuml: 376, + fnof: 402, + circ: 710, + tilde: 732, + Alpha: 913, + Beta: 914, + Gamma: 915, + Delta: 916, + Epsilon: 917, + Zeta: 918, + Eta: 919, + Theta: 920, + Iota: 921, + Kappa: 922, + Lambda: 923, + Mu: 924, + Nu: 925, + Xi: 926, + Omicron: 927, + Pi: 928, + Rho: 929, + Sigma: 931, + Tau: 932, + Upsilon: 933, + Phi: 934, + Chi: 935, + Psi: 936, + Omega: 937, + alpha: 945, + beta: 946, + gamma: 947, + delta: 948, + epsilon: 949, + zeta: 950, + eta: 951, + theta: 952, + iota: 953, + kappa: 954, + lambda: 955, + mu: 956, + nu: 957, + xi: 958, + omicron: 959, + pi: 960, + rho: 961, + sigmaf: 962, + sigma: 963, + tau: 964, + upsilon: 965, + phi: 966, + chi: 967, + psi: 968, + omega: 969, + thetasym: 977, + upsih: 978, + piv: 982, + ensp: 8194, + emsp: 8195, + thinsp: 8201, + zwnj: 8204, + zwj: 8205, + lrm: 8206, + rlm: 8207, + ndash: 8211, + mdash: 8212, + lsquo: 8216, + rsquo: 8217, + sbquo: 8218, + ldquo: 8220, + rdquo: 8221, + bdquo: 8222, + dagger: 8224, + Dagger: 8225, + bull: 8226, + hellip: 8230, + permil: 8240, + prime: 8242, + Prime: 8243, + lsaquo: 8249, + rsaquo: 8250, + oline: 8254, + frasl: 8260, + euro: 8364, + image: 8465, + weierp: 8472, + real: 8476, + trade: 8482, + alefsym: 8501, + larr: 8592, + uarr: 8593, + rarr: 8594, + darr: 8595, + harr: 8596, + crarr: 8629, + lArr: 8656, + uArr: 8657, + rArr: 8658, + dArr: 8659, + hArr: 8660, + forall: 8704, + part: 8706, + exist: 8707, + empty: 8709, + nabla: 8711, + isin: 8712, + notin: 8713, + ni: 8715, + prod: 8719, + sum: 8721, + minus: 8722, + lowast: 8727, + radic: 8730, + prop: 8733, + infin: 8734, + ang: 8736, + and: 8743, + or: 8744, + cap: 8745, + cup: 8746, + int: 8747, + there4: 8756, + sim: 8764, + cong: 8773, + asymp: 8776, + ne: 8800, + equiv: 8801, + le: 8804, + ge: 8805, + sub: 8834, + sup: 8835, + nsub: 8836, + sube: 8838, + supe: 8839, + oplus: 8853, + otimes: 8855, + perp: 8869, + sdot: 8901, + lceil: 8968, + rceil: 8969, + lfloor: 8970, + rfloor: 8971, + lang: 9001, + rang: 9002, + loz: 9674, + spades: 9824, + clubs: 9827, + hearts: 9829, + diams: 9830 + }; + Object.keys(sax.ENTITIES).forEach(function(key) { + var e = sax.ENTITIES[key]; + var s2 = typeof e === "number" ? String.fromCharCode(e) : e; + sax.ENTITIES[key] = s2; }); -} -function call({ func, name, cache: cache2, retry }, ...args) { - const config2 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (typeof config2.configurable?.["__pregel_call"] === "function") - return config2.configurable[CONFIG_KEY_CALL](func, name, args, { - retry, - cache: cache2, - callbacks: config2.callbacks - }); - throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); -} -var init_call = __esm(() => { - init_constants3(); - init_utils8(); - init_write(); - init_singletons(); - init_runnables(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/algo.js -function triggersNextStep(updatedChannels, triggerToNodes) { - if (triggerToNodes == null) - return false; - for (const chan of updatedChannels) - if (triggerToNodes[chan]) - return true; - return false; -} -function maxChannelMapVersion(channelVersions) { - let maxVersion; - for (const chan in channelVersions) { - if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) - continue; - if (maxVersion == null) - maxVersion = channelVersions[chan]; - else - maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); + for (var s in sax.STATE) + sax.STATE[sax.STATE[s]] = s; + S = sax.STATE; + function emit(parser, event, data) { + parser[event] && parser[event](data); } - return maxVersion; -} -function shouldInterrupt(checkpoint, interruptNodes, tasks) { - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - const seen = checkpoint.versions_seen["__interrupt__"] ?? {}; - let anyChannelUpdated = false; - if ((checkpoint.channel_versions["__start__"] ?? nullVersion) > (seen["__start__"] ?? nullVersion)) - anyChannelUpdated = true; - else - for (const chan in checkpoint.channel_versions) { - if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) - continue; - if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { - anyChannelUpdated = true; - break; - } + function emitNode(parser, nodeType, data) { + if (parser.textNode) + closeText(parser); + emit(parser, nodeType, data); + } + function closeText(parser) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode) + emit(parser, "ontext", parser.textNode); + parser.textNode = ""; + } + function textopts(opt, text) { + if (opt.trim) + text = text.trim(); + if (opt.normalize) + text = text.replace(/\s+/g, " "); + return text; + } + function error90(parser, er) { + closeText(parser); + if (parser.trackPosition) + er += ` +Line: ` + parser.line + ` +Column: ` + parser.column + ` +Char: ` + parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + function end(parser) { + if (parser.sawRoot && !parser.closedRoot) + strictFail(parser, "Unclosed root tag"); + if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) + error90(parser, "Unexpected end"); + closeText(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + SAXParser.call(parser, parser.strict, parser.opt); + return parser; + } + function strictFail(parser, message) { + if (typeof parser !== "object" || !(parser instanceof SAXParser)) + throw new Error("bad call to strictFail"); + if (parser.strict) + error90(parser, message); + } + function newTag(parser) { + if (!parser.strict) + parser.tagName = parser.tagName[parser.looseCase](); + var parent = parser.tags[parser.tags.length - 1] || parser; + var tag = parser.tag = { + name: parser.tagName, + attributes: {} + }; + if (parser.opt.xmlns) + tag.ns = parent.ns; + parser.attribList.length = 0; + emitNode(parser, "onopentagstart", tag); + } + function qname(name, attribute) { + var qualName = name.indexOf(":") < 0 ? ["", name] : name.split(":"); + var prefix = qualName[0]; + var local = qualName[1]; + if (attribute && name === "xmlns") { + prefix = "xmlns"; + local = ""; } - const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); - return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; -} -function _localRead(checkpoint, channels, task, select, fresh = false) { - let updated = /* @__PURE__ */ new Set; - if (!Array.isArray(select)) { - for (const [c] of task.writes) - if (c === select) { - updated = new Set([c]); - break; - } - updated = updated || /* @__PURE__ */ new Set; - } else - updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); - let values; - if (fresh && updated.size > 0) { - const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); - const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1); - const newChannels = emptyChannels(localChannels, newCheckpoint); - _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], undefined, undefined); - values = readChannels({ - ...channels, - ...newChannels - }, select); - } else - values = readChannels(channels, select); - return values; -} -function _localWrite(commit, processes, writes) { - for (const [chan, value] of writes) - if (["__pregel_push", "__pregel_tasks"].includes(chan) && value != null) { - if (!_isSend(value)) - throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); - if (!(value.node in processes)) - throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); + return { + prefix, + local + }; + } + function attrib(parser) { + if (!parser.strict) + parser.attribName = parser.attribName[parser.looseCase](); + if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { + parser.attribName = parser.attribValue = ""; + return; } - commit(writes); -} -function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { - tasks.sort((a, b) => { - const aPath = a.path?.slice(0, 3) || []; - const bPath = b.path?.slice(0, 3) || []; - for (let i = 0;i < Math.min(aPath.length, bPath.length); i += 1) { - if (aPath[i] < bPath[i]) - return -1; - if (aPath[i] > bPath[i]) - return 1; + if (parser.opt.xmlns) { + var qn = qname(parser.attribName, true); + var prefix = qn.prefix; + var local = qn.local; + if (prefix === "xmlns") + if (local === "xml" && parser.attribValue !== XML_NAMESPACE) + strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + ` +Actual: ` + parser.attribValue); + else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) + strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + ` +Actual: ` + parser.attribValue); + else { + var tag = parser.tag; + var parent = parser.tags[parser.tags.length - 1] || parser; + if (tag.ns === parent.ns) + tag.ns = Object.create(parent.ns); + tag.ns[local] = parser.attribValue; + } + parser.attribList.push([parser.attribName, parser.attribValue]); + } else { + parser.tag.attributes[parser.attribName] = parser.attribValue; + emitNode(parser, "onattribute", { + name: parser.attribName, + value: parser.attribValue + }); } - return aPath.length - bPath.length; - }); - const bumpStep = tasks.some((task) => task.triggers.length > 0); - const onlyChannels = getOnlyChannels(channels); - for (const task of tasks) { - checkpoint.versions_seen[task.name] ??= {}; - for (const chan of task.triggers) - if (chan in checkpoint.channel_versions) - checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; + parser.attribName = parser.attribValue = ""; } - let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); - const channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan))); - let usedNewVersion = false; - for (const chan of channelsToConsume) - if (chan in onlyChannels && onlyChannels[chan].consume()) { - if (getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - usedNewVersion = true; - } - } - const pendingWritesByChannel = {}; - for (const task of tasks) - for (const [chan, val] of task.writes) - if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { - pendingWritesByChannel[chan] ??= []; - pendingWritesByChannel[chan].push(val); - } - if (maxVersion != null && getNextVersion != null) - maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; - const updatedChannels = /* @__PURE__ */ new Set; - for (const [chan, vals] of Object.entries(pendingWritesByChannel)) - if (chan in onlyChannels) { - const channel = onlyChannels[chan]; - let updated; - try { - updated = channel.update(vals); - } catch (e) { - if (e.name === InvalidUpdateError.unminifiable_name) { - const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); - wrappedError.lc_error_code = e.lc_error_code; - throw wrappedError; - } else - throw e; - } - if (updated && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); + function openTag(parser, selfClosing) { + if (parser.opt.xmlns) { + var tag = parser.tag; + var qn = qname(parser.tagName); + tag.prefix = qn.prefix; + tag.local = qn.local; + tag.uri = tag.ns[qn.prefix] || ""; + if (tag.prefix && !tag.uri) { + strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); + tag.uri = qn.prefix; } - } - if (bumpStep) - for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) - continue; - const channel = onlyChannels[chan]; - if (channel.isAvailable() && !updatedChannels.has(chan)) { - if (channel.update([]) && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); + var parent = parser.tags[parser.tags.length - 1] || parser; + if (tag.ns && parent.ns !== tag.ns) + Object.keys(tag.ns).forEach(function(p) { + emitNode(parser, "onopennamespace", { + prefix: p, + uri: tag.ns[p] + }); + }); + for (var i = 0, l = parser.attribList.length;i < l; i++) { + var nv = parser.attribList[i]; + var name = nv[0]; + var value = nv[1]; + var qualName = qname(name, true); + var prefix = qualName.prefix; + var local = qualName.local; + var uri2 = prefix === "" ? "" : tag.ns[prefix] || ""; + var a = { + name, + value, + prefix, + local, + uri: uri2 + }; + if (prefix && prefix !== "xmlns" && !uri2) { + strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); + a.uri = prefix; } + parser.tag.attributes[name] = a; + emitNode(parser, "onattribute", a); } + parser.attribList.length = 0; } - if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) - for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) - continue; - const channel = onlyChannels[chan]; - if (channel.finish() && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); + parser.tag.isSelfClosing = !!selfClosing; + parser.sawRoot = true; + parser.tags.push(parser.tag); + emitNode(parser, "onopentag", parser.tag); + if (!selfClosing) { + if (!parser.noscript && parser.tagName.toLowerCase() === "script") + parser.state = S.SCRIPT; + else + parser.state = S.TEXT; + parser.tag = null; + parser.tagName = ""; + } + parser.attribName = parser.attribValue = ""; + parser.attribList.length = 0; + } + function closeTag(parser) { + if (!parser.tagName) { + strictFail(parser, "Weird empty close tag."); + parser.textNode += ""; + parser.state = S.TEXT; + return; + } + if (parser.script) { + if (parser.tagName !== "script") { + parser.script += ""; + parser.tagName = ""; + parser.state = S.SCRIPT; + return; } + emitNode(parser, "onscript", parser.script); + parser.script = ""; } - return updatedChannels; -} -function* candidateNodes(checkpoint, processes, extra) { - if (extra.updatedChannels != null && extra.triggerToNodes != null) { - const triggeredNodes = /* @__PURE__ */ new Set; - for (const channel of extra.updatedChannels) { - const nodeIds = extra.triggerToNodes[channel]; - for (const id of nodeIds ?? []) - triggeredNodes.add(id); + var t = parser.tags.length; + var tagName = parser.tagName; + if (!parser.strict) + tagName = tagName[parser.looseCase](); + var closeTo = tagName; + while (t--) + if (parser.tags[t].name !== closeTo) + strictFail(parser, "Unexpected close tag"); + else + break; + if (t < 0) { + strictFail(parser, "Unmatched closing tag: " + parser.tagName); + parser.textNode += ""; + parser.state = S.TEXT; + return; } - yield* [...triggeredNodes].sort(); - return; + parser.tagName = tagName; + var s2 = parser.tags.length; + while (s2-- > t) { + var tag = parser.tag = parser.tags.pop(); + parser.tagName = parser.tag.name; + emitNode(parser, "onclosetag", parser.tagName); + var x = {}; + for (var i in tag.ns) + x[i] = tag.ns[i]; + var parent = parser.tags[parser.tags.length - 1] || parser; + if (parser.opt.xmlns && tag.ns !== parent.ns) + Object.keys(tag.ns).forEach(function(p) { + var n2 = tag.ns[p]; + emitNode(parser, "onclosenamespace", { + prefix: p, + uri: n2 + }); + }); + } + if (t === 0) + parser.closedRoot = true; + parser.tagName = parser.attribValue = parser.attribName = ""; + parser.attribList.length = 0; + parser.state = S.TEXT; } - if ((() => { - for (const chan in checkpoint.channel_versions) - if (checkpoint.channel_versions[chan] !== null) - return false; - return true; - })()) - return; - for (const name in processes) { - if (!Object.prototype.hasOwnProperty.call(processes, name)) - continue; - yield name; + function parseEntity(parser) { + var entity = parser.entity; + var entityLC = entity.toLowerCase(); + var num; + var numStr = ""; + if (parser.ENTITIES[entity]) + return parser.ENTITIES[entity]; + if (parser.ENTITIES[entityLC]) + return parser.ENTITIES[entityLC]; + entity = entityLC; + if (entity.charAt(0) === "#") + if (entity.charAt(1) === "x") { + entity = entity.slice(2); + num = parseInt(entity, 16); + numStr = num.toString(16); + } else { + entity = entity.slice(1); + num = parseInt(entity, 10); + numStr = num.toString(10); + } + entity = entity.replace(/^0+/, ""); + if (isNaN(num) || numStr.toLowerCase() !== entity) { + strictFail(parser, "Invalid character entity"); + return "&" + parser.entity + ";"; + } + return String.fromCodePoint(num); } -} -function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config2, forExecution, extra) { - const tasks = {}; - const tasksChannel = channels[TASKS]; - if (tasksChannel?.isAvailable()) { - const len = tasksChannel.get().length; - for (let i = 0;i < len; i += 1) { - const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config2, forExecution, extra); - if (task !== undefined) - tasks[task.id] = task; + function beginWhiteSpace(parser, c) { + if (c === "<") { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else if (!isWhitespace(c)) { + strictFail(parser, "Non-whitespace before first tag."); + parser.textNode = c; + parser.state = S.TEXT; } } - for (const name of candidateNodes(checkpoint, processes, extra)) { - const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config2, forExecution, extra); - if (task !== undefined) - tasks[task.id] = task; + function charAt(chunk, i) { + var result = ""; + if (i < chunk.length) + result = chunk.charAt(i); + return result; } - return tasks; -} -function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config2, forExecution, extra) { - const { step, checkpointer, manager } = extra; - const configurable = config2.configurable ?? {}; - const parentNamespace = configurable.checkpoint_ns ?? ""; - if (taskPath[0] === "__pregel_push" && isCall(taskPath[taskPath.length - 1])) { - const call2 = taskPath[taskPath.length - 1]; - const proc = getRunnableForFunc(call2.name, call2.func); - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? call2.name : `${parentNamespace}|${call2.name}`; - const id = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - call2.name, - PUSH, - taskPath[1], - taskPath[2] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${id}`; - const outputTaskPath = [...taskPath.slice(0, 3), true]; - const metadata = { - langgraph_step: step, - langgraph_node: call2.name, - langgraph_triggers: triggers, - langgraph_path: outputTaskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId: id, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; - return { - name: call2.name, - input: call2.input, - proc, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - store: extra.store ?? config2.store - }), { - runName: call2.name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: id, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: call2.name, - writes, - triggers, - path: outputTaskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId: id, - currentTaskInput: call2.input, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace + function write(chunk) { + var parser = this; + if (this.error) + throw this.error; + if (parser.closed) + return error90(parser, "Cannot write after close. Assign an onready handler."); + if (chunk === null) + return end(parser); + if (typeof chunk === "object") + chunk = chunk.toString(); + var i = 0; + var c = ""; + while (true) { + c = charAt(chunk, i++); + parser.c = c; + if (!c) + break; + if (parser.trackPosition) { + parser.position++; + if (c === ` +`) { + parser.line++; + parser.column = 0; + } else + parser.column++; + } + switch (parser.state) { + case S.BEGIN: + parser.state = S.BEGIN_WHITESPACE; + if (c === "\uFEFF") + continue; + beginWhiteSpace(parser, c); + continue; + case S.BEGIN_WHITESPACE: + beginWhiteSpace(parser, c); + continue; + case S.TEXT: + if (parser.sawRoot && !parser.closedRoot) { + var starti = i - 1; + while (c && c !== "<" && c !== "&") { + c = charAt(chunk, i++); + if (c && parser.trackPosition) { + parser.position++; + if (c === ` +`) { + parser.line++; + parser.column = 0; + } else + parser.column++; + } } - }), - executionInfo - }, - triggers, - retry_policy: call2.retry, - cache_key: call2.cache ? { - key: XXH3((call2.cache.keyFunc ?? JSON.stringify)([call2.input])), - ns: [CACHE_NS_WRITES, call2.name ?? "__dynamic__"], - ttl: call2.cache.ttl - } : undefined, - id, - path: outputTaskPath, - writers: [] - }; - } else - return { - id, - name: call2.name, - interrupts: [], - path: outputTaskPath - }; - } else if (taskPath[0] === "__pregel_push") { - const index2 = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); - if (!channels["__pregel_tasks"]?.isAvailable()) - return; - const sends = channels[TASKS].get(); - if (index2 < 0 || index2 >= sends.length) - return; - const packet = _isSendInterface(sends[index2]) && !_isSend(sends[index2]) ? new Send(sends[index2].node, sends[index2].args) : sends[index2]; - if (!_isSendInterface(packet)) { - console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); - return; - } - if (!(packet.node in processes)) { - console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); - return; - } - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}|${packet.node}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - packet.node, - PUSH, - index2.toString() - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: packet.node, - langgraph_triggers: triggers, - langgraph_path: taskPath.slice(0, 3), - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const proc = processes[packet.node]; - const node = proc.getNode(); - if (node !== undefined) { - if (proc.metadata !== undefined) - metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; - return { - name: packet.node, - input: packet.args, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - tags: proc.tags, - store: extra.store ?? config2.store - }), { - runName: packet.node, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: packet.node, - writes, - triggers, - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: packet.args, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace - } - }), - executionInfo - }, - triggers, - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - packet.node - ], - ttl: proc.cachePolicy.ttl - } : undefined, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else - return { - id: taskId, - name: packet.node, - interrupts: [], - path: taskPath - }; - } else if (taskPath[0] === "__pregel_pull") { - const name = taskPath[1].toString(); - const proc = processes[name]; - if (proc === undefined) - return; - if (pendingWrites?.length) { - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - name - ]), checkpoint.id); - if (pendingWrites.some((w) => w[0] === taskId && w[1] !== "__error__")) - return; - } - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - if (nullVersion === undefined) - return; - const seen = checkpoint.versions_seen[name] ?? {}; - const trigger = proc.triggers.find((chan) => { - if (!channels[chan].isAvailable()) - return false; - return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); - }); - if (trigger !== undefined) { - const val = _procInput(proc, channels, forExecution); - if (val === undefined) - return; - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - [trigger] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: name, - langgraph_triggers: [trigger], - langgraph_path: taskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const node = proc.getNode(); - if (node !== undefined) { - if (proc.metadata !== undefined) - metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; - return { - name, - input: val, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - tags: proc.tags, - store: extra.store ?? config2.store - }), { - runName: name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { - writes.push(...items); - }, processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name, - writes, - triggers: [trigger], - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: val, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace - } - }), - executionInfo - }, - triggers: [trigger], - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - name - ], - ttl: proc.cachePolicy.ttl - } : undefined, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else - return { - id: taskId, - name, - interrupts: [], - path: taskPath - }; - } - } -} -function _procInput(proc, channels, forExecution) { - let val; - if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { - val = {}; - for (const [k, chan] of Object.entries(proc.channels)) - if (proc.triggers.includes(chan)) - try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) - return; + parser.textNode += chunk.substring(starti, i - 1); + } + if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else { + if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) + strictFail(parser, "Text data outside of root node."); + if (c === "&") + parser.state = S.TEXT_ENTITY; + else + parser.textNode += c; + } + continue; + case S.SCRIPT: + if (c === "<") + parser.state = S.SCRIPT_ENDING; else - throw e; - } - else if (chan in channels) - try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) + parser.script += c; + continue; + case S.SCRIPT_ENDING: + if (c === "/") + parser.state = S.CLOSE_TAG; + else { + parser.script += "<" + c; + parser.state = S.SCRIPT; + } + continue; + case S.OPEN_WAKA: + if (c === "!") { + parser.state = S.SGML_DECL; + parser.sgmlDecl = ""; + } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { + parser.state = S.OPEN_TAG; + parser.tagName = c; + } else if (c === "/") { + parser.state = S.CLOSE_TAG; + parser.tagName = ""; + } else if (c === "?") { + parser.state = S.PROC_INST; + parser.procInstName = parser.procInstBody = ""; + } else { + strictFail(parser, "Unencoded <"); + if (parser.startTagPosition + 1 < parser.position) { + var pad = parser.position - parser.startTagPosition; + c = new Array(pad).join(" ") + c; + } + parser.textNode += "<" + c; + parser.state = S.TEXT; + } + continue; + case S.SGML_DECL: + if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { + emitNode(parser, "onopencdata"); + parser.state = S.CDATA; + parser.sgmlDecl = ""; + parser.cdata = ""; + } else if (parser.sgmlDecl + c === "--") { + parser.state = S.COMMENT; + parser.comment = ""; + parser.sgmlDecl = ""; + } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { + parser.state = S.DOCTYPE; + if (parser.doctype || parser.sawRoot) + strictFail(parser, "Inappropriately located doctype declaration"); + parser.doctype = ""; + parser.sgmlDecl = ""; + } else if (c === ">") { + emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); + parser.sgmlDecl = ""; + parser.state = S.TEXT; + } else if (isQuote(c)) { + parser.state = S.SGML_DECL_QUOTED; + parser.sgmlDecl += c; + } else + parser.sgmlDecl += c; + continue; + case S.SGML_DECL_QUOTED: + if (c === parser.q) { + parser.state = S.SGML_DECL; + parser.q = ""; + } + parser.sgmlDecl += c; + continue; + case S.DOCTYPE: + if (c === ">") { + parser.state = S.TEXT; + emitNode(parser, "ondoctype", parser.doctype); + parser.doctype = true; + } else { + parser.doctype += c; + if (c === "[") + parser.state = S.DOCTYPE_DTD; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_QUOTED; + parser.q = c; + } + } + continue; + case S.DOCTYPE_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.q = ""; + parser.state = S.DOCTYPE; + } + continue; + case S.DOCTYPE_DTD: + parser.doctype += c; + if (c === "]") + parser.state = S.DOCTYPE; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_DTD_QUOTED; + parser.q = c; + } + continue; + case S.DOCTYPE_DTD_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.state = S.DOCTYPE_DTD; + parser.q = ""; + } + continue; + case S.COMMENT: + if (c === "-") + parser.state = S.COMMENT_ENDING; + else + parser.comment += c; + continue; + case S.COMMENT_ENDING: + if (c === "-") { + parser.state = S.COMMENT_ENDED; + parser.comment = textopts(parser.opt, parser.comment); + if (parser.comment) + emitNode(parser, "oncomment", parser.comment); + parser.comment = ""; + } else { + parser.comment += "-" + c; + parser.state = S.COMMENT; + } + continue; + case S.COMMENT_ENDED: + if (c !== ">") { + strictFail(parser, "Malformed comment"); + parser.comment += "--" + c; + parser.state = S.COMMENT; + } else + parser.state = S.TEXT; + continue; + case S.CDATA: + if (c === "]") + parser.state = S.CDATA_ENDING; + else + parser.cdata += c; + continue; + case S.CDATA_ENDING: + if (c === "]") + parser.state = S.CDATA_ENDING_2; + else { + parser.cdata += "]" + c; + parser.state = S.CDATA; + } + continue; + case S.CDATA_ENDING_2: + if (c === ">") { + if (parser.cdata) + emitNode(parser, "oncdata", parser.cdata); + emitNode(parser, "onclosecdata"); + parser.cdata = ""; + parser.state = S.TEXT; + } else if (c === "]") + parser.cdata += "]"; + else { + parser.cdata += "]]" + c; + parser.state = S.CDATA; + } + continue; + case S.PROC_INST: + if (c === "?") + parser.state = S.PROC_INST_ENDING; + else if (isWhitespace(c)) + parser.state = S.PROC_INST_BODY; + else + parser.procInstName += c; + continue; + case S.PROC_INST_BODY: + if (!parser.procInstBody && isWhitespace(c)) continue; + else if (c === "?") + parser.state = S.PROC_INST_ENDING; else - throw e; - } - } else if (Array.isArray(proc.channels)) { - let successfulRead = false; - for (const chan of proc.channels) - try { - val = readChannel(channels, chan, false); - successfulRead = true; - break; - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) + parser.procInstBody += c; continue; - else - throw e; - } - if (!successfulRead) - return; - } else - throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); - if (forExecution && proc.mapper !== undefined) - val = proc.mapper(val); - return val; -} -function sanitizeUntrackedValuesInSend(packet, channels) { - if (typeof packet.args !== "object" || packet.args === null) - return packet; - const sanitizedArg = {}; - for (const [key, value] of Object.entries(packet.args)) { - const channel = channels[key]; - if (!channel || channel.lc_graph_name !== "UntrackedValue") - sanitizedArg[key] = value; - } - return new Send(packet.node, sanitizedArg); -} -function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { - const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__")?.[2]; - const scratchpad = { - callCounter: 0, - interruptCounter: -1, - resume: (() => { - const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === "__resume__").flatMap(([_writeTaskId, _chan, resume]) => resume); - if (resumeMap != null && namespaceHash in resumeMap) { - const mappedResume = resumeMap[namespaceHash]; - result.push(mappedResume); - } - return result; - })(), - nullResume, - subgraphCounter: 0, - currentTaskInput, - consumeNullResume: () => { - if (scratchpad.nullResume) { - delete scratchpad.nullResume; - pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__"), 1); - return nullResume; + case S.PROC_INST_ENDING: + if (c === ">") { + emitNode(parser, "onprocessinginstruction", { + name: parser.procInstName, + body: parser.procInstBody + }); + parser.procInstName = parser.procInstBody = ""; + parser.state = S.TEXT; + } else { + parser.procInstBody += "?" + c; + parser.state = S.PROC_INST_BODY; + } + continue; + case S.OPEN_TAG: + if (isMatch(nameBody, c)) + parser.tagName += c; + else { + newTag(parser); + if (c === ">") + openTag(parser); + else if (c === "/") + parser.state = S.OPEN_TAG_SLASH; + else { + if (!isWhitespace(c)) + strictFail(parser, "Invalid character in tag name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.OPEN_TAG_SLASH: + if (c === ">") { + openTag(parser, true); + closeTag(parser); + } else { + strictFail(parser, "Forward-slash in opening tag not followed by >"); + parser.state = S.ATTRIB; + } + continue; + case S.ATTRIB: + if (isWhitespace(c)) + continue; + else if (c === ">") + openTag(parser); + else if (c === "/") + parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else + strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME: + if (c === "=") + parser.state = S.ATTRIB_VALUE; + else if (c === ">") { + strictFail(parser, "Attribute without value"); + parser.attribValue = parser.attribName; + attrib(parser); + openTag(parser); + } else if (isWhitespace(c)) + parser.state = S.ATTRIB_NAME_SAW_WHITE; + else if (isMatch(nameBody, c)) + parser.attribName += c; + else + strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME_SAW_WHITE: + if (c === "=") + parser.state = S.ATTRIB_VALUE; + else if (isWhitespace(c)) + continue; + else { + strictFail(parser, "Attribute without value"); + parser.tag.attributes[parser.attribName] = ""; + parser.attribValue = ""; + emitNode(parser, "onattribute", { + name: parser.attribName, + value: "" + }); + parser.attribName = ""; + if (c === ">") + openTag(parser); + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.state = S.ATTRIB_NAME; + } else { + strictFail(parser, "Invalid attribute name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.ATTRIB_VALUE: + if (isWhitespace(c)) + continue; + else if (isQuote(c)) { + parser.q = c; + parser.state = S.ATTRIB_VALUE_QUOTED; + } else { + strictFail(parser, "Unquoted attribute value"); + parser.state = S.ATTRIB_VALUE_UNQUOTED; + parser.attribValue = c; + } + continue; + case S.ATTRIB_VALUE_QUOTED: + if (c !== parser.q) { + if (c === "&") + parser.state = S.ATTRIB_VALUE_ENTITY_Q; + else + parser.attribValue += c; + continue; + } + attrib(parser); + parser.q = ""; + parser.state = S.ATTRIB_VALUE_CLOSED; + continue; + case S.ATTRIB_VALUE_CLOSED: + if (isWhitespace(c)) + parser.state = S.ATTRIB; + else if (c === ">") + openTag(parser); + else if (c === "/") + parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + strictFail(parser, "No whitespace between attributes"); + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else + strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_VALUE_UNQUOTED: + if (!isAttribEnd(c)) { + if (c === "&") + parser.state = S.ATTRIB_VALUE_ENTITY_U; + else + parser.attribValue += c; + continue; + } + attrib(parser); + if (c === ">") + openTag(parser); + else + parser.state = S.ATTRIB; + continue; + case S.CLOSE_TAG: + if (!parser.tagName) + if (isWhitespace(c)) + continue; + else if (notMatch(nameStart, c)) + if (parser.script) { + parser.script += "") + closeTag(parser); + else if (isMatch(nameBody, c)) + parser.tagName += c; + else if (parser.script) { + parser.script += "") + closeTag(parser); + else + strictFail(parser, "Invalid characters in closing tag"); + continue; + case S.TEXT_ENTITY: + case S.ATTRIB_VALUE_ENTITY_Q: + case S.ATTRIB_VALUE_ENTITY_U: + var returnState; + var buffer; + switch (parser.state) { + case S.TEXT_ENTITY: + returnState = S.TEXT; + buffer = "textNode"; + break; + case S.ATTRIB_VALUE_ENTITY_Q: + returnState = S.ATTRIB_VALUE_QUOTED; + buffer = "attribValue"; + break; + case S.ATTRIB_VALUE_ENTITY_U: + returnState = S.ATTRIB_VALUE_UNQUOTED; + buffer = "attribValue"; + break; + } + if (c === ";") + if (parser.opt.unparsedEntities) { + var parsedEntity = parseEntity(parser); + parser.entity = ""; + parser.state = returnState; + parser.write(parsedEntity); + } else { + parser[buffer] += parseEntity(parser); + parser.entity = ""; + parser.state = returnState; + } + else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) + parser.entity += c; + else { + strictFail(parser, "Invalid character in entity name"); + parser[buffer] += "&" + parser.entity + c; + parser.entity = ""; + parser.state = returnState; + } + continue; + default: + throw new Error(parser, "Unknown state: " + parser.state); } } - }; - return scratchpad; -} -var increment = (current) => { - return current !== undefined ? current + 1 : 1; -}, IGNORE; -var init_algo = __esm(() => { - init_constants3(); - init_errors5(); - init_base15(); - init_hash3(); - init_io(); - init_types7(); - init_utils9(); - init_call(); - init_dist3(); - init_runnables(); - IGNORE = new Set([ - NO_WRITES, - PUSH, - RESUME, - INTERRUPT, - RETURN, - ERROR2 - ]); + if (parser.position >= parser.bufferCheckPosition) + checkBufferLength(parser); + return parser; + } + /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ + if (!String.fromCodePoint) + (function() { + var stringFromCharCode = String.fromCharCode; + var floor = Math.floor; + var fromCodePoint = function() { + var MAX_SIZE = 16384; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) + return ""; + var result = ""; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) + throw RangeError("Invalid code point: " + codePoint); + if (codePoint <= 65535) + codeUnits.push(codePoint); + else { + codePoint -= 65536; + highSurrogate = (codePoint >> 10) + 55296; + lowSurrogate = codePoint % 1024 + 56320; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 === length || codeUnits.length > MAX_SIZE) { + result += stringFromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + }; + if (Object.defineProperty) + Object.defineProperty(String, "fromCodePoint", { + value: fromCodePoint, + configurable: true, + writable: true + }); + else + String.fromCodePoint = fromCodePoint; + })(); + return sax; +}, sax; +var init_sax = __esm(() => { + sax = initializeSax(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/debug.js -function* mapDebugTasks(tasks) { - for (const { id, name, input, config: config2, triggers, writes } of tasks) { - if (config2?.tags?.includes("langsmith:hidden")) - continue; - yield { - id, - name, - input, - triggers, - interrupts: writes.filter(([writeId, n3]) => { - return writeId === id && n3 === "__interrupt__"; - }).map(([, v]) => { - return v; - }) +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/xml.js +function parseXMLMarkdown(s) { + const cleanedString = strip(s); + const parser = sax.parser(true); + let parsedResult = {}; + const elementStack = []; + parser.onopentag = (node) => { + const element = { + name: node.name, + attributes: node.attributes, + children: [], + text: "", + isSelfClosing: node.isSelfClosing }; - } -} -function isMultipleChannelWrite(value) { - if (typeof value !== "object" || value === null) - return false; - return "$writes" in value && Array.isArray(value.$writes); + if (elementStack.length > 0) + elementStack[elementStack.length - 1].children.push(element); + else + parsedResult = element; + if (!node.isSelfClosing) + elementStack.push(element); + }; + parser.onclosetag = () => { + if (elementStack.length > 0) { + const lastElement = elementStack.pop(); + if (elementStack.length === 0 && lastElement) + parsedResult = lastElement; + } + }; + parser.ontext = (text) => { + if (elementStack.length > 0) { + const currentElement = elementStack[elementStack.length - 1]; + currentElement.text += text; + } + }; + parser.onattribute = (attr) => { + if (elementStack.length > 0) { + const currentElement = elementStack[elementStack.length - 1]; + currentElement.attributes[attr.name] = attr.value; + } + }; + const match2 = /```(xml)?(.*)```/s.exec(cleanedString); + const xmlString = match2 ? match2[2] : cleanedString; + parser.write(xmlString).close(); + if (parsedResult && parsedResult.name === "?xml") + parsedResult = parsedResult.children[0]; + return parseParsedResult(parsedResult); } -function mapTaskResultWrites(writes) { +var XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. +1. Output should conform to the tags below. +2. If tags are not given, make them on your own. +3. Remember to always open and close all the tags. + +As an example, for the tags ["foo", "bar", "baz"]: +1. String " + + + +" is a well-formatted instance of the schema. +2. String " + + " is a badly-formatted instance. +3. String " + + +" is a badly-formatted instance. + +Here are the output tags: +\`\`\` +{tags} +\`\`\``, XMLOutputParser, strip = (text) => text.split(` +`).map((line) => line.replace(/^\s+/, "")).join(` +`).trim(), parseParsedResult = (input) => { + if (Object.keys(input).length === 0) + return {}; const result = {}; - for (const [channel, value] of writes) { - const strChannel = String(channel); - if (strChannel in result) { - const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; - channelWrites.push(value); - result[strChannel] = { $writes: channelWrites }; - } else - result[strChannel] = value; - } - return result; -} -function* mapDebugTaskResults(tasks, streamChannels) { - for (const [{ id, name, config: config2 }, writes] of tasks) { - if (config2?.tags?.includes("langsmith:hidden")) - continue; - yield { - id, - name, - result: mapTaskResultWrites(writes.filter(([channel]) => { - return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; - })), - interrupts: writes.filter((w) => w[0] === INTERRUPT).map((w) => w[1]) - }; - } -} -function* mapDebugCheckpoint(config2, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { - function formatConfig(config3) { - const pyConfig = {}; - if (config3.callbacks != null) - pyConfig.callbacks = config3.callbacks; - if (config3.configurable != null) - pyConfig.configurable = config3.configurable; - if (config3.maxConcurrency != null) - pyConfig.max_concurrency = config3.maxConcurrency; - if (config3.metadata != null) - pyConfig.metadata = config3.metadata; - if (config3.recursionLimit != null) - pyConfig.recursion_limit = config3.recursionLimit; - if (config3.runId != null) - pyConfig.run_id = config3.runId; - if (config3.runName != null) - pyConfig.run_name = config3.runName; - if (config3.tags != null) - pyConfig.tags = config3.tags; - return pyConfig; - } - const parentNs = config2.configurable?.checkpoint_ns; - const taskStates = {}; - for (const task of tasks) { - if (!((task.subgraphs?.length) ? task.subgraphs : [task.proc]).find(findSubgraphPregel)) - continue; - let taskNs = `${task.name}:${task.id}`; - if (parentNs) - taskNs = `${parentNs}|${taskNs}`; - taskStates[task.id] = { configurable: { - thread_id: config2.configurable?.thread_id, - checkpoint_ns: taskNs - } }; + if (input.children.length > 0) { + result[input.name] = input.children.map(parseParsedResult); + return result; + } else { + result[input.name] = input.text ?? undefined; + return result; } - yield { - config: formatConfig(config2), - values: readChannels(channels, streamChannels), - metadata, - next: tasks.map((task) => task.name), - tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), - parentConfig: parentConfig ? formatConfig(parentConfig) : undefined - }; -} -function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { - return tasks.map((task) => { - const error51 = pendingWrites.find(([id, n3]) => id === task.id && n3 === "__error__")?.[2]; - const interrupts = pendingWrites.filter(([id, n3]) => id === task.id && n3 === "__interrupt__").map(([, , v]) => v); - const result = (() => { - if (error51 || interrupts.length || !pendingWrites.length) +}; +var init_xml = __esm(() => { + init_duplex(); + init_transform(); + init_json_patch(); + init_sax(); + XMLOutputParser = class extends BaseCumulativeTransformOutputParser { + tags; + constructor(fields) { + super(fields); + this.tags = fields?.tags; + } + static lc_name() { + return "XMLOutputParser"; + } + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + _diff(prev, next) { + if (!next) return; - const idx = pendingWrites.findIndex(([tid, n3]) => tid === task.id && n3 === "__return__"); - if (idx >= 0) - return pendingWrites[idx][2]; - if (typeof outputKeys === "string") - return pendingWrites.find(([tid, n3]) => tid === task.id && n3 === outputKeys)?.[2]; - if (Array.isArray(outputKeys)) { - const results = pendingWrites.filter(([tid, n3]) => tid === task.id && outputKeys.includes(n3)).map(([, n3, v]) => [n3, v]); - if (!results.length) - return; - return mapTaskResultWrites(results); - } - })(); - if (error51) - return { - id: task.id, - name: task.name, - path: task.path, - error: error51, - interrupts, - result - }; - const taskState = states?.[task.id]; - return { - id: task.id, - name: task.name, - path: task.path, - interrupts, - ...taskState !== undefined ? { state: taskState } : {}, - result - }; - }); -} -function printStepCheckpoint(step, channels, whitelist) { - console.log([ - `${wrap2(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, - `\x1B[1m State at the end of step ${step}:\x1B[0m -`, - JSON.stringify(readChannels(channels, whitelist), null, 2) - ].join("")); -} -function printStepTasks(step, nextTasks) { - const nTasks = nextTasks.length; - console.log([ - `${wrap2(COLORS_MAP.blue, `[${step}:tasks]`)}`, - `\x1B[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1B[0m -`, - nextTasks.map((task) => `- ${wrap2(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join(` -`) - ].join("")); -} -function printStepWrites(step, writes, whitelist) { - const byChannel = {}; - for (const [channel, value] of writes) - if (whitelist.includes(channel)) { - if (!byChannel[channel]) - byChannel[channel] = []; - byChannel[channel].push(value); + if (!prev) + return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); } - console.log([ - `${wrap2(COLORS_MAP.blue, `[${step}:writes]`)}`, - `\x1B[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1B[0m -`, - Object.entries(byChannel).map(([name, vals]) => `- ${wrap2(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join(` -`) - ].join("")); -} -var COLORS_MAP, wrap2 = (color2, text) => `${color2.start}${text}${color2.end}`; -var init_debug = __esm(() => { - init_constants3(); - init_io(); - init_subgraph(); - COLORS_MAP = { - blue: { - start: "\x1B[34m", - end: "\x1B[0m" - }, - green: { - start: "\x1B[32m", - end: "\x1B[0m" - }, - yellow: { - start: "\x1B[33;1m", - end: "\x1B[0m" + async parsePartialResult(generations) { + return parseXMLMarkdown(generations[0].text); + } + async parse(text) { + return parseXMLMarkdown(text); + } + getFormatInstructions() { + return this.tags && this.tags.length > 0 ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/stream.js -function _stringifyAsDict(obj) { - return JSON.stringify(obj, function(key, value) { - const rawValue2 = this[key]; - if (rawValue2 != null && typeof rawValue2 === "object" && "toDict" in rawValue2 && typeof rawValue2.toDict === "function") { - const { type, data } = rawValue2.toDict(); - return { - ...data, - type - }; - } - return value; - }); -} -function _serializeError(error51) { - if (error51 instanceof Error) - return { - error: error51.name, - message: error51.message - }; - return { - error: "Error", - message: JSON.stringify(error51) - }; -} -function _isRunnableConfig(config2) { - if (typeof config2 !== "object" || config2 == null) - return false; - return "configurable" in config2 && typeof config2.configurable === "object" && config2.configurable != null; -} -function _extractCheckpointFromConfig(config2) { - if (!_isRunnableConfig(config2) || !config2.configurable.thread_id) - return null; - return { - thread_id: config2.configurable.thread_id, - checkpoint_ns: config2.configurable.checkpoint_ns || "", - checkpoint_id: config2.configurable.checkpoint_id || null, - checkpoint_map: config2.configurable.checkpoint_map || null - }; -} -function _serializeConfig(config2) { - if (_isRunnableConfig(config2)) { - const configurable = Object.fromEntries(Object.entries(config2.configurable).filter(([key]) => !key.startsWith("__"))); - const newConfig = { - ...config2, - configurable - }; - delete newConfig.callbacks; - return newConfig; - } - return config2; -} -function _serializeCheckpoint(payload) { - const result = { - ...payload, - checkpoint: _extractCheckpointFromConfig(payload.config), - parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), - config: _serializeConfig(payload.config), - parent_config: _serializeConfig(payload.parentConfig), - tasks: payload.tasks.map((task) => { - if (_isRunnableConfig(task.state)) { - const checkpoint = _extractCheckpointFromConfig(task.state); - if (checkpoint != null) { - const cloneTask = { - ...task, - checkpoint - }; - delete cloneTask.state; - return cloneTask; - } - } - return task; - }) - }; - delete result.parentConfig; - return result; -} -function toEventStream(stream2) { - const encoder2 = new TextEncoder; - return new ReadableStream({ async start(controller) { - const enqueueChunk = (sse) => { - controller.enqueue(encoder2.encode(`event: ${sse.event} -data: ${_stringifyAsDict(sse.data)} +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/index.js +var output_parsers_exports; +var init_output_parsers = __esm(() => { + init_runtime2(); + init_json(); + init_base6(); + init_transform(); + init_bytes(); + init_list(); + init_string2(); + init_json2(); + init_standard_schema2(); + init_structured(); + init_xml(); + output_parsers_exports = /* @__PURE__ */ __exportAll({ + AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, + BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, + BaseLLMOutputParser: () => BaseLLMOutputParser, + BaseOutputParser: () => BaseOutputParser, + BaseTransformOutputParser: () => BaseTransformOutputParser, + BytesOutputParser: () => BytesOutputParser, + CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, + CustomListOutputParser: () => CustomListOutputParser, + JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, + JsonOutputParser: () => JsonOutputParser, + ListOutputParser: () => ListOutputParser, + MarkdownListOutputParser: () => MarkdownListOutputParser, + NumberedListOutputParser: () => NumberedListOutputParser, + OutputParserException: () => OutputParserException, + StandardSchemaOutputParser: () => StandardSchemaOutputParser, + StringOutputParser: () => StringOutputParser, + StructuredOutputParser: () => StructuredOutputParser, + XMLOutputParser: () => XMLOutputParser, + XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, + parseJsonMarkdown: () => parseJsonMarkdown, + parsePartialJson: () => parsePartialJson, + parseXMLMarkdown: () => parseXMLMarkdown + }); +}); -`)); - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js +function parseToolCall(rawToolCall, options) { + if (rawToolCall.function === undefined) + return; + let functionArgs; + if (options?.partial) try { - for await (const payload of stream2) { - const [ns3, mode, chunk] = payload; - let data = chunk; - if (mode === "debug") { - const debugChunk = chunk; - if (debugChunk.type === "checkpoint") - data = { - ...debugChunk, - payload: _serializeCheckpoint(debugChunk.payload) - }; - } - if (mode === "checkpoints") - data = _serializeCheckpoint(chunk); - enqueueChunk({ - event: ns3?.length ? `${mode}|${ns3.join("|")}` : mode, - data - }); - } - } catch (error51) { - enqueueChunk({ - event: "error", - data: _serializeError(error51) - }); - } - controller.close(); - } }); -} -var IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, StreamToolsHandler; -var init_stream5 = __esm(() => { - init_constants3(); - init_stream(); - init_base2(); - IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { - _abortController; - _innerReader; - constructor(readableStream, abortController) { - const reader = readableStream.getReader(); - const ac = abortController ?? new AbortController; - super({ start(controller) { - return pump2(); - function pump2() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump2(); - }); - } - } }); - this._abortController = ac; - this._innerReader = reader; + functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); + } catch { + return; } - async cancel(reason) { - this._abortController.abort(reason); - this._innerReader.releaseLock(); + else + try { + functionArgs = JSON.parse(rawToolCall.function.arguments); + } catch (e) { + throw new OutputParserException([ + `Function "${rawToolCall.function.name}" arguments:`, + ``, + rawToolCall.function.arguments, + ``, + `are not valid JSON.`, + `Error: ${e.message}` + ].join(` +`)); } - get signal() { - return this._abortController.signal; + const parsedToolCall = { + name: rawToolCall.function.name, + args: functionArgs, + type: "tool_call" + }; + if (options?.returnId) + parsedToolCall.id = rawToolCall.id; + return parsedToolCall; +} +function convertLangChainToolCallToOpenAI(toolCall) { + if (toolCall.id === undefined) + throw new Error(`All OpenAI tool calls must have an "id" field.`); + return { + id: toolCall.id, + type: "function", + function: { + name: toolCall.name, + arguments: JSON.stringify(toolCall.args) } }; - IterableReadableWritableStream = class extends IterableReadableStream { - modes; - controller; - passthroughFn; - _closed = false; - get closed() { - return this._closed; +} +function makeInvalidToolCall(rawToolCall, errorMsg) { + return { + name: rawToolCall.function?.name, + args: rawToolCall.function?.arguments, + id: rawToolCall.id, + error: errorMsg, + type: "invalid_tool_call" + }; +} +var JsonOutputToolsParser, JsonOutputKeyToolsParser; +var init_json_output_tools_parsers = __esm(() => { + init_json(); + init_ai(); + init_zod2(); + init_base6(); + init_transform(); + init_json2(); + JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputToolsParser"; } - constructor(params) { - let streamControllerPromiseResolver; - const streamControllerPromise = new Promise((resolve2) => { - streamControllerPromiseResolver = resolve2; - }); - super({ start: (controller) => { - streamControllerPromiseResolver(controller); - } }); - streamControllerPromise.then((controller) => { - this.controller = controller; - }); - this.passthroughFn = params.passthroughFn; - this.modes = params.modes; + returnId = false; + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + constructor(fields) { + super(fields); + this.returnId = fields?.returnId ?? this.returnId; } - push(chunk) { - this.passthroughFn?.(chunk); - this.controller.enqueue(chunk); + _diff() { + throw new Error("Not supported."); } - close() { - try { - this.controller.close(); - } catch {} finally { - this._closed = true; - } + async parse() { + throw new Error("Not implemented."); } - error(e) { - this.controller.error(e); + async parseResult(generations) { + return await this.parsePartialResult(generations, false); + } + async parsePartialResult(generations, partial3 = true) { + const message = generations[0].message; + let toolCalls; + if (isAIMessage(message) && message.tool_calls?.length) + toolCalls = message.tool_calls.map((toolCall) => { + const { id, ...rest } = toolCall; + if (!this.returnId) + return rest; + return { + id, + ...rest + }; + }); + else if (message.additional_kwargs.tool_calls !== undefined) + toolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)).map((rawToolCall) => { + return parseToolCall(rawToolCall, { + returnId: this.returnId, + partial: partial3 + }); + }); + if (!toolCalls) + return []; + const parsedToolCalls = []; + for (const toolCall of toolCalls) + if (toolCall !== undefined) { + const backwardsCompatibleToolCall = { + type: toolCall.name, + args: toolCall.args, + id: toolCall.id + }; + parsedToolCalls.push(backwardsCompatibleToolCall); + } + return parsedToolCalls; } }; - StreamToolsHandler = class extends BaseCallbackHandler { - name = "StreamToolsHandler"; - streamFn; - runs = {}; - constructor(streamFn) { - super(); - this.streamFn = streamFn; + JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { + static lc_name() { + return "JsonOutputKeyToolsParser"; } - handleToolStart(_tool, input, runId, _parentRunId, tags, metadata, runName, toolCallId) { - if (!metadata || tags && tags.includes("langsmith:hidden")) - return; - const ns3 = metadata.langgraph_checkpoint_ns?.split("|") ?? []; - const info = { - ns: ns3, - toolCallId, - toolName: runName ?? "unknown", - input - }; - this.runs[runId] = info; - this.streamFn([ - ns3, - "tools", - { - event: "on_tool_start", - toolCallId: info.toolCallId, - name: info.toolName, - input - } - ]); + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + returnId = false; + keyName; + returnSingle = false; + zodSchema; + serializableSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + if ("zodSchema" in params) + this.zodSchema = params.zodSchema; + if ("serializableSchema" in params) + this.serializableSchema = params.serializableSchema; } - handleToolEvent(chunk, runId) { - const info = this.runs[runId]; - if (!info) - return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_event", - toolCallId: info.toolCallId, - name: info.toolName, - data: chunk - } - ]); + async _validateResult(result) { + if (this.serializableSchema !== undefined) { + const validated = await this.serializableSchema["~standard"].validate(result); + if (validated.issues) + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(result, null, 2)); + return validated.value; + } + if (this.zodSchema === undefined) + return result; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); + if (zodParsedResult.success) + return zodParsedResult.data; + else + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); } - handleToolEnd(output, runId) { - const info = this.runs[runId]; - delete this.runs[runId]; - if (!info) + async parsePartialResult(generations) { + const matchingResults = (await super.parsePartialResult(generations)).filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_end", - toolCallId: info.toolCallId, - name: info.toolName, - output - } - ]); + if (!this.returnId) + returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) + return returnedValues[0]; + return returnedValues; } - handleToolError(err, runId) { - const info = this.runs[runId]; - delete this.runs[runId]; - if (!info) + async parseResult(generations) { + const matchingResults = (await super.parsePartialResult(generations, false)).filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_error", - toolCallId: info.toolCallId, - name: info.toolName, - error: err - } - ]); + if (!this.returnId) + returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) + return this._validateResult(returnedValues[0]); + return await Promise.all(returnedValues.map((value) => this._validateResult(value))); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/loop.js -function createDuplexStream(...streams) { - return new IterableReadableWritableStream({ - passthroughFn: (value) => { - for (const stream2 of streams) - if (stream2.modes.has(value[1])) - stream2.push(value); - }, - modes: new Set(streams.flatMap((s) => Array.from(s.modes))) +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/types/index.js +var types_exports; +var init_types3 = __esm(() => { + init_runtime2(); + init_zod2(); + types_exports = /* @__PURE__ */ __exportAll({ + extendInteropZodObject: () => extendInteropZodObject, + getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, + getInteropZodObjectShape: () => getInteropZodObjectShape, + getSchemaDescription: () => getSchemaDescription, + interopParse: () => interopParse, + interopParseAsync: () => interopParseAsync, + interopSafeParse: () => interopSafeParse, + interopSafeParseAsync: () => interopSafeParseAsync, + interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, + interopZodObjectPartial: () => interopZodObjectPartial, + interopZodObjectPassthrough: () => interopZodObjectPassthrough, + interopZodObjectStrict: () => interopZodObjectStrict, + interopZodTransformInputSchema: () => interopZodTransformInputSchema, + isInteropZodError: () => isInteropZodError, + isInteropZodLiteral: () => isInteropZodLiteral, + isInteropZodObject: () => isInteropZodObject, + isInteropZodSchema: () => isInteropZodSchema, + isShapelessZodSchema: () => isShapelessZodSchema, + isSimpleStringZodSchema: () => isSimpleStringZodSchema, + isZodArrayV4: () => isZodArrayV4, + isZodLiteralV3: () => isZodLiteralV3, + isZodLiteralV4: () => isZodLiteralV4, + isZodNullableV4: () => isZodNullableV4, + isZodObjectV3: () => isZodObjectV3, + isZodObjectV4: () => isZodObjectV4, + isZodOptionalV4: () => isZodOptionalV4, + isZodSchema: () => isZodSchema, + isZodSchemaV3: () => isZodSchemaV3, + isZodSchemaV4: () => isZodSchemaV4 }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/structured_output.js +function createContentParser(schema) { + if (isInteropZodSchema(schema)) + return StructuredOutputParser.fromZodSchema(schema); + if (isSerializableSchema(schema)) + return StandardSchemaOutputParser.fromSerializableSchema(schema); + return new JsonOutputParser; } -var INPUT_DONE, INPUT_RESUMING, DEFAULT_LOOP_LIMIT = 25, AsyncBatchedCache, PregelLoop = class PregelLoop2 { - input; - output; - config; - checkpointer; - checkpointerGetNextVersion; - channels; - checkpoint; - checkpointIdSaved; - checkpointConfig; - checkpointMetadata; - checkpointNamespace; - checkpointPendingWrites = []; - checkpointPreviousVersions; - step; - stop; - durability; - outputKeys; - streamKeys; - nodes; - skipDoneTasks; - prevCheckpointConfig; - updatedChannels; - status = "pending"; - tasks = {}; - stream; - checkpointerPromises = /* @__PURE__ */ new Set; - isNested; - _checkpointerChainedPromise = Promise.resolve(); - _trackCheckpointerPromise(promise2) { - const tracked = promise2.then((value) => { - this.checkpointerPromises.delete(tracked); - return value; - }, (error51) => { - throw error51; +function createFunctionCallingParser(schema, keyName, ParserClass) { + const Ctor = ParserClass ?? JsonOutputKeyToolsParser; + if (isInteropZodSchema(schema)) + return new Ctor({ + returnSingle: true, + keyName, + zodSchema: schema }); - this.checkpointerPromises.add(tracked); - } - store; - cache; - manager; - interruptAfter; - interruptBefore; - toInterrupt = []; - debug = false; - triggerToNodes; - get isResuming() { - let hasChannelVersions = false; - if ("__start__" in this.checkpoint.channel_versions) - hasChannelVersions = true; - else - for (const chan in this.checkpoint.channel_versions) - if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { - hasChannelVersions = true; - break; - } - const configIsResuming = this.config.configurable?.["__pregel_resuming"] !== undefined && this.config.configurable?.["__pregel_resuming"]; - const inputIsNullOrUndefined = this.input === null || this.input === undefined; - const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; - const inputIsResuming = this.input === INPUT_RESUMING; - const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== undefined && this.checkpointMetadata?.run_id !== undefined && this.config.metadata.run_id === this.checkpointMetadata?.run_id; - return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); + if (isSerializableSchema(schema)) + return new Ctor({ + returnSingle: true, + keyName, + serializableSchema: schema + }); + return new Ctor({ + returnSingle: true, + keyName + }); +} +function assembleStructuredOutputPipeline(llm, outputParser, includeRaw, runName) { + if (!includeRaw) { + const result2 = llm.pipe(outputParser); + return runName ? result2.withConfig({ runName }) : result2; } - constructor(params) { - this.input = params.input; - this.checkpointer = params.checkpointer; - if (this.checkpointer !== undefined) - this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); - else - this.checkpointerGetNextVersion = increment; - this.checkpoint = params.checkpoint; - this.checkpointMetadata = params.checkpointMetadata; - this.checkpointPreviousVersions = params.checkpointPreviousVersions; - this.channels = params.channels; - this.checkpointPendingWrites = params.checkpointPendingWrites; - this.step = params.step; - this.stop = params.stop; - this.config = params.config; - this.checkpointConfig = params.checkpointConfig; - this.isNested = params.isNested; - this.manager = params.manager; - this.outputKeys = params.outputKeys; - this.streamKeys = params.streamKeys; - this.nodes = params.nodes; - this.skipDoneTasks = params.skipDoneTasks; - this.store = params.store; - this.cache = params.cache ? new AsyncBatchedCache(params.cache) : undefined; - this.stream = params.stream; - this.checkpointNamespace = params.checkpointNamespace; - this.prevCheckpointConfig = params.prevCheckpointConfig; - this.interruptAfter = params.interruptAfter; - this.interruptBefore = params.interruptBefore; - this.durability = params.durability; - this.debug = params.debug; - this.triggerToNodes = params.triggerToNodes; + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config3) => outputParser.invoke(input.raw, config3) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + const result = RunnableSequence.from([{ raw: llm }, parsedWithFallback]); + return runName ? result.withConfig({ runName }) : result; +} +var structured_output_exports; +var init_structured_output = __esm(() => { + init_runtime2(); + init_zod2(); + init_standard_schema(); + init_base4(); + init_passthrough(); + init_runnables(); + init_json2(); + init_standard_schema2(); + init_structured(); + init_output_parsers(); + init_json_output_tools_parsers(); + init_types3(); + structured_output_exports = /* @__PURE__ */ __exportAll({ + assembleStructuredOutputPipeline: () => assembleStructuredOutputPipeline, + createContentParser: () => createContentParser, + createFunctionCallingParser: () => createFunctionCallingParser + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/stream.js +function applyDelta(block, delta) { + switch (delta.type) { + case "text-delta": + if (block.type === "text") + return { + ...block, + text: (block.text ?? "") + delta.text + }; + return block; + case "reasoning-delta": + if (block.type === "thinking") + return { + ...block, + thinking: (block.thinking ?? "") + delta.reasoning + }; + if (block.type === "reasoning") + return { + ...block, + reasoning: (block.reasoning ?? "") + delta.reasoning + }; + return block; + case "data-delta": + return { + ...block, + data: (block.data ?? "") + delta.data + }; + case "block-delta": + return { + ...block, + ...delta.fields + }; + default: + throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); } - static async initialize(params) { - let { config: config2, stream: stream2 } = params; - if (stream2 !== undefined && config2.configurable?.["__pregel_stream"] !== undefined) - stream2 = createDuplexStream(stream2, config2.configurable[CONFIG_KEY_STREAM]); - const skipDoneTasks = config2.configurable ? !("checkpoint_id" in config2.configurable) : true; - const scratchpad = config2.configurable?.[CONFIG_KEY_SCRATCHPAD]; - if (config2.configurable && scratchpad) { - if (scratchpad.subgraphCounter > 0) - config2 = patchConfigurable2(config2, { [CONFIG_KEY_CHECKPOINT_NS]: [config2.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join("|") }); - scratchpad.subgraphCounter += 1; - } - const isNested = CONFIG_KEY_READ in (config2.configurable ?? {}); - if (!isNested && config2.configurable?.checkpoint_ns !== undefined && config2.configurable?.checkpoint_ns !== "") - config2 = patchConfigurable2(config2, { - checkpoint_ns: "", - checkpoint_id: undefined - }); - let checkpointConfig = config2; - if (config2.configurable?.["checkpoint_map"] !== undefined && config2.configurable?.["checkpoint_map"]?.[config2.configurable?.checkpoint_ns]) - checkpointConfig = patchConfigurable2(config2, { checkpoint_id: config2.configurable[CONFIG_KEY_CHECKPOINT_MAP][config2.configurable?.checkpoint_ns] }); - const checkpointNamespace = config2.configurable?.checkpoint_ns?.split("|") ?? []; - const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { - config: config2, - checkpoint: emptyCheckpoint(), - metadata: { - source: "input", - step: -2, - parents: {} - }, - pendingWrites: [] +} +function getEventDelta(event) { + if (event.event !== "content-block-delta") + return; + if ("delta" in event && event.delta) + return event.delta; + const content = event.content; + if (content == null || typeof content !== "object") + return; + const block = content; + if (block.type === "text" && typeof block.text === "string") + return { + type: "text-delta", + text: block.text }; - checkpointConfig = { - ...config2, - ...saved.config, - configurable: { - checkpoint_ns: "", - ...config2.configurable, - ...saved.config.configurable + if (block.type === "reasoning" && typeof block.reasoning === "string") + return { + type: "reasoning-delta", + reasoning: block.reasoning + }; + if (block.type === "thinking" && typeof block.thinking === "string") + return { + type: "reasoning-delta", + reasoning: block.thinking + }; + if (typeof block.data === "string") + return { + type: "data-delta", + data: block.data, + encoding: "base64" + }; + if (typeof block.type === "string") + return { + type: "block-delta", + fields: { + ...block, + type: block.type } }; - const prevCheckpointConfig = saved.parentConfig; - const checkpoint = copyCheckpoint(saved.checkpoint); - const checkpointMetadata = { ...saved.metadata }; - const checkpointPendingWrites = saved.pendingWrites ?? []; - const channels = emptyChannels(params.channelSpecs, checkpoint); - const step = (checkpointMetadata.step ?? 0) + 1; - const stop = step + (config2.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; - const checkpointPreviousVersions = { ...checkpoint.channel_versions }; - const store = params.store ? new AsyncBatchedStore(params.store) : undefined; - if (store) - await store.start(); - return new PregelLoop2({ - input: params.input, - config: config2, - checkpointer: params.checkpointer, - checkpoint, - checkpointMetadata, - checkpointConfig, - prevCheckpointConfig, - checkpointNamespace, - channels, - isNested, - manager: params.manager, - skipDoneTasks, - step, - stop, - checkpointPreviousVersions, - checkpointPendingWrites, - outputKeys: params.outputKeys ?? [], - streamKeys: params.streamKeys ?? [], - nodes: params.nodes, - stream: stream2, - store, - cache: params.cache, - interruptAfter: params.interruptAfter, - interruptBefore: params.interruptBefore, - durability: params.durability, - debug: params.debug, - triggerToNodes: params.triggerToNodes - }); +} +function getReasoningDelta(content) { + if (content == null || typeof content !== "object") + return; + const block = content; + if (block.type === "reasoning" && typeof block.reasoning === "string") + return block.reasoning; + if (block.type === "thinking" && typeof block.thinking === "string") + return block.thinking; +} +function isReasoningContent(content) { + if (content == null || typeof content !== "object") + return false; + const type = content.type; + return type === "reasoning" || type === "thinking"; +} +function normalizeUsage(usage) { + if (!usage) + return; + return { + ...usage, + input_tokens: usage.input_tokens ?? 0, + output_tokens: usage.output_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0 + }; +} +function parseToolArgs(value) { + if (value != null && typeof value === "object" && !Array.isArray(value)) + return value; + if (typeof value !== "string" || value.length === 0) + return {}; + try { + const parsed = JSON.parse(value); + return parsed != null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; } - _checkpointerPutAfterPrevious(input) { - this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { - return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); - }); - this._trackCheckpointerPromise(this._checkpointerChainedPromise); +} +function standardizeToolBlock(block) { + const record2 = block; + if (block.type === "tool_call") + return block; + if (block.type !== "tool_call_chunk" && block.type !== "tool_use" && block.type !== "input_json_delta") + return block; + const name = typeof record2.name === "string" ? record2.name : undefined; + if (name == null) + return block; + const args = record2.args ?? record2.input; + return { + ...record2, + type: "tool_call", + name, + args: parseToolArgs(args) + }; +} +var stream_exports2, ReplayBuffer2 = class { + events = []; + finished = false; + waiters = []; + error = null; + push(event) { + this.events.push(event); + const toWake = this.waiters.splice(0); + for (const waiter of toWake) + waiter(); } - putWrites(taskId, writes) { - let writesCopy = writes; - if (writesCopy.length === 0) - return; - if (writesCopy.every(([key]) => (key in WRITES_IDX_MAP))) - writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); - let hasUntrackedChannels = false; - for (const key in this.channels) - if (Object.prototype.hasOwnProperty.call(this.channels, key)) { - if (this.channels[key].lc_graph_name === "UntrackedValue") { - hasUntrackedChannels = true; - break; - } - } - let writesToSave = writesCopy; - if (hasUntrackedChannels) - writesToSave = writesCopy.filter(([c]) => { - const channel = this.channels[c]; - return !channel || channel.lc_graph_name !== "UntrackedValue"; - }).map(([c, v]) => { - if (c === "__pregel_tasks" && _isSend(v)) - return [c, sanitizeUntrackedValuesInSend(v, this.channels)]; - return [c, v]; - }); - this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); - for (const [c, v] of writesToSave) - this.checkpointPendingWrites.push([ - taskId, - c, - v - ]); - const config2 = patchConfigurable2(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - if (this.durability !== "exit" && this.checkpointer != null) - this._trackCheckpointerPromise(this.checkpointer.putWrites(config2, writesToSave, taskId)); - if (this.tasks) - this._outputWrites(taskId, writesCopy); - if (!writes.length || !this.cache || !this.tasks) - return; - const task = this.tasks[taskId]; - if (task == null || task.cache_key == null) - return; - if (writes[0][0] === "__error__" || writes[0][0] === "__interrupt__") - return; - this.cache.set([{ - key: [task.cache_key.ns, task.cache_key.key], - value: task.writes, - ttl: task.cache_key.ttl - }]); + finish() { + this.finished = true; + const toWake = this.waiters.splice(0); + for (const waiter of toWake) + waiter(); } - _outputWrites(taskId, writes, cached2 = false) { - const task = this.tasks[taskId]; - if (task !== undefined) { - if (task.config !== undefined && (task.config.tags ?? []).includes("langsmith:hidden")) - return; - if (writes.length > 0) { - if (writes[0][0] === "__interrupt__") { - if (task.path?.[0] === "__pregel_push" && task.path?.[task.path.length - 1] === true) - return; - const interruptWrites = writes.filter((w) => w[0] === INTERRUPT).flatMap((w) => w[1]); - this._emit([["updates", { [INTERRUPT]: interruptWrites }], ["values", { [INTERRUPT]: interruptWrites }]]); - } else if (writes[0][0] !== "__error__") - this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached2), "updates"))); - } - if (!cached2) - this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); - } + setError(err) { + this.error = err; + this.finished = true; + const toWake = this.waiters.splice(0); + for (const waiter of toWake) + waiter(); } - async _matchCachedWrites() { - if (!this.cache) - return []; - const matched = []; - const serializeKey = ([ns3, key]) => { - return `ns:${ns3.join(",")}|key:${key}`; - }; - const keys = []; - const keyMap = {}; - for (const task of Object.values(this.tasks)) - if (task.cache_key != null && !task.writes.length) { - keys.push([task.cache_key.ns, task.cache_key.key]); - keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; + async* iterate() { + if (this.finished) { + if (this.error) + throw this.error; + yield* this.events; + return; + } + let cursor = 0; + while (true) { + while (cursor < this.events.length) { + yield this.events[cursor]; + cursor++; } - if (keys.length === 0) - return []; - const cache2 = await this.cache.get(keys); - for (const { key, value } of cache2) { - const task = keyMap[serializeKey(key)]; - if (task != null) { - task.writes.push(...value); - matched.push({ - task, - result: value - }); + if (this.finished) { + if (this.error) + throw this.error; + return; } + await new Promise((resolve2) => { + if (cursor < this.events.length || this.finished) { + resolve2(); + return; + } + this.waiters.push(resolve2); + }); } - return matched; } - async tick(params) { - if (this.store && !this.store.isRunning) - await this.store?.start(); - const { inputKeys = [] } = params; - if (this.status !== "pending") - throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); - if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) - await this._first(inputKeys); - else if (this.toInterrupt.length > 0) { - this.status = "interrupt_before"; - throw new GraphInterrupt; - } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { - const writes = Object.values(this.tasks).flatMap((t) => t.writes); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); - this.checkpointPendingWrites = []; - await this._putCheckpoint({ source: "loop" }); - this._emitValuesWithCheckpointMeta(valuesOutput); - if (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { - this.status = "interrupt_after"; - throw new GraphInterrupt; - } - if (this.config.configurable?.["__pregel_resuming"] !== undefined) - delete this.config.configurable?.[CONFIG_KEY_RESUMING]; - } else - return false; - if (this.step > this.stop) { - this.status = "out_of_steps"; - return false; +}, TextContentStream, ToolCallsStream, ReasoningContentStream, UsageMetadataStream, ChatModelStream; +var init_stream2 = __esm(() => { + init_runtime2(); + init_ai(); + stream_exports2 = /* @__PURE__ */ __exportAll({ + ChatModelStream: () => ChatModelStream, + ReasoningContentStream: () => ReasoningContentStream, + TextContentStream: () => TextContentStream, + ToolCallsStream: () => ToolCallsStream, + UsageMetadataStream: () => UsageMetadataStream + }); + TextContentStream = class { + _buffer; + constructor(buffer) { + this._buffer = buffer; } - this.tasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { - step: this.step, - checkpointer: this.checkpointer, - isResuming: this.isResuming, - manager: this.manager, - store: this.store, - stream: this.stream, - triggerToNodes: this.triggerToNodes, - updatedChannels: this.updatedChannels - }); - if (this.checkpointer) - this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); - if (Object.values(this.tasks).length === 0) { - this.status = "done"; - return false; + get full() { + const buffer = this._buffer; + return { async* [Symbol.asyncIterator]() { + let accumulated = ""; + for await (const event of buffer.iterate()) { + const delta = getEventDelta(event); + if (delta?.type === "text-delta") { + accumulated += delta.text; + yield accumulated; + } + } + } }; } - if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === "__error__" || k === "__interrupt__" || k === "__resume__") - continue; - const task = Object.values(this.tasks).find((t) => t.id === tid); - if (task) - task.writes.push([k, v]); + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) { + const delta = getEventDelta(event); + if (delta?.type === "text-delta") + yield delta.text; + } } - for (const task of Object.values(this.tasks)) - if (task.writes.length > 0) - this._outputWrites(task.id, task.writes, true); - } - if (Object.values(this.tasks).every((task) => task.writes.length > 0)) - return this.tick({ inputKeys }); - if (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { - this.status = "interrupt_before"; - throw new GraphInterrupt; + return gen(); } - const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), "tasks")); - this._emit(debugOutput); - return true; - } - async finishAndHandleError(error51) { - if (this.durability === "exit" && (!this.isNested || typeof error51 !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(":")))) { - this._putCheckpoint(this.checkpointMetadata); - this._flushPendingWrites(); + then(onfulfilled, onrejected) { + return (async () => { + let text = ""; + for await (const delta of this) + text += delta; + return text; + })().then(onfulfilled, onrejected); } - const suppress = this._suppressInterrupt(error51); - if (suppress || error51 === undefined) - this.output = readChannels(this.channels, this.outputKeys); - if (suppress) { - if (this.tasks !== undefined && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - this._emitValuesWithCheckpointMeta(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); - } - if (isGraphInterrupt(error51) && !error51.interrupts.length) - this._emit([["updates", { [INTERRUPT]: [] }], ["values", { [INTERRUPT]: [] }]]); + }; + ToolCallsStream = class { + _buffer; + constructor(buffer) { + this._buffer = buffer; } - return suppress; - } - async acceptPush(task, writeIdx, call2) { - if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { - this.toInterrupt.push(task); - return; - } - const pushed = _prepareSingleTask([ - PUSH, - task.path ?? [], - writeIdx, - task.id, - call2 - ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { - step: this.step, - checkpointer: this.checkpointer, - manager: this.manager, - store: this.store, - stream: this.stream - }); - if (!pushed) - return; - if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { - this.toInterrupt.push(pushed); - return; + get full() { + const buffer = this._buffer; + return { async* [Symbol.asyncIterator]() { + const calls = []; + for await (const event of buffer.iterate()) + if (event.event === "content-block-finish" && event.content.type === "tool_call") { + calls.push(event.content); + yield [...calls]; + } + } }; } - this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); - if (this.debug) - printStepTasks(this.step, [pushed]); - this.tasks[pushed.id] = pushed; - if (this.skipDoneTasks) - this._matchWrites({ [pushed.id]: pushed }); - const tasks = await this._matchCachedWrites(); - for (const { task: task2 } of tasks) - this._outputWrites(task2.id, task2.writes, true); - return pushed; - } - _suppressInterrupt(e) { - return isGraphInterrupt(e) && !this.isNested; - } - async _first(inputKeys) { - const { configurable } = this.config; - const scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD]; - if (scratchpad && scratchpad.nullResume !== undefined) - this.putWrites(NULL_TASK_ID, [[RESUME, scratchpad.nullResume]]); - if (isCommand(this.input)) { - const hasResume = this.input.resume != null; - if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { - this.config.configurable ??= {}; - this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; - } - if (hasResume && this.checkpointer == null) - throw new Error("Cannot use Command(resume=...) without checkpointer"); - const writes = {}; - for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { - writes[tid] ??= []; - writes[tid].push([key, value]); + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) + if (event.event === "content-block-finish" && event.content.type === "tool_call") + yield event.content; } - if (Object.keys(writes).length === 0) - throw new EmptyInputError("Received empty Command input"); - for (const [tid, ws] of Object.entries(writes)) - this.putWrites(tid, ws); + return gen(); } - const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites(this.checkpoint, this.channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], this.checkpointerGetNextVersion, this.triggerToNodes); - const isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0; - if (this.isResuming || isCommandUpdateOrGoto) { - for (const channelName in this.channels) { - if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) - continue; - if (this.checkpoint.channel_versions[channelName] !== undefined) { - const version4 = this.checkpoint.channel_versions[channelName]; - this.checkpoint.versions_seen[INTERRUPT] = { - ...this.checkpoint.versions_seen[INTERRUPT], - [channelName]: version4 - }; - } - } - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); - if (this.isResuming) - this.input = INPUT_RESUMING; - else if (isCommandUpdateOrGoto) { - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; + then(onfulfilled, onrejected) { + return (async () => { + const calls = []; + for await (const call of this) + calls.push(call); + return calls; + })().then(onfulfilled, onrejected); + } + }; + ReasoningContentStream = class { + _buffer; + constructor(buffer) { + this._buffer = buffer; + } + get full() { + const buffer = this._buffer; + return { async* [Symbol.asyncIterator]() { + let accumulated = ""; + let seenReasoning = false; + for await (const event of buffer.iterate()) + if (event.event === "content-block-start") { + if (!isReasoningContent(event.content)) { + if (seenReasoning) + return; + continue; + } + seenReasoning = true; + const delta = getReasoningDelta(event.content); + if (delta == null || delta.length === 0) + continue; + accumulated += delta; + yield accumulated; + } else if (event.event === "content-block-delta") { + const eventDelta = getEventDelta(event); + if (eventDelta?.type !== "reasoning-delta") + continue; + seenReasoning = true; + const delta = eventDelta.reasoning; + if (delta == null || delta.length === 0) + continue; + accumulated += delta; + yield accumulated; + } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) + return; + else if (event.event === "message-finish") + return; + } }; + } + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + let seenReasoning = false; + for await (const event of buffer.iterate()) + if (event.event === "content-block-start") { + if (!isReasoningContent(event.content)) { + if (seenReasoning) + return; + continue; + } + seenReasoning = true; + const delta = getReasoningDelta(event.content); + if (delta != null && delta.length > 0) + yield delta; + } else if (event.event === "content-block-delta") { + const eventDelta = getEventDelta(event); + if (eventDelta?.type !== "reasoning-delta") + continue; + seenReasoning = true; + const delta = eventDelta.reasoning; + if (delta != null && delta.length > 0) + yield delta; + } else if (event.event === "content-block-finish" && isReasoningContent(event.content)) + return; + else if (event.event === "message-finish") + return; } - this._emitValuesWithCheckpointMeta(valuesOutput); - } else { - const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); - if (inputWrites.length > 0) { - const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ - name: INPUT, - writes: inputWrites, - triggers: [] - }]), this.checkpointerGetNextVersion, this.triggerToNodes); - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; - } else if (!("__pregel_resuming" in (this.config.configurable ?? {}))) - throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); - else - this.input = INPUT_DONE; + return gen(); } - if (!this.isNested) - this.config = patchConfigurable2(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming }); - } - _emit(values) { - for (const entry of values) { - const [mode, payload, meta3] = entry; - if (this.stream.modes.has(mode)) - this.stream.push([ - this.checkpointNamespace, - mode, - payload, - meta3 - ]); - if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { - const step = mode === "checkpoints" ? this.step - 1 : this.step; - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const type = (() => { - if (mode === "checkpoints") - return "checkpoint"; - else if (typeof payload === "object" && payload != null && "result" in payload) - return "task_result"; - else - return "task"; - })(); - this.stream.push([ - this.checkpointNamespace, - "debug", - { - step, - type, - timestamp, - payload + then(onfulfilled, onrejected) { + return (async () => { + let text = ""; + for await (const delta of this) + text += delta; + return text; + })().then(onfulfilled, onrejected); + } + }; + UsageMetadataStream = class { + _buffer; + constructor(buffer) { + this._buffer = buffer; + } + [Symbol.asyncIterator]() { + const buffer = this._buffer; + async function* gen() { + for await (const event of buffer.iterate()) + if (event.event === "usage") { + const usage = normalizeUsage(event.usage); + if (usage) + yield usage; + } else if (event.event === "message-start" && event.usage) { + const usage = normalizeUsage(event.usage); + if (usage) + yield usage; + } else if (event.event === "message-finish" && event.usage) { + const usage = normalizeUsage(event.usage); + if (usage) + yield usage; } - ]); } + return gen(); } - } - _currentCheckpointMeta() { - if (!this.checkpointMetadata || !this.checkpoint?.id) - return; - const parent_id = this.prevCheckpointConfig?.configurable?.checkpoint_id; - return { checkpoint: { - id: this.checkpoint.id, - ...parent_id ? { parent_id } : {}, - step: this.checkpointMetadata.step, - source: this.checkpointMetadata.source - } }; - } - _emitValuesWithCheckpointMeta(entries) { - const meta3 = this._currentCheckpointMeta(); - if (!meta3) { - this._emit(entries); - return; + then(onfulfilled, onrejected) { + return (async () => { + let latest; + for await (const usage of this) + latest = usage; + return latest; + })().then(onfulfilled, onrejected); } - this._emit(entries.map(([mode, payload]) => mode === "values" ? [ - mode, - payload, - meta3 - ] : [mode, payload])); - } - _putCheckpoint(inputMetadata) { - const exiting = this.checkpointMetadata === inputMetadata; - const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); - const storeCheckpoint = (checkpoint) => { - this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : undefined; - this.checkpointConfig = patchConfigurable2(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); - const channelVersions = { ...this.checkpoint.channel_versions }; - const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); - this.checkpointPreviousVersions = channelVersions; - this._checkpointerPutAfterPrevious({ - config: { ...this.checkpointConfig }, - checkpoint: copyCheckpoint(checkpoint), - metadata: { ...this.checkpointMetadata }, - newVersions - }); - this.checkpointConfig = { - ...this.checkpointConfig, - configurable: { - ...this.checkpointConfig.configurable, - checkpoint_id: this.checkpoint.id - } - }; - }; - if (!exiting) - this.checkpointMetadata = { - ...inputMetadata, - step: this.step, - parents: this.config.configurable?.["checkpoint_map"] ?? {} - }; - this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : undefined, this.step, exiting ? { id: this.checkpoint.id } : undefined); - if (doCheckpoint) - storeCheckpoint(this.checkpoint); - if (!exiting) - this.step += 1; - } - _flushPendingWrites() { - if (this.checkpointer == null) - return; - if (this.checkpointPendingWrites.length === 0) - return; - const config2 = patchConfigurable2(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - const byTask = {}; - for (const [tid, key, value] of this.checkpointPendingWrites) { - byTask[tid] ??= []; - byTask[tid].push([key, value]); + }; + ChatModelStream = class { + _buffer; + constructor(source) { + this._buffer = new ReplayBuffer2; + this._consume(source); } - for (const [tid, ws] of Object.entries(byTask)) - this._trackCheckpointerPromise(this.checkpointer.putWrites(config2, ws, tid)); - } - _matchWrites(tasks) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === "__error__" || k === "__interrupt__" || k === "__resume__") - continue; - const task = Object.values(tasks).find((t) => t.id === tid); - if (task) - task.writes.push([k, v]); + async _consume(source) { + try { + for await (const event of source) + this._buffer.push(event); + this._buffer.finish(); + } catch (err) { + this._buffer.setError(err instanceof Error ? err : new Error(String(err))); + } } - for (const task of Object.values(tasks)) - if (task.writes.length > 0) - this._outputWrites(task.id, task.writes, true); - } -}; -var init_loop = __esm(() => { - init_constants3(); - init_errors5(); - init_base15(); - init_utils8(); - init_hash3(); - init_io(); - init_utils9(); - init_algo(); - init_debug(); - init_stream5(); - init_dist3(); - INPUT_DONE = Symbol.for("INPUT_DONE"); - INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); - AsyncBatchedCache = class extends BaseCache2 { - cache; - queue = Promise.resolve(); - constructor(cache2) { - super(); - this.cache = cache2; + [Symbol.asyncIterator]() { + return this._buffer.iterate(); } - async get(keys) { - return this.enqueueOperation("get", keys); + get text() { + return new TextContentStream(this._buffer); } - async set(pairs) { - return this.enqueueOperation("set", pairs); + get toolCalls() { + return new ToolCallsStream(this._buffer); } - async clear(namespaces) { - return this.enqueueOperation("clear", namespaces); + get reasoning() { + return new ReasoningContentStream(this._buffer); } - async stop() { - await this.queue; + get usage() { + return new UsageMetadataStream(this._buffer); } - enqueueOperation(type, ...args) { - const newPromise = this.queue.then(() => { - return this.cache[type](...args); - }); - this.queue = newPromise.then(() => { - return; - }, () => { - return; + get output() { + return this._assembleMessage(); + } + then(onfulfilled, onrejected) { + return this._assembleMessage().then(onfulfilled, onrejected); + } + async _assembleMessage() { + const contentBlocks = []; + let id; + let usage; + let metadata = {}; + let finishReason; + for await (const event of this._buffer.iterate()) + switch (event.event) { + case "message-start": + id = event.id ?? id; + if (event.usage) + usage = normalizeUsage(event.usage); + break; + case "content-block-start": + contentBlocks[event.index] = event.content; + break; + case "content-block-delta": { + const current = contentBlocks[event.index]; + const delta = getEventDelta(event); + if (current) { + if (delta) + contentBlocks[event.index] = applyDelta(current, delta); + } + break; + } + case "content-block-finish": + contentBlocks[event.index] = event.content; + break; + case "usage": + usage = normalizeUsage(event.usage); + break; + case "message-finish": + finishReason = event.reason; + if (event.usage) + usage = normalizeUsage(event.usage); + if (event.responseMetadata) + metadata = { + ...metadata, + ...event.responseMetadata + }; + break; + default: + break; + } + const filteredBlocks = contentBlocks.filter((b) => b != null).map(standardizeToolBlock); + return new AIMessage({ + id, + content: filteredBlocks, + usage_metadata: usage, + response_metadata: { + ...metadata, + ...finishReason ? { finish_reason: finishReason } : {}, + output_version: "v1" + } }); - return newPromise; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/messages.js -function isChatGenerationChunk2(x) { - return isBaseMessage(x?.message); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/compat.js +function nextBlockIndex(activeBlocks) { + let next = 0; + for (const index of activeBlocks.keys()) + if (index >= next) + next = index + 1; + return next; } -function normalizeStreamMetadata(metadata, tags, name) { - if (!metadata) +function getAdditionalKwargs(message) { + const additional = message.additional_kwargs; + return additional != null && typeof additional === "object" ? additional : {}; +} +function extractImageBlocksFromToolOutputs(message) { + const toolOutputs = getAdditionalKwargs(message).tool_outputs; + if (!Array.isArray(toolOutputs)) + return []; + const blocks2 = []; + for (const entry of toolOutputs) { + if (entry == null || typeof entry !== "object") + continue; + const record2 = entry; + if (record2.type !== "image_generation_call") + continue; + const data = typeof record2.result === "string" ? record2.result : undefined; + const url2 = typeof record2.url === "string" ? record2.url : undefined; + if (data == null && url2 == null) + continue; + const outputFormat = typeof record2.output_format === "string" ? record2.output_format.toLowerCase() : undefined; + const mimeType = (outputFormat != null ? MIME_TYPE_BY_IMAGE_FORMAT[outputFormat] : undefined) ?? "image/png"; + blocks2.push({ + type: "image", + ...typeof record2.id === "string" ? { id: record2.id } : {}, + ...url2 != null ? { url: url2 } : {}, + ...data != null ? { data } : {}, + mimeType + }); + } + return blocks2; +} +function getAudioPayload(message) { + const audio = getAdditionalKwargs(message).audio; + if (audio == null || typeof audio !== "object") return; - const streamNamespace = metadata.langgraph_checkpoint_ns; - const checkpointNs = metadata.checkpoint_ns; - const namespace = streamNamespace ?? checkpointNs; - if (!namespace) + const record2 = audio; + const data = typeof record2.data === "string" ? record2.data : undefined; + const url2 = typeof record2.url === "string" ? record2.url : undefined; + const transcript = typeof record2.transcript === "string" ? record2.transcript : undefined; + if (data == null && url2 == null && transcript == null) return; - return [namespace.split("|"), { - tags, - name, - ...metadata - }]; + const explicitMimeType = typeof record2.mime_type === "string" ? record2.mime_type : typeof record2.mimeType === "string" ? record2.mimeType : undefined; + const format3 = typeof record2.format === "string" ? record2.format.toLowerCase() : undefined; + const mimeType = explicitMimeType ?? (format3 != null ? MIME_TYPE_BY_AUDIO_FORMAT[format3] : undefined) ?? (data != null ? "audio/wav" : "audio/pcm"); + return { + ...typeof record2.id === "string" ? { id: record2.id } : {}, + ...data != null ? { data } : {}, + ...url2 != null ? { url: url2 } : {}, + ...transcript != null ? { transcript } : {}, + mimeType + }; } -var StreamMessagesHandler; -var init_messages3 = __esm(() => { - init_constants3(); - init_base2(); - init_messages(); - StreamMessagesHandler = class extends BaseCallbackHandler { - name = "StreamMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - emittedChatModelRunIds = {}; - stableMessageIdMap = {}; - lc_prefer_streaming = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; +async function* convertChunksToEvents(chunks, options) { + const activeBlocks = /* @__PURE__ */ new Map; + let messageStarted = false; + let lastUsage; + let audioStream; + const emittedImageKeys = /* @__PURE__ */ new Set; + for await (const chunk of chunks) { + options?.signal?.throwIfAborted(); + const msg = chunk.message; + let usageHandledInStart = false; + if (!messageStarted) { + messageStarted = true; + const startEvent = { + event: "message-start", + id: msg.id ?? undefined + }; + if (AIMessageChunk.isInstance(msg) && msg.usage_metadata) { + startEvent.usage = msg.usage_metadata; + lastUsage = { ...msg.usage_metadata }; + usageHandledInStart = true; + } + yield startEvent; } - _emit(meta3, message, runId, dedupe = false) { - if (dedupe && message.id !== undefined && this.seen[message.id] !== undefined) - return; - let messageId = message.id; - if (runId != null) - if (isToolMessage(message)) - messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) - messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; + const content = msg.content; + if (typeof content === "string") { + if (content !== "") { + const blockIndex = 0; + if (!activeBlocks.has(blockIndex)) { + const initial = { + type: "text", + text: "" + }; + activeBlocks.set(blockIndex, { + type: "text", + accumulated: initial + }); + yield { + event: "content-block-start", + index: blockIndex, + content: initial + }; } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; + const block = activeBlocks.get(blockIndex); + block.accumulated = { + ...block.accumulated, + text: (block.accumulated.text ?? "") + content + }; + yield { + event: "content-block-delta", + index: blockIndex, + delta: { + type: "text-delta", + text: content + } + }; } - if (message.id != null) - this.seen[message.id] = message; - this.streamFn([ - meta3[0], - "messages", - [message, meta3[1]] - ]); - } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) - this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); - } - handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { - const chunk = fields?.chunk; - this.emittedChatModelRunIds[runId] = true; - if (this.metadatas[runId] !== undefined) - if (isChatGenerationChunk2(chunk)) - this._emit(this.metadatas[runId], chunk.message, runId); - else - this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); - } - handleLLMEnd(output, runId) { - if (this.metadatas[runId] === undefined) - return; - if (!this.emittedChatModelRunIds[runId]) { - const chatGeneration = output.generations?.[0]?.[0]; - if (isBaseMessage(chatGeneration?.message)) - this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); - delete this.emittedChatModelRunIds[runId]; + } else if (Array.isArray(content)) + for (const part of content) { + const blockIndex = typeof part.index === "number" ? part.index : activeBlocks.size; + if (!activeBlocks.has(blockIndex)) { + activeBlocks.set(blockIndex, { + type: part.type, + accumulated: { ...part } + }); + yield { + event: "content-block-start", + index: blockIndex, + content: { ...part } + }; + } else { + const block = activeBlocks.get(blockIndex); + const delta = contentBlockToDelta(part); + block.accumulated = applyDeltaToBlock(block.accumulated, delta); + yield { + event: "content-block-delta", + index: blockIndex, + delta + }; + } } - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; - } - handleLLMError(_err, runId) { - delete this.metadatas[runId]; - } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { - this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) - if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) - this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) - if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) - this.seen[item.id] = item; - } + if (AIMessageChunk.isInstance(msg) && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) + for (const toolChunk of msg.tool_call_chunks) { + const blockIndex = typeof toolChunk.index === "number" ? toolChunk.index : activeBlocks.size; + if (!activeBlocks.has(blockIndex)) { + const initial = { + type: "tool_call_chunk", + id: toolChunk.id, + name: toolChunk.name, + args: "", + index: blockIndex + }; + activeBlocks.set(blockIndex, { + type: "tool_call_chunk", + accumulated: initial + }); + yield { + event: "content-block-start", + index: blockIndex, + content: initial + }; } + const acc = activeBlocks.get(blockIndex).accumulated; + if (toolChunk.id != null) + acc.id = toolChunk.id; + if (toolChunk.name != null) + acc.name = toolChunk.name; + acc.args = (acc.args ?? "") + (toolChunk.args ?? ""); + yield { + event: "content-block-delta", + index: blockIndex, + delta: { + type: "block-delta", + fields: { + type: "tool_call_chunk", + ..."id" in acc && acc.id != null ? { id: acc.id } : {}, + ..."name" in acc && acc.name != null ? { name: acc.name } : {}, + args: acc.args + } + } + }; } - } - handleChainEnd(outputs, runId) { - const metadata = this.metadatas[runId]; - delete this.metadatas[runId]; - if (metadata !== undefined) { - if (isBaseMessage(outputs)) - this._emit(metadata, outputs, runId, true); - else if (Array.isArray(outputs)) { - for (const value of outputs) - if (isBaseMessage(value)) - this._emit(metadata, value, runId, true); - } else if (outputs != null && typeof outputs === "object") { - for (const value of Object.values(outputs)) - if (isBaseMessage(value)) - this._emit(metadata, value, runId, true); - else if (Array.isArray(value)) { - for (const item of value) - if (isBaseMessage(item)) - this._emit(metadata, item, runId, true); + const audioPayload = getAudioPayload(msg); + if (audioPayload != null) { + if (audioStream == null) { + const index = nextBlockIndex(activeBlocks); + audioStream = { + index, + id: audioPayload.id, + mimeType: audioPayload.mimeType, + transcript: "" + }; + const initial = { + type: "audio", + ...audioPayload.id != null ? { id: audioPayload.id } : {}, + ...audioPayload.url != null ? { url: audioPayload.url } : {}, + data: "", + mimeType: audioPayload.mimeType + }; + activeBlocks.set(index, { + type: "audio", + accumulated: initial + }); + yield { + event: "content-block-start", + index, + content: initial + }; + } + const activeAudio = activeBlocks.get(audioStream.index); + if (activeAudio != null) { + const accumulated = activeAudio.accumulated; + if (audioPayload.id != null && audioStream.id == null) { + audioStream.id = audioPayload.id; + accumulated.id = audioPayload.id; + } + if (audioPayload.transcript != null) { + audioStream.transcript += audioPayload.transcript; + accumulated.transcript = audioStream.transcript; + yield { + event: "content-block-delta", + index: audioStream.index, + delta: { + type: "block-delta", + fields: { + type: "audio", + transcript: audioStream.transcript + } + } + }; + } + if (audioPayload.data != null && audioPayload.data.length > 0) { + accumulated.data = (accumulated.data ?? "") + audioPayload.data; + yield { + event: "content-block-delta", + index: audioStream.index, + delta: { + type: "data-delta", + data: audioPayload.data, + encoding: "base64" } + }; } } } - handleChainError(_err, runId) { - delete this.metadatas[runId]; + for (const imageBlock of extractImageBlocksFromToolOutputs(msg)) { + const imageRecord = imageBlock; + const imageKey = imageRecord.id ?? imageRecord.url ?? (imageRecord.data != null ? `${imageRecord.data.length}:${imageRecord.data.slice(0, 32)}` : undefined); + if (imageKey != null && emittedImageKeys.has(imageKey)) + continue; + if (imageKey != null) + emittedImageKeys.add(imageKey); + const index = nextBlockIndex(activeBlocks); + activeBlocks.set(index, { + type: "image", + accumulated: imageBlock + }); + yield { + event: "content-block-start", + index, + content: imageBlock + }; + } + if (!usageHandledInStart && AIMessageChunk.isInstance(msg) && msg.usage_metadata) { + const chunkUsage = msg.usage_metadata; + if (!lastUsage) + lastUsage = { ...chunkUsage }; + else + lastUsage = { + input_tokens: lastUsage.input_tokens + chunkUsage.input_tokens, + output_tokens: lastUsage.output_tokens + chunkUsage.output_tokens, + total_tokens: lastUsage.total_tokens + chunkUsage.total_tokens + }; + yield { + event: "usage", + usage: { ...lastUsage } + }; } + } + for (const [index, block] of activeBlocks) + yield { + event: "content-block-finish", + index, + content: finalizeContentBlock(block.accumulated) + }; + yield { + event: "message-finish", + reason: "stop", + ...lastUsage ? { usage: lastUsage } : {} }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/messages-v2.js -function getResponseMetadata(message) { - if ("response_metadata" in message && typeof message.response_metadata === "object" && message.response_metadata != null) - return message.response_metadata; -} -function getUsageMetadata(message) { - if ("usage_metadata" in message && typeof message.usage_metadata === "object" && message.usage_metadata != null) - return message.usage_metadata; } -function startBlockFor(block) { - switch (block.type) { - case "text": - return { - type: "text", - text: "" - }; - case "reasoning": +function applyDeltaToBlock(block, delta) { + switch (delta.type) { + case "text-delta": + if (block.type === "text") + return { + ...block, + text: (block.text ?? "") + delta.text + }; + return block; + case "reasoning-delta": + if (block.type === "thinking") + return { + ...block, + thinking: (block.thinking ?? "") + delta.reasoning + }; + if (block.type === "reasoning") + return { + ...block, + reasoning: (block.reasoning ?? "") + delta.reasoning + }; + return block; + case "data-delta": return { - type: "reasoning", - reasoning: "" + ...block, + data: (block.data ?? "") + delta.data }; - case "tool_call": - case "tool_call_chunk": + case "block-delta": return { - type: "tool_call_chunk", - ...block.id != null ? { id: block.id } : {}, - ...block.name != null ? { name: block.name } : {}, - args: "" + ...block, + ...delta.fields }; default: - return block; + throw new Error(`Unknown delta type: ${JSON.stringify(delta)}`); } } -function deltaFor(block) { - switch (block.type) { - case "text": { - const text = typeof block.text === "string" ? block.text : ""; - return text.length > 0 ? { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "text-delta", - text - } - } : undefined; - } - case "reasoning": { - const reasoning = typeof block.reasoning === "string" ? block.reasoning : ""; - return reasoning.length > 0 ? { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "reasoning-delta", - reasoning - } - } : undefined; - } - case "tool_call_chunk": +function contentBlockToDelta(block) { + if (block.type === "text") + return { + type: "text-delta", + text: block.text + }; + if (block.type === "reasoning") + return { + type: "reasoning-delta", + reasoning: block.reasoning + }; + if (block.type === "thinking" && typeof block.thinking === "string") + return { + type: "reasoning-delta", + reasoning: block.thinking + }; + if (typeof block.data === "string") + return { + type: "data-delta", + data: block.data, + encoding: "base64" + }; + if (typeof block.type === "string") + return { + type: "block-delta", + fields: { ...block } + }; + throw new Error(`Unsupported content block delta: ${JSON.stringify(block)}`); +} +function finalizeContentBlock(block) { + if (block.type === "tool_call_chunk") { + const chunk = block; + let parsedArgs; + try { + parsedArgs = JSON.parse(chunk.args ?? "{}"); + } catch { return { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "block-delta", - fields: { - ...block, - type: "tool_call_chunk" - } - } + type: "invalid_tool_call", + id: chunk.id, + name: chunk.name, + args: chunk.args, + error: "Failed to parse tool call arguments as JSON" }; - default: - return; + } + return { + type: "tool_call", + id: chunk.id, + name: chunk.name, + args: parsedArgs + }; } + return block; } -var StreamProtocolMessagesHandler; -var init_messages_v2 = __esm(() => { - init_constants3(); - init_base2(); - init_messages(); - StreamProtocolMessagesHandler = class extends BaseCallbackHandler { - name = "StreamProtocolMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - streamedRunIds = /* @__PURE__ */ new Set; - stableMessageIdMap = {}; - lc_prefer_chat_model_stream_events = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; - } - normalizeMessageId(message, runId) { - let messageId = message.id; - if (runId != null) - if (isToolMessage(message)) - messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) - messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; - } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; - } - if (message.id != null) - this.seen[message.id] = message; - return message.id; - } - emit(meta3, data, runId) { - const metadata = runId != null ? { - ...meta3[1], - run_id: runId - } : meta3[1]; - this.streamFn([ - meta3[0], - "messages", - [data, metadata] - ]); +var compat_exports, MIME_TYPE_BY_AUDIO_FORMAT, MIME_TYPE_BY_IMAGE_FORMAT; +var init_compat2 = __esm(() => { + init_runtime2(); + init_ai(); + compat_exports = /* @__PURE__ */ __exportAll({ + convertChunksToEvents: () => convertChunksToEvents, + finalizeContentBlock: () => finalizeContentBlock + }); + MIME_TYPE_BY_AUDIO_FORMAT = { + wav: "audio/wav", + mp3: "audio/mpeg", + flac: "audio/flac", + opus: "audio/opus", + aac: "audio/aac", + pcm16: "audio/pcm" + }; + MIME_TYPE_BY_IMAGE_FORMAT = { + png: "image/png", + jpeg: "image/jpeg", + jpg: "image/jpeg", + webp: "image/webp", + gif: "image/gif" + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/chat_models.js +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) + for (let idx = 0;idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) + messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1) + ] + }); + } + } + messagesToTrace.push(messageToTrace); + } + return messagesToTrace; +} +var chat_models_exports, BaseChatModel, SimpleChatModel; +var init_chat_models = __esm(() => { + init_runtime2(); + init_errors3(); + init_data(); + init_base(); + init_ai(); + init_utils3(); + init_env(); + init_base2(); + init_manager(); + init_stream(); + init_outputs(); + init_zod2(); + init_standard_schema(); + init_json_schema3(); + init_base4(); + init_messages(); + init_base5(); + init_utils5(); + init_structured_output(); + init_stream2(); + init_compat2(); + chat_models_exports = /* @__PURE__ */ __exportAll({ + BaseChatModel: () => BaseChatModel, + SimpleChatModel: () => SimpleChatModel + }); + BaseChatModel = class BaseChatModel2 extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "chat_models", + this._llmType() + ]; + disableStreaming = false; + outputVersion; + get callKeys() { + return [...super.callKeys, "outputVersion"]; } - emitFinalMessage(meta3, message, runId, dedupe = false) { - const existingId = message.id ?? (runId != null ? this.stableMessageIdMap[runId] : undefined); - if (dedupe && existingId != null && this.seen[existingId] !== undefined) - return; - const messageId = this.normalizeMessageId(message, runId); - const role = message.type === "human" ? "human" : message.type === "system" ? "system" : message.type === "tool" ? "tool" : "ai"; - const toolCallId = role === "tool" && isToolMessage(message) ? message.tool_call_id : undefined; - this.emit(meta3, { - event: "message-start", - ...messageId != null ? { id: messageId } : {}, - ...role !== "ai" ? { role } : {}, - ...typeof toolCallId === "string" ? { tool_call_id: toolCallId } : {} - }, runId); - (Array.isArray(message.content) ? message.content : typeof message.content === "string" && message.content.length > 0 ? [{ - type: "text", - text: message.content - }] : []).forEach((block, offset) => { - const index2 = typeof block.index === "number" ? block.index : offset; - this.emit(meta3, { - event: "content-block-start", - index: index2, - content: startBlockFor(block) - }, runId); - const delta = deltaFor({ - ...block, - index: index2 - }); - if (delta != null) - this.emit(meta3, delta, runId); - this.emit(meta3, { - event: "content-block-finish", - index: index2, - content: block - }, runId); + constructor(fields) { + super(fields); + this.outputVersion = iife3(() => { + const outputVersion = fields.outputVersion ?? getEnvironmentVariable("LC_OUTPUT_VERSION"); + if (outputVersion && ["v0", "v1"].includes(outputVersion)) + return outputVersion; + return "v0"; }); - this.emit(meta3, { - event: "message-finish", - ...getUsageMetadata(message) != null ? { usage: getUsageMetadata(message) } : {}, - ...getResponseMetadata(message) != null ? { responseMetadata: getResponseMetadata(message) } : {} - }, runId); } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; } - handleLLMNewToken() {} - handleChatModelStreamEvent(event, runId) { - const meta3 = this.metadatas[runId]; - if (meta3 === undefined) - return; - let forwarded = event; - if (event.event === "message-start") { - this.streamedRunIds.add(runId); - const id = event.id ?? `run-${runId}`; - this.seen[id] = true; - this.stableMessageIdMap[runId] ??= id; - if (event.id == null) - forwarded = { - ...event, - id - }; - } - this.emit(meta3, forwarded, runId); + async invoke(input, options) { + const promptValue = BaseChatModel2._convertInputToPromptValue(input); + return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].message; } - handleLLMEnd(output, runId) { - const meta3 = this.metadatas[runId]; - if (meta3 === undefined) - return; - const chatGeneration = output.generations?.[0]?.[0]; - const message = isBaseMessage(chatGeneration?.message) ? chatGeneration.message : undefined; - if (message != null) - if (this.streamedRunIds.has(runId)) { - const messageId = this.normalizeMessageId(message, runId); - if (messageId != null) - this.seen[messageId] = message; - } else - this.emitFinalMessage(meta3, message, runId, true); - this.streamedRunIds.delete(runId); - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + async* _streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); } - handleLLMError(_err, runId) { - this.streamedRunIds.delete(runId); - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + async* _streamChatModelEvents(messages, options, runManager) { + yield* convertChunksToEvents(this._streamResponseChunks(messages, options, runManager), { signal: options.signal }); } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) - if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) - this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) - if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) - this.seen[item.id] = item; + streamV2(input, options) { + const messages = BaseChatModel2._convertInputToPromptValue(input).toChatMessages(); + const [, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + return new ChatModelStream(this._streamChatModelEvents(messages, callOptions)); + } + async* _streamIterator(input, options) { + if (this._streamResponseChunks === BaseChatModel2.prototype._streamResponseChunks || this.disableStreaming) + yield this.invoke(input, options); + else { + const messages = BaseChatModel2._convertInputToPromptValue(input).toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParamsWithDefaults(callOptions) + }; + const invocationParams = this.invocationParams(callOptions); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: callOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const outputVersion = callOptions.outputVersion ?? this.outputVersion; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); + let generationChunk; + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + callOptions.signal?.throwIfAborted(); + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + if (outputVersion === "v1") + yield castStandardMessageContent(chunk.message); + else + yield chunk.message; + if (!generationChunk) + generationChunk = chunk; + else + generationChunk = generationChunk.concat(chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== undefined) + llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + callOptions.signal?.throwIfAborted(); + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generationChunk]], + llmOutput + }))); } } - handleChainEnd(outputs, runId) { - const meta3 = this.metadatas[runId]; - delete this.metadatas[runId]; - if (meta3 === undefined) - return; - const emitMessage = (value) => { - if (isBaseMessage(value)) - this.emitFinalMessage(meta3, value, runId, true); + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName }; - if (isBaseMessage(outputs)) - emitMessage(outputs); - else if (Array.isArray(outputs)) - for (const value of outputs) - emitMessage(value); - else if (outputs != null && typeof outputs === "object") - for (const value of Object.values(outputs)) - if (Array.isArray(value)) - for (const item of value) - emitMessage(item); - else - emitMessage(value); - delete this.stableMessageIdMap[runId]; } - handleChainError(_err, runId) { - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + getLsParamsWithDefaults(options) { + return { + ...this.getLsParams(options), + ls_integration: "langchain_chat_model" + }; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/retry.js -async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { - const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; - let interval = resolvedRetryPolicy !== undefined ? resolvedRetryPolicy.initialInterval ?? 500 : 0; - let attempts = 0; - let error51; - let result; - let config2 = pregelTask.config ?? {}; - if (configurable) - config2 = patchConfigurable2(config2, configurable); - config2 = { - ...config2, - signal - }; - const firstAttemptTime = Date.now(); - if (config2.executionInfo != null) - config2.executionInfo = { - ...config2.executionInfo, - nodeFirstAttemptTime: firstAttemptTime - }; - while (true) { - if (signal?.aborted) - break; - pregelTask.writes.splice(0, pregelTask.writes.length); - error51 = undefined; - try { - result = await pregelTask.proc.invoke(pregelTask.input, config2); - break; - } catch (e) { - error51 = e; - error51.pregelTaskId = pregelTask.id; - if (isParentCommand(error51)) { - const ns3 = config2?.configurable?.checkpoint_ns; - const cmd = error51.command; - if (cmd.graph === ns3) { - for (const writer of pregelTask.writers) - await writer.invoke(cmd, config2); - error51 = undefined; - break; - } else if (cmd.graph === Command.PARENT) { - const parentNs = getParentCheckpointNamespace(ns3); - error51.command = new Command({ - ...error51.command, - graph: parentNs - }); - } - } - if (isGraphBubbleUp(error51)) - break; - if (resolvedRetryPolicy === undefined) - break; - attempts += 1; - if (attempts >= (resolvedRetryPolicy.maxAttempts ?? 3)) - break; - if (!(resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER)(error51)) - break; - interval = Math.min(resolvedRetryPolicy.maxInterval ?? 128000, interval * (resolvedRetryPolicy.backoffFactor ?? 2)); - const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1000) : interval; - await new Promise((resolve2) => setTimeout(resolve2, intervalWithJitter)); - const errorName = error51.name ?? error51.constructor.unminifiable_name ?? error51.constructor.name; - if (resolvedRetryPolicy?.logWarning ?? true) - console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error51}`); - config2 = patchConfigurable2(config2, { [CONFIG_KEY_RESUMING]: true }); - if (config2.executionInfo != null) - config2.executionInfo = { - ...config2.executionInfo, - nodeAttempt: attempts + 1, - nodeFirstAttemptTime: firstAttemptTime + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== undefined && startedRunManagers.length === baseMessages.length) + runManagers = startedRunManagers; + else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParamsWithDefaults(parsedOptions) }; - } - } - return { - task: pregelTask, - result, - error: error51, - signalAborted: signal?.aborted - }; -} -var DEFAULT_STATUS_NO_RETRY, DEFAULT_RETRY_ON_HANDLER = (error51) => { - if (error51.message.startsWith("Cancel") || error51.message.startsWith("AbortError") || error51.name === "AbortError") - return false; - if (error51.name === "GraphValueError") - return false; - if (error51?.code === "ECONNABORTED") - return false; - const status = error51?.response?.status ?? error51?.status; - if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) - return false; - if (error51?.error?.code === "insufficient_quota") - return false; - return true; -}; -var init_retry = __esm(() => { - init_constants3(); - init_errors5(); - init_config2(); - init_utils9(); - DEFAULT_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 - ]; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/runner.js -function createPromiseBarrier() { - const barrier = { - next: () => { - return; - }, - wait: Promise.resolve(PROMISE_ADDED_SYMBOL) - }; - function waitHandler(resolve2) { - barrier.next = () => { - barrier.wait = new Promise(waitHandler); - resolve2(PROMISE_ADDED_SYMBOL); - }; - } - barrier.wait = new Promise(waitHandler); - return barrier; -} -async function call2(runner, task, func, name, input, options = {}) { - const scratchpad = task.config?.configurable?.[CONFIG_KEY_SCRATCHPAD]; - if (!scratchpad) - throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); - const cnt = scratchpad.callCounter; - scratchpad.callCounter += 1; - const wcall = new Call({ - func, - name, - input, - cache: options.cache, - retry: options.retry, - callbacks: options.callbacks - }); - const nextTask = await this.scheduleTask(task, cnt, wcall); - if (!nextTask) - return; - const existingPromise = this.executingTasksMap[nextTask.id]; - if (existingPromise !== undefined) - return existingPromise; - if (nextTask.writes.length > 0) { - const returns = nextTask.writes.filter(([c]) => c === RETURN); - const errors4 = nextTask.writes.filter(([c]) => c === ERROR2); - if (returns.length > 0) { - if (returns.length === 1) - return Promise.resolve(returns[0][1]); - throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); - } - if (errors4.length > 0) { - if (errors4.length === 1) { - const errorValue = errors4[0][1]; - const error51 = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); - return Promise.reject(error51); - } - throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); - } - return; - } else { - const prom = _runWithRetry(nextTask, options.retry, { [CONFIG_KEY_CALL]: call2.bind(this, runner, nextTask) }); - this.executingTasksMap[nextTask.id] = prom; - this.barrier.next(); - return prom.then(({ result, error: error51 }) => { - if (error51) - return Promise.reject(error51); - return result; - }); - } -} -var PROMISE_ADDED_SYMBOL, PregelRunner = class { - nodeFinished; - loop; - constructor({ loop, nodeFinished }) { - this.loop = loop; - this.nodeFinished = nodeFinished; - } - async tick(options = {}) { - const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; - const nodeErrors = /* @__PURE__ */ new Set; - let graphBubbleUp; - const exceptionSignalController = new AbortController; - const exceptionSignal = exceptionSignalController.signal; - const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : undefined; - const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); - const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ - exceptionSignal, - stepTimeoutSignal, - signal: options.signal - }); - const taskStream = this._executeTasksWithRetry(pendingTasks, { - signals, - retryPolicy, - maxConcurrency - }); - for await (const { task, error: error51, signalAborted } of taskStream) { - this._commit(task, error51); - if (isGraphInterrupt(error51)) - graphBubbleUp = error51; - else if (isGraphBubbleUp(error51) && !isGraphInterrupt(graphBubbleUp)) - graphBubbleUp = error51; - else if (error51 && (nodeErrors.size === 0 || !signalAborted)) { - exceptionSignalController.abort(); - nodeErrors.add(error51); - } - } - disposeCombinedSignal?.(); - onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat()); - if (nodeErrors.size === 1) - throw Array.from(nodeErrors)[0]; - else if (nodeErrors.size > 1) - throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); - if (isGraphInterrupt(graphBubbleUp)) - throw graphBubbleUp; - if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) - throw graphBubbleUp; - } - _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { - const previousSignals = this.loop.config.configurable?.["__pregel_abort_signals"] ?? {}; - const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; - const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; - const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); - const signals = { - externalAbortSignal, - timeoutAbortSignal, - composedAbortSignal - }; - this.loop.config = patchConfigurable2(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); - return { - signals, - disposeCombinedSignal - }; - } - async* _executeTasksWithRetry(tasks, options) { - const { retryPolicy, maxConcurrency, signals } = options ?? {}; - const barrier = createPromiseBarrier(); - const executingTasksMap = {}; - const thisCall = { - executingTasksMap, - barrier, - retryPolicy, - scheduleTask: async (task, writeIdx, call2) => this.loop.acceptPush(task, writeIdx, call2) - }; - if (signals?.composedAbortSignal?.aborted) - throw new Error("Abort"); - let startedTasksCount = 0; - let listener; - const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); - const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { - listener = () => reject(/* @__PURE__ */ new Error("Abort")); - timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); - }) : undefined; - while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { - for (;Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { - const task = tasks[startedTasksCount]; - executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [CONFIG_KEY_CALL]: call2?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error51) => { - return { - task, - error: error51, - signalAborted: signals?.composedAbortSignal?.aborted - }; + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); } - const settledTask = await Promise.race([ - ...Object.values(executingTasksMap), - ...abortPromise ? [abortPromise] : [], - barrier.wait - ]); - if (settledTask === PROMISE_ADDED_SYMBOL) - continue; - yield settledTask; - if (listener != null) { - timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); - timeoutOrCancelSignal.dispose?.(); + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + const llmOutputs = []; + const hasChatModelStreamEventHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersChatModelStreamEvents); + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasChatModelStreamEventHandler && !this.disableStreaming && baseMessages.length === 1 && (this._streamChatModelEvents !== BaseChatModel2.prototype._streamChatModelEvents || this._streamResponseChunks !== BaseChatModel2.prototype._streamResponseChunks)) + try { + let sawEvent = false; + const runManager = runManagers?.[0]; + const events = this._streamChatModelEvents(baseMessages[0], parsedOptions); + const message = await new ChatModelStream({ async* [Symbol.asyncIterator]() { + for await (const event of events) { + parsedOptions.signal?.throwIfAborted(); + sawEvent = true; + const streamEvent = event.event === "message-start" && event.id == null && runManager?.runId != null ? { + ...event, + id: `run-${runManager.runId}` + } : event; + await runManager?.handleChatModelStreamEvent(streamEvent); + yield streamEvent; + } + } }); + parsedOptions.signal?.throwIfAborted(); + if (!sawEvent) + throw new Error("Received empty response from chat model call."); + if (message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + message._updateId(`run-${runId}`); + } + const generation = { + text: message.text, + message + }; + generations.push([generation]); + const llmOutput = message.usage_metadata !== undefined ? { tokenUsage: { + promptTokens: message.usage_metadata.input_tokens, + completionTokens: message.usage_metadata.output_tokens, + totalTokens: message.usage_metadata.total_tokens + } } : undefined; + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel2.prototype._streamResponseChunks) + try { + const stream2 = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + let llmOutput; + for await (const chunk of stream2) { + if (parsedOptions.signal?.aborted) { + const partialMessage = aggregated?.message; + throw new ModelAbortError("Model invocation was aborted.", partialMessage); + } + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + if (aggregated === undefined) + aggregated = chunk; + else + aggregated = concat(aggregated, chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== undefined) + llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + if (parsedOptions.signal?.aborted) { + const partialMessage = aggregated?.message; + throw new ModelAbortError("Model invocation was aborted.", partialMessage); + } + if (aggregated === undefined) + throw new Error("Received empty response from chat model call."); + if (outputVersion === "v1") + aggregated.message = castStandardMessageContent(aggregated.message); + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { + const generateResults = await this._generate(messageList, { + ...parsedOptions, + promptIndex: i + }, runManagers?.[i]); + if (outputVersion === "v1") + for (const generation of generateResults.generations) + generation.message = castStandardMessageContent(generation.message); + return generateResults; + })); + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + generation.message._updateId(`run-${runId}`); + } + generation.message.response_metadata = { + ...generation.generationInfo, + ...generation.message.response_metadata + }; + } + if (result.generations.length === 1) + result.generations[0].message.response_metadata = { + ...result.llmOutput, + ...result.generations[0].message.response_metadata + }; + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput + }); + } else { + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); } - delete executingTasksMap[settledTask.task.id]; + const output = { + generations, + llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : undefined + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, + configurable: true + }); + return output; } - } - _commit(task, error51) { - if (error51 !== undefined) - if (isGraphInterrupt(error51)) { - if (error51.interrupts.length) { - const interrupts = error51.interrupts.map((interrupt2) => [INTERRUPT, interrupt2]); - const resumes = task.writes.filter((w) => w[0] === RESUME); - if (resumes.length) - interrupts.push(...resumes); - this.loop.putWrites(task.id, interrupts); + async _generateCached({ messages, cache: cache2, llmStringKey, parsedOptions, handledOptions }) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParamsWithDefaults(parsedOptions) + }; + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); + const missingPromptIndices = []; + const cachedResults = (await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { + const prompt = BaseChatModel2._convertInputToPromptValue(baseMessage).toString(); + const result = await cache2.lookup(prompt, llmStringKey); + if (result == null) + missingPromptIndices.push(index); + return result; + }))).map((result, index) => ({ + result, + runManager: runManagers?.[index] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result2) => { + if ("message" in result2 && isBaseMessage(result2.message) && isAIMessage(result2.message)) { + result2.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + if (outputVersion === "v1") + result2.message = castStandardMessageContent(result2.message); + } + result2.generationInfo = { + ...result2.generationInfo, + tokenUsage: {} + }; + return result2; + }); + if (result.length) + await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, undefined, undefined, undefined, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { cached: true }); + return Promise.reject(promiseResult.reason); } - } else if (isGraphBubbleUp(error51) && task.writes.length) - this.loop.putWrites(task.id, task.writes); - else - this.loop.putWrites(task.id, [[ERROR2, { - message: error51.message, - name: error51.name - }]]); - else { - if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes("langsmith:hidden"))) - this.nodeFinished(String(task.name)); - if (task.writes.length === 0) - task.writes.push([NO_WRITES, null]); - this.loop.putWrites(task.id, task.writes); - } - } -}; -var init_runner = __esm(() => { - init_constants3(); - init_errors5(); - init_types7(); - init_utils9(); - init_retry(); - PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/validate.js -function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { - if (!channels) - throw new GraphValidationError("Channels not provided"); - const subscribedChannels = /* @__PURE__ */ new Set; - const allOutputChannels = /* @__PURE__ */ new Set; - for (const [name, node] of Object.entries(nodes)) { - if (name === "__interrupt__") - throw new GraphValidationError(`"Node name ${INTERRUPT} is reserved"`); - if (node.constructor === PregelNode) - node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); - else - throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); - } - for (const chan of subscribedChannels) - if (!(chan in channels)) - throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); - if (!Array.isArray(inputChannels)) { - if (!subscribedChannels.has(inputChannels)) - throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); - } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) - throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); - if (!Array.isArray(outputChannels)) - allOutputChannels.add(outputChannels); - else - outputChannels.forEach((chan) => allOutputChannels.add(chan)); - if (streamChannels && !Array.isArray(streamChannels)) - allOutputChannels.add(streamChannels); - else if (Array.isArray(streamChannels)) - streamChannels.forEach((chan) => allOutputChannels.add(chan)); - for (const chan of allOutputChannels) - if (!(chan in channels)) - throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); - if (interruptAfterNodes && interruptAfterNodes !== "*") { - for (const node of interruptAfterNodes) - if (!(node in nodes)) - throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } - if (interruptBeforeNodes && interruptBeforeNodes !== "*") { - for (const node of interruptBeforeNodes) - if (!(node in nodes)) - throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } -} -function validateKeys(keys, channels) { - if (Array.isArray(keys)) { - for (const key of keys) - if (!(key in channels)) - throw new Error(`Key ${String(key)} not found in channels`); - } else if (!(keys in channels)) - throw new Error(`Key ${String(keys)} not found in channels`); -} -var GraphValidationError; -var init_validate4 = __esm(() => { - init_constants3(); - init_read(); - GraphValidationError = class extends Error { - constructor(message) { - super(message); - this.name = "GraphValidationError"; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/topic.js -var Topic; -var init_topic = __esm(() => { - init_errors5(); - init_base15(); - Topic = class Topic2 extends BaseChannel { - lc_graph_name = "Topic"; - unique = false; - accumulate = false; - seen; - values; - constructor(fields) { - super(); - this.unique = fields?.unique ?? this.unique; - this.accumulate = fields?.accumulate ?? this.accumulate; - this.seen = /* @__PURE__ */ new Set; - this.values = []; + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, + configurable: true + }); + return output; } - fromCheckpoint(checkpoint) { - const empty = new Topic2({ - unique: this.unique, - accumulate: this.accumulate + async generate(messages, options, callbacks) { + let parsedOptions; + if (Array.isArray(options)) + parsedOptions = { stop: options }; + else + parsedOptions = options; + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) + return this._generateUncached(baseMessages, callOptions, runnableConfig); + const { cache: cache2 } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache: cache2, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig }); - if (typeof checkpoint !== "undefined") { - empty.seen = new Set(checkpoint[0]); - empty.values = checkpoint[1]; + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : undefined); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + const prompt = BaseChatModel2._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache2.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; } - return empty; + return { + generations, + llmOutput + }; } - update(values) { - let updated = false; - if (!this.accumulate) { - updated = this.values.length > 0; - this.values = []; - } - const flatValues = values.flat(); - if (flatValues.length > 0) - if (this.unique) { - for (const value of flatValues) - if (!this.seen.has(value)) { - updated = true; - this.seen.add(value); - this.values.push(value); - } - } else { - updated = true; - this.values.push(...flatValues); - } - return updated; + invocationParams(_options) { + return {}; } - get() { - if (this.values.length === 0) - throw new EmptyChannelError; - return this.values; + _modelType() { + return "base_chat_model"; } - checkpoint() { - return [[...this.seen], this.values]; + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); } - isAvailable() { - return this.values.length !== 0; + withStructuredOutput(outputSchema, config3) { + if (typeof this.bindTools !== "function") + throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); + if (config3?.strict) + throw new Error(`"strict" mode is not supported for this model by default.`); + const schema = outputSchema; + const name = config3?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config3?.method; + const includeRaw = config3?.includeRaw; + if (method === "jsonMode") + throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); + let functionName = name ?? "extract"; + if (!isInteropZodSchema(schema) && !isSerializableSchema(schema) && "name" in schema) + functionName = schema.name; + const asJsonSchema = isInteropZodSchema(schema) || isSerializableSchema(schema) ? toJsonSchema(schema) : schema; + const tools = [{ + type: "function", + function: { + name: functionName, + description, + parameters: asJsonSchema + } + }]; + return assembleStructuredOutputPipeline(this.bindTools(tools), RunnableLambda.from((input) => { + if (!AIMessageChunk.isInstance(input)) + throw new Error("Input is not an AIMessageChunk."); + if (!input.tool_calls || input.tool_calls.length === 0) + throw new Error("No tool calls found in the response."); + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) + throw new Error(`No tool call found with name ${functionName}.`); + return toolCall.args; + }), includeRaw, includeRaw ? "StructuredOutputRunnable" : "StructuredOutput"); + } + }; + SimpleChatModel = class extends BaseChatModel { + async _generate(messages, options, runManager) { + const message = new AIMessage(await this._call(messages, options, runManager)); + if (typeof message.content !== "string") + throw new Error("Cannot generate with a simple chat model when output is not a string."); + return { generations: [{ + text: message.content, + message + }] }; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/pregel/index.js -function protocolEventsToEventStream(run2) { - const encoder2 = new TextEncoder; - return new ReadableStream({ async start(controller) { - try { - for await (const event of run2) { - const namespace = event.params.namespace; - const eventName = namespace.length ? `${event.method}|${namespace.join("|")}` : event.method; - controller.enqueue(encoder2.encode(`event: ${eventName} -data: ${JSON.stringify(event.params.data ?? {})} - -`)); - } - } catch (error51) { - controller.enqueue(encoder2.encode(`event: error -data: ${JSON.stringify({ message: String(error51) })} - -`)); - } finally { - controller.close(); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/chat_models/universal.js +async function getChatModelByClassName(className, modelProvider) { + let config3; + if (modelProvider) + config3 = MODEL_PROVIDER_CONFIG[modelProvider]; + else { + const providerEntry = Object.entries(MODEL_PROVIDER_CONFIG).find(([, c]) => c.className === className); + config3 = providerEntry ? providerEntry[1] : undefined; + } + if (!config3) + return; + try { + return (await import(config3.package))[config3.className]; + } catch (e) { + const err = e; + if ("code" in err && err.code?.toString().includes("ERR_MODULE_NOT_FOUND") && "message" in err && typeof err.message === "string") { + const attemptedPackage = (err.message.startsWith("Error: ") ? err.message.slice(7) : err.message).split("Cannot find package '")[1].split("'")[0]; + throw new Error(`Unable to import ${attemptedPackage}. Please install with \`npm install ${attemptedPackage}\` or \`pnpm install ${attemptedPackage}\``); } - } }); -} -function _buildServerInfo(config2) { - const metadata = config2.metadata ?? {}; - const configurable = config2.configurable ?? {}; - const assistantId = metadata.assistant_id; - const graphId = metadata.graph_id; - const authUserData = configurable.langgraph_auth_user; - let user; - if (authUserData != null && typeof authUserData === "object" && "identity" in authUserData) - user = authUserData; - if (assistantId != null || graphId != null || user != null) - return { - assistantId: assistantId != null ? String(assistantId) : "", - graphId: graphId != null ? String(graphId) : "", - user - }; + throw e; + } } -function _excludeAsMetadata(key, value) { - const keyLower = key.toLowerCase(); - let hasOmittedSubstring = false; - for (const substr of OMITTED_KEYS) - if (keyLower.includes(substr)) { - hasOmittedSubstring = true; - break; - } - return key.startsWith("__") || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || hasOmittedSubstring; +async function _initChatModelHelper(model, modelProvider, params = {}) { + const modelProviderCopy = modelProvider || _inferModelProvider(model); + if (!modelProviderCopy) + throw new Error(`Unable to infer model provider for { model: ${model} }, please specify modelProvider directly.`); + const config3 = MODEL_PROVIDER_CONFIG[modelProviderCopy]; + if (!config3) { + const supported = SUPPORTED_PROVIDERS.join(", "); + throw new Error(`Unsupported { modelProvider: ${modelProviderCopy} }. + +Supported model providers are: ${supported}`); + } + const { modelProvider: _unused, ...passedParams } = params; + return new (await getChatModelByClassName(config3.className, modelProviderCopy))({ + model, + ...passedParams + }); } -function _getTracingMetadataDefaults(config2) { - const configurable = config2.configurable; - if (!configurable) +function _inferModelProvider(modelName) { + if (modelName.startsWith("gpt-3") || modelName.startsWith("gpt-4") || modelName.startsWith("gpt-5") || modelName.startsWith("o1") || modelName.startsWith("o3") || modelName.startsWith("o4")) + return "openai"; + else if (modelName.startsWith("claude")) + return "anthropic"; + else if (modelName.startsWith("command")) + return "cohere"; + else if (modelName.startsWith("accounts/fireworks")) + return "fireworks"; + else if (modelName.startsWith("gemini")) + return "google-vertexai"; + else if (modelName.startsWith("amazon.")) + return "bedrock"; + else if (modelName.startsWith("mistral")) + return "mistralai"; + else if (modelName.startsWith("sonar") || modelName.startsWith("pplx")) + return "perplexity"; + else return; - const metadata = {}; - for (const [key, value] of Object.entries(configurable)) { - if (_excludeAsMetadata(key, value)) - continue; - metadata[key] = value; - } - return Object.keys(metadata).length > 0 ? metadata : undefined; } -var Channel = class { - static subscribeTo(channels, options) { - const { key, tags } = { - key: undefined, - tags: undefined, - ...options ?? {} - }; - if (Array.isArray(channels) && key !== undefined) - throw new Error("Can't specify a key when subscribing to multiple channels"); - let channelMappingOrArray; - if (typeof channels === "string") - if (key) - channelMappingOrArray = { [key]: channels }; - else - channelMappingOrArray = [channels]; - else - channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); - return new PregelNode({ - channels: channelMappingOrArray, - triggers: Array.isArray(channels) ? channels : [channels], - tags - }); +async function initChatModel(model, fields) { + let { configurableFields, configPrefix, modelProvider, profile, ...params } = { + configPrefix: "", + ...fields ?? {} + }; + if (modelProvider === undefined && model?.includes(":")) { + const [provider, ...remainingParts] = model.split(":"); + const modelComponents = remainingParts.length === 0 ? [provider] : [provider, remainingParts.join(":")]; + if (SUPPORTED_PROVIDERS.includes(modelComponents[0])) + [modelProvider, model] = modelComponents; } - static writeTo(channels, writes) { - const channelWriteEntries = []; - for (const channel of channels) - channelWriteEntries.push({ - channel, - value: PASSTHROUGH, - skipNone: false - }); - for (const [key, value] of Object.entries(writes ?? {})) - if (Runnable.isRunnable(value) || typeof value === "function") - channelWriteEntries.push({ - channel: key, - value: PASSTHROUGH, - skipNone: true, - mapper: _coerceToRunnable(value) - }); - else - channelWriteEntries.push({ - channel: key, - value, - skipNone: false - }); - return new ChannelWrite(channelWriteEntries); + let configurableFieldsCopy = Array.isArray(configurableFields) ? [...configurableFields] : configurableFields; + if (!model && configurableFieldsCopy === undefined) + configurableFieldsCopy = ["model", "modelProvider"]; + if (configPrefix && configurableFieldsCopy === undefined) + console.warn(`{ configPrefix: ${configPrefix} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`); + const paramsCopy = { ...params }; + let configurableModel; + if (configurableFieldsCopy === undefined) + configurableModel = new ConfigurableModel({ + defaultConfig: { + ...paramsCopy, + model, + modelProvider + }, + configPrefix, + profile + }); + else { + if (model) + paramsCopy.model = model; + if (modelProvider) + paramsCopy.modelProvider = modelProvider; + configurableModel = new ConfigurableModel({ + defaultConfig: paramsCopy, + configPrefix, + configurableFields: configurableFieldsCopy, + profile + }); } -}, PartialRunnable, Pregel, OMITTED_KEYS; -var init_pregel = __esm(() => { - init_constants3(); - init_errors5(); - init_base15(); - init_config2(); - init_utils8(); - init_write(); - init_read(); - init_io(); - init_utils9(); - init_algo(); - init_subgraph(); - init_debug(); - init_stream5(); - init_loop(); - init_messages3(); - init_messages_v2(); - init_runner(); - init_convert(); - init_run_stream(); - init_stream4(); - init_validate4(); - init_topic(); - init_interrupt(); - init_dist3(); + await configurableModel._getModelInstance(); + return configurableModel; +} +var MODEL_PROVIDER_CONFIG, SUPPORTED_PROVIDERS, ConfigurableModel; +var init_universal = __esm(() => { + init_runtime(); + init_chat_models(); init_runnables(); - init_manager(); - PartialRunnable = class extends Runnable { - lc_namespace = ["langgraph", "pregel"]; - invoke(_input, _options) { - throw new Error("Not implemented"); - } - withConfig(_config) { - return super.withConfig(_config); - } - stream(input, options) { - return super.stream(input, options); + init_stream(); + MODEL_PROVIDER_CONFIG = { + openai: { + package: "@langchain/openai", + className: "ChatOpenAI" + }, + anthropic: { + package: "@langchain/anthropic", + className: "ChatAnthropic" + }, + azure_openai: { + package: "@langchain/openai", + className: "AzureChatOpenAI" + }, + cohere: { + package: "@langchain/cohere", + className: "ChatCohere" + }, + google: { + package: "@langchain/google", + className: "ChatGoogle" + }, + "google-vertexai": { + package: "@langchain/google-vertexai", + className: "ChatVertexAI" + }, + "google-vertexai-web": { + package: "@langchain/google-vertexai-web", + className: "ChatVertexAI" + }, + "google-genai": { + package: "@langchain/google-genai", + className: "ChatGoogleGenerativeAI" + }, + ollama: { + package: "@langchain/ollama", + className: "ChatOllama" + }, + mistralai: { + package: "@langchain/mistralai", + className: "ChatMistralAI" + }, + mistral: { + package: "@langchain/mistralai", + className: "ChatMistralAI" + }, + groq: { + package: "@langchain/groq", + className: "ChatGroq" + }, + bedrock: { + package: "@langchain/aws", + className: "ChatBedrockConverse" + }, + aws: { + package: "@langchain/aws", + className: "ChatBedrockConverse" + }, + deepseek: { + package: "@langchain/deepseek", + className: "ChatDeepSeek" + }, + xai: { + package: "@langchain/xai", + className: "ChatXAI" + }, + cerebras: { + package: "@langchain/cerebras", + className: "ChatCerebras" + }, + fireworks: { + package: "@langchain/fireworks", + className: "ChatFireworks" + }, + together: { + package: "@langchain/together-ai", + className: "ChatTogetherAI", + hasCircularDependency: true + }, + perplexity: { + package: "@langchain/perplexity", + className: "ChatPerplexity" } }; - Pregel = class extends PartialRunnable { - static lc_name() { - return "LangGraph"; + SUPPORTED_PROVIDERS = Object.keys(MODEL_PROVIDER_CONFIG); + ConfigurableModel = class ConfigurableModel2 extends BaseChatModel { + _llmType() { + return "chat_model"; } - lc_namespace = ["langgraph", "pregel"]; - lg_is_pregel = true; - nodes; - channels; - inputChannels; - outputChannels; - autoValidate = true; - streamMode = ["values"]; - streamChannels; - interruptAfter; - interruptBefore; - stepTimeout; - debug = false; - checkpointer; - retryPolicy; - config; - store; - cache; - userInterrupt; - streamTransformers; - triggerToNodes = {}; + lc_namespace = ["langchain", "chat_models"]; + _defaultConfig = {}; + _configurableFields = "any"; + _configPrefix; + _queuedMethodOperations = {}; + _modelInstanceCache = /* @__PURE__ */ new Map; + _profile; constructor(fields) { super(fields); - let { streamMode } = fields; - if (streamMode != null && !Array.isArray(streamMode)) - streamMode = [streamMode]; - this.nodes = fields.nodes; - this.channels = fields.channels; - if ("__pregel_tasks" in this.channels && "lc_graph_name" in this.channels["__pregel_tasks"] && this.channels["__pregel_tasks"].lc_graph_name !== "Topic") - throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`); - else - this.channels[TASKS] = new Topic({ accumulate: false }); - this.autoValidate = fields.autoValidate ?? this.autoValidate; - this.streamMode = streamMode ?? this.streamMode; - this.inputChannels = fields.inputChannels; - this.outputChannels = fields.outputChannels; - this.streamChannels = fields.streamChannels ?? this.streamChannels; - this.interruptAfter = fields.interruptAfter; - this.interruptBefore = fields.interruptBefore; - this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; - this.debug = fields.debug ?? this.debug; - this.checkpointer = fields.checkpointer; - this.retryPolicy = fields.retryPolicy; - this.config = fields.config; - this.store = fields.store; - this.cache = fields.cache; - this.name = fields.name; - this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; - this.userInterrupt = fields.userInterrupt; - this.streamTransformers = fields.streamTransformers ?? []; - if (this.autoValidate) - this.validate(); - } - withConfig(config2) { - const { streamTransformers, ...restConfig } = config2; - const mergedConfig = mergeConfigs(this.config, restConfig); - const mergedStreamTransformers = [...this.streamTransformers, ...streamTransformers ?? []]; - return new this.constructor({ - ...this, - config: mergedConfig, - streamTransformers: mergedStreamTransformers - }); - } - validate() { - validateGraph({ - nodes: this.nodes, - channels: this.channels, - outputChannels: this.outputChannels, - inputChannels: this.inputChannels, - streamChannels: this.streamChannels, - interruptAfterNodes: this.interruptAfter, - interruptBeforeNodes: this.interruptBefore - }); - for (const [name, node] of Object.entries(this.nodes)) - for (const trigger of node.triggers) { - this.triggerToNodes[trigger] ??= []; - this.triggerToNodes[trigger].push(name); - } - return this; - } - get streamChannelsList() { - if (Array.isArray(this.streamChannels)) - return this.streamChannels; - else if (this.streamChannels) - return [this.streamChannels]; + this._defaultConfig = fields.defaultConfig ?? {}; + if (fields.configurableFields === "any") + this._configurableFields = "any"; else - return Object.keys(this.channels); - } - get streamChannelsAsIs() { - if (this.streamChannels) - return this.streamChannels; + this._configurableFields = fields.configurableFields ?? ["model", "modelProvider"]; + if (fields.configPrefix) + this._configPrefix = fields.configPrefix.endsWith("_") ? fields.configPrefix : `${fields.configPrefix}_`; else - return Object.keys(this.channels); + this._configPrefix = ""; + this._queuedMethodOperations = fields.queuedMethodOperations ?? this._queuedMethodOperations; + this._profile = fields.profile ?? undefined; + this.metadata = { + ...this.metadata, + ls_integration: "langchain_init_chat_model" + }; } - async getGraphAsync(config2) { - return this.getGraph(config2); + async _getModelInstance(config3) { + const cacheKey2 = this._getCacheKey(config3); + const cachedModel = this._modelInstanceCache.get(cacheKey2); + if (cachedModel) + return cachedModel; + const params = { + ...this._defaultConfig, + ...this._modelParams(config3) + }; + let initializedModel = await _initChatModelHelper(params.model, params.modelProvider, params); + for (const [method, args] of Object.entries(this._queuedMethodOperations)) + if (method in initializedModel && typeof initializedModel[method] === "function") + initializedModel = await initializedModel[method](...args); + this._modelInstanceCache.set(cacheKey2, initializedModel); + return initializedModel; } - *getSubgraphs(namespace, recurse) { - for (const [name, node] of Object.entries(this.nodes)) { - if (namespace !== undefined) { - if (!namespace.startsWith(name)) - continue; - } - const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; - for (const candidate of candidates) { - const graph = findSubgraphPregel(candidate); - if (graph !== undefined) { - if (name === namespace) { - yield [name, graph]; - return; - } - if (namespace === undefined) - yield [name, graph]; - if (recurse) { - let newNamespace = namespace; - if (namespace !== undefined) - newNamespace = namespace.slice(name.length + 1); - for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) - yield [`${name}|${subgraphName}`, subgraph]; - } - } - } - } + async _generate(messages, options, runManager) { + return (await this._getModelInstance(options))._generate(messages, options ?? {}, runManager); } - async* getSubgraphsAsync(namespace, recurse) { - yield* this.getSubgraphs(namespace, recurse); + bindTools(tools, params) { + const newQueuedOperations = { ...this._queuedMethodOperations }; + newQueuedOperations.bindTools = [tools, params]; + return new ConfigurableModel2({ + defaultConfig: this._defaultConfig, + configurableFields: this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: newQueuedOperations + }); } - async _prepareStateSnapshot({ config: config2, saved, subgraphCheckpointer, applyPendingWrites = false }) { - if (saved === undefined) - return { - values: {}, - next: [], - config: config2, - tasks: [] - }; - const channels = emptyChannels(this.channels, saved.checkpoint); - if (saved.pendingWrites?.length) { - const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); - if (nullWrites.length > 0) - _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], undefined, this.triggerToNodes); - } - const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - store: this.store - })); - const subgraphs = await gatherIterator(this.getSubgraphsAsync()); - const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; - const taskStates = {}; - for (const task of nextTasks) { - const matchingSubgraph = subgraphs.find(([name]) => name === task.name); - if (!matchingSubgraph) - continue; - let taskNs = `${String(task.name)}:${task.id}`; - if (parentNamespace) - taskNs = `${parentNamespace}|${taskNs}`; - if (subgraphCheckpointer === undefined) { - const config3 = { configurable: { - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - taskStates[task.id] = config3; - } else { - const subgraphConfig = { configurable: { - [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - const pregel = matchingSubgraph[1]; - taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); - } - } - if (applyPendingWrites && saved.pendingWrites?.length) { - const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); - for (const [taskId, channel, value] of saved.pendingWrites) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(channel)) - continue; - if (!(taskId in nextTaskById)) - continue; - nextTaskById[taskId].writes.push([String(channel), value]); + withStructuredOutput = (schema, ...args) => { + const newQueuedOperations = { ...this._queuedMethodOperations }; + newQueuedOperations.withStructuredOutput = [schema, ...args]; + return new ConfigurableModel2({ + defaultConfig: this._defaultConfig, + configurableFields: this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: newQueuedOperations + }); + }; + _modelParams(config3) { + const configurable = config3?.configurable ?? {}; + let modelParams = {}; + for (const [key, value] of Object.entries(configurable)) + if (key.startsWith(this._configPrefix)) { + const strippedKey = this._removePrefix(key, this._configPrefix); + modelParams[strippedKey] = value; } - const tasksWithWrites2 = nextTasks.filter((task) => task.writes.length > 0); - if (tasksWithWrites2.length > 0) - _applyWrites(saved.checkpoint, channels, tasksWithWrites2, undefined, this.triggerToNodes); - } - let metadata = saved?.metadata; - if (metadata && saved?.config?.configurable?.thread_id) - metadata = { - ...metadata, - thread_id: saved.config.configurable.thread_id - }; - const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); - return { - values: readChannels(channels, this.streamChannelsAsIs), - next: nextList, - tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), - metadata, - config: patchCheckpointMap(saved.config, saved.metadata), - createdAt: saved.checkpoint.ts, - parentConfig: saved.parentConfig - }; + if (this._configurableFields !== "any") + modelParams = Object.fromEntries(Object.entries(modelParams).filter(([key]) => this._configurableFields.includes(key))); + return modelParams; } - async getState(config2, options) { - const checkpointer = config2.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config2.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config2.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) - if (name === recastNamespace) - return await subgraph.getState(patchConfigurable(config2, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); - } - const mergedConfig = mergeConfigs(this.config, config2); - const saved = await checkpointer.getTuple(config2); - return await this._prepareStateSnapshot({ + _removePrefix(str, prefix) { + return str.startsWith(prefix) ? str.slice(prefix.length) : str; + } + withConfig(config3) { + const mergedConfig = { ...config3 || {} }; + const modelParams = this._modelParams(mergedConfig); + const remainingConfig = Object.fromEntries(Object.entries(mergedConfig).filter(([k]) => k !== "configurable")); + remainingConfig.configurable = Object.fromEntries(Object.entries(mergedConfig.configurable || {}).filter(([k]) => this._configPrefix && !Object.keys(modelParams).includes(this._removePrefix(k, this._configPrefix)))); + return new RunnableBinding({ config: mergedConfig, - saved, - subgraphCheckpointer: options?.subgraphs ? checkpointer : undefined, - applyPendingWrites: !config2.configurable?.checkpoint_id + bound: new ConfigurableModel2({ + defaultConfig: { + ...this._defaultConfig, + ...modelParams + }, + configurableFields: Array.isArray(this._configurableFields) ? [...this._configurableFields] : this._configurableFields, + configPrefix: this._configPrefix, + queuedMethodOperations: this._queuedMethodOperations + }) }); } - async* getStateHistory(config2, options) { - const checkpointer = config2.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config2.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config2.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) - if (name === recastNamespace) { - yield* pregel.getStateHistory(patchConfigurable(config2, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); - return; - } - } - const mergedConfig = mergeConfigs(this.config, config2, { configurable: { checkpoint_ns: checkpointNamespace } }); - for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) - yield this._prepareStateSnapshot({ - config: checkpointTuple.config, - saved: checkpointTuple - }); + async invoke(input, options) { + const model = await this._getModelInstance(options); + const config3 = ensureConfig(options); + return model.invoke(input, config3); } - async bulkUpdateState(startConfig, supersteps) { - const checkpointer = startConfig.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - if (supersteps.length === 0) - throw new Error("No supersteps provided"); - if (supersteps.some((s) => s.updates.length === 0)) - throw new Error("No updates provided"); - const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && startConfig.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) - return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); - throw new Error(`Subgraph "${recastNamespace}" not found`); - } - const updateSuperStep = async (inputConfig, updates) => { - const config2 = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; - const saved = await checkpointer.getTuple(config2); - const checkpoint = saved !== undefined ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); - const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; - const step = saved?.metadata?.step ?? -1; - let checkpointConfig = patchConfigurable(config2, { checkpoint_ns: config2.configurable?.checkpoint_ns ?? "" }); - let checkpointMetadata = config2.metadata ?? {}; - if (saved?.config.configurable) { - checkpointConfig = patchConfigurable(config2, saved.config.configurable); - checkpointMetadata = { - ...saved.metadata, - ...checkpointMetadata - }; - } - const { values, asNode } = updates[0]; - if (values == null && asNode === undefined) { - if (updates.length > 1) - throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); - return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, undefined, step), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, {}), saved ? saved.metadata : undefined); - } - const channels = emptyChannels(this.channels, checkpoint); - if (values === null && asNode === "__end__") { - if (updates.length > 1) - throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); - if (saved) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - checkpointer, - store: this.store - }); - const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - for (const [taskId, k, v] of saved.pendingWrites || []) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(k)) - continue; - if (!(taskId in nextTasks)) - continue; - nextTasks[taskId].writes.push([k, v]); - } - _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - } - return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { - ...checkpointMetadata, - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : undefined); - } - if (asNode === "__copy__") { - if (updates.length > 1) - throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); - if (saved == null) - throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); - const isCopyWithUpdates = (values2) => { - if (!Array.isArray(values2)) - return false; - if (values2.length === 0) - return false; - return values2.every((v) => Array.isArray(v) && v.length === 2); - }; - const nextCheckpoint = createCheckpoint(checkpoint, undefined, step); - const nextConfig2 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: undefined }), nextCheckpoint, { - source: "fork", - step: step + 1, - parents: saved.metadata?.parents ?? {} - }, {}); - if (isCopyWithUpdates(values)) { - const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig2, false, { step: step + 2 }); - const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { - acc[name] ??= []; - acc[name].push({ id }); - return acc; - }, {}); - const userGroupBy = values.reduce((acc, item) => { - const [values2, asNode2] = item; - acc[asNode2] ??= []; - const targetIdx = acc[asNode2].length; - const taskId = tasksGroupBy[asNode2]?.[targetIdx]?.id; - acc[asNode2].push({ - values: values2, - asNode: asNode2, - taskId - }); - return acc; - }, {}); - return updateSuperStep(patchCheckpointMap(nextConfig2, saved.metadata), Object.values(userGroupBy).flat()); - } - return patchCheckpointMap(nextConfig2, saved.metadata); - } - if (asNode === "__input__") { - if (updates.length > 1) - throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); - const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); - if (inputWrites.length === 0) - throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); - _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: inputWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; - const nextConfig2 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { - source: "input", - step: nextStep, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); - await checkpointer.putWrites(nextConfig2, inputWrites, uuid5(INPUT, checkpoint.id)); - return patchCheckpointMap(nextConfig2, saved ? saved.metadata : undefined); - } - if (config2.configurable?.checkpoint_id === undefined && saved?.pendingWrites !== undefined && saved.pendingWrites.length > 0) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - store: this.store, - checkpointer: this.checkpointer, - step: (saved.metadata?.step ?? -1) + 1 - }); - const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], undefined, this.triggerToNodes); - for (const [tid, k, v] of saved.pendingWrites) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(k) || nextTasks[tid] === undefined) - continue; - nextTasks[tid].writes.push([k, v]); - } - const tasks2 = Object.values(nextTasks).filter((task) => { - return task.writes.length > 0; - }); - if (tasks2.length > 0) - _applyWrites(checkpoint, channels, tasks2, undefined, this.triggerToNodes); - } - const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { - return Object.values(seenVersions); - }).flat().find((v) => !!v); - const validUpdates = []; - if (updates.length === 1) { - let { values: values2, asNode: asNode2, taskId } = updates[0]; - if (asNode2 === undefined && Object.keys(this.nodes).length === 1) - [asNode2] = Object.keys(this.nodes); - else if (asNode2 === undefined && nonNullVersion === undefined) { - if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== undefined) - asNode2 = this.inputChannels; - } else if (asNode2 === undefined) { - const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n3, seen]) => { - return Object.values(seen).map((v) => { - return [v, n3]; - }); - }).flat().filter(([_, v]) => v !== INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); - if (lastSeenByNode) { - if (lastSeenByNode.length === 1) - asNode2 = lastSeenByNode[0][1]; - else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) - asNode2 = lastSeenByNode[lastSeenByNode.length - 1][1]; - } - } - if (asNode2 === undefined) - throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); - validUpdates.push({ - values: values2, - asNode: asNode2, - taskId - }); - } else - for (const { asNode: asNode2, values: values2, taskId } of updates) { - if (asNode2 == null) - throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); - validUpdates.push({ - values: values2, - asNode: asNode2, - taskId - }); - } - const tasks = []; - for (const { asNode: asNode2, values: values2, taskId } of validUpdates) { - if (this.nodes[asNode2] === undefined) - throw new InvalidUpdateError(`Node "${asNode2.toString()}" does not exist`); - const writers = this.nodes[asNode2].getWriters(); - if (!writers.length) - throw new InvalidUpdateError(`No writers found for node "${asNode2.toString()}"`); - tasks.push({ - name: asNode2, - input: values2, - proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], - writes: [], - triggers: [INTERRUPT], - id: taskId ?? uuid5("__interrupt__", checkpoint.id), - writers: [] - }); - } - for (const task of tasks) - await task.proc.invoke(task.input, patchConfig({ - ...config2, - store: config2?.store ?? this.store - }, { - runName: config2.runName ?? `${this.getName()}UpdateState`, - configurable: { - [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) - } - })); - for (const task of tasks) { - const channelWrites = task.writes.filter((w) => w[0] !== PUSH); - if (saved !== undefined && channelWrites.length > 0) - await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); - } - _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); - const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, newVersions); - for (const task of tasks) { - const pushWrites = task.writes.filter((w) => w[0] === PUSH); - if (pushWrites.length > 0) - await checkpointer.putWrites(nextConfig, pushWrites, task.id); - } - return patchCheckpointMap(nextConfig, saved ? saved.metadata : undefined); - }; - let currentConfig = startConfig; - for (const { updates } of supersteps) - currentConfig = await updateSuperStep(currentConfig, updates); - return currentConfig; + async stream(input, options) { + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: await (await this._getModelInstance(options)).stream(input, options), + config: options + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } - async updateState(inputConfig, values, asNode) { - return this.bulkUpdateState(inputConfig, [{ updates: [{ - values, - asNode - }] }]); + async batch(inputs, options, batchOptions) { + return super.batch(inputs, options, batchOptions); } - _defaults(config2) { - const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config2; - let streamModeSingle = true; - const defaultDebug = debug !== undefined ? debug : this.debug; - let defaultOutputKeys = outputKeys; - if (defaultOutputKeys === undefined) - defaultOutputKeys = this.streamChannelsAsIs; - else - validateKeys(defaultOutputKeys, this.channels); - let defaultInputKeys = inputKeys; - if (defaultInputKeys === undefined) - defaultInputKeys = this.inputChannels; - else - validateKeys(defaultInputKeys, this.channels); - const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; - const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; - let defaultStreamMode; - if (streamMode !== undefined) { - defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; - streamModeSingle = typeof streamMode === "string"; - } else { - if (config2.configurable?.["__pregel_task_id"] !== undefined) - defaultStreamMode = ["values"]; - else - defaultStreamMode = this.streamMode; - streamModeSingle = true; - } - let defaultCheckpointer; - if (this.checkpointer === false) - defaultCheckpointer = undefined; - else if (config2 !== undefined && config2.configurable?.["__pregel_checkpointer"] !== undefined) - defaultCheckpointer = config2.configurable[CONFIG_KEY_CHECKPOINTER]; - else if (this.checkpointer === true) - throw new Error("checkpointer: true cannot be used for root graphs."); - else - defaultCheckpointer = this.checkpointer; - const defaultStore = config2.store ?? this.store; - const defaultCache = config2.cache ?? this.cache; - if (config2.durability != null && config2.checkpointDuring != null) - throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); - const checkpointDuringDurability = (() => { - if (config2.checkpointDuring == null) - return; - if (config2.checkpointDuring === false) - return "exit"; - return "async"; - })(); - const defaultDurability = config2.durability ?? checkpointDuringDurability ?? config2?.configurable?.["__pregel_durability"] ?? "async"; - return [ - defaultDebug, - defaultStreamMode, - defaultInputKeys, - defaultOutputKeys, - rest, - defaultInterruptBefore, - defaultInterruptAfter, - defaultCheckpointer, - defaultStore, - streamModeSingle, - defaultCache, - defaultDurability - ]; + async* transform(generator, options) { + const model = await this._getModelInstance(options); + const config3 = ensureConfig(options); + yield* model.transform(generator, config3); } - async stream(input, options) { - const abortController = new AbortController; - const config2 = { - recursionLimit: this.config?.recursionLimit, - ...options, - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - const stream2 = await super.stream(input, config2); - return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream2) : stream2, abortController); + async* streamLog(input, options, streamOptions) { + const model = await this._getModelInstance(options); + const config3 = ensureConfig(options); + yield* model.streamLog(input, config3, { + ...streamOptions, + _schemaFormat: "original", + includeNames: streamOptions?.includeNames, + includeTypes: streamOptions?.includeTypes, + includeTags: streamOptions?.includeTags, + excludeNames: streamOptions?.excludeNames, + excludeTypes: streamOptions?.excludeTypes, + excludeTags: streamOptions?.excludeTags + }); } - async#streamEventsV3(input, options) { - const { version: version4, encoding, transformers: userTransformers, ...restOptions } = options; - const streamOptions = { - recursionLimit: this.config?.recursionLimit, - ...restOptions, - configurable: { - ...this.config?.configurable, - ...restOptions?.configurable - }, - version: version4, - streamMode: STREAM_EVENTS_V3_MODES, - subgraphs: true, - encoding: undefined - }; - const sourcePromise = this.stream(input, streamOptions); - const graphRun = createGraphRunStream({ [Symbol.asyncIterator]: async function* () { - const src = await sourcePromise; - for await (const chunk of src) + streamEvents(input, options, streamOptions) { + const outerThis = this; + async function* wrappedGenerator() { + const model = await outerThis._getModelInstance(options); + const config3 = ensureConfig(options); + const eventStream = model.streamEvents(input, config3, streamOptions); + for await (const chunk of eventStream) yield chunk; - } }, [...this.streamTransformers ?? [], ...userTransformers ?? []]); - if (encoding === "text/event-stream") { - const abortController = new AbortController; - abortController.signal.addEventListener("abort", () => graphRun.abort(abortController.signal.reason), { once: true }); - return new IterableReadableStreamWithAbortSignal(protocolEventsToEventStream(graphRun), abortController); } - return graphRun; - } - streamEvents(input, options, streamOptions) { - if (options.version === "v3") - return this.#streamEventsV3(input, options); - const abortController = new AbortController; - const config2 = { - recursionLimit: this.config?.recursionLimit, - ...options, - callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks), - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config2, streamOptions), abortController); - } - async _validateInput(input) { - return input; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator()); } - async _validateContext(context2) { - return context2; + get profile() { + if (this._profile) + return this._profile; + const cacheKey2 = this._getCacheKey({}); + return this._modelInstanceCache.get(cacheKey2)?.profile ?? {}; } - async* _streamIterator(input, options) { - const streamEncoding = "version" in (options ?? {}) ? undefined : options?.encoding ?? undefined; - const streamSubgraphs = options?.subgraphs; - const inputConfig = ensureLangGraphConfig(this.config, options); - if (inputConfig.recursionLimit === undefined || inputConfig.recursionLimit < 1) - throw new Error(`Passed "recursionLimit" must be at least 1.`); - if (this.checkpointer !== undefined && this.checkpointer !== false && inputConfig.configurable === undefined) - throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); - const validInput = await this._validateInput(input); - const { runId, ...restConfig } = inputConfig; - const [debug, streamMode, , outputKeys, config2, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache2, durability] = this._defaults(restConfig); - config2.metadata = { - ls_integration: "langgraph", - ...config2.metadata - }; - if (typeof config2.context !== "undefined") - config2.context = await this._validateContext(config2.context); - else - config2.configurable = await this._validateContext(config2.configurable); - const stream2 = new IterableReadableWritableStream({ modes: new Set(streamMode) }); - if (this.checkpointer === true) { - config2.configurable ??= {}; - const ns3 = config2.configurable["checkpoint_ns"] ?? ""; - config2.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns3.split("|").map((part) => part.split(":")[0]).join("|"); - } - if (streamMode.includes("messages")) { - const messageStreamer = options?.version === "v3" ? new StreamProtocolMessagesHandler((chunk) => stream2.push(chunk)) : new StreamMessagesHandler((chunk) => stream2.push(chunk)); - const { callbacks } = config2; - if (callbacks === undefined) - config2.callbacks = [messageStreamer]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat(messageStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(messageStreamer, true); - config2.callbacks = copiedCallbacks; - } - } - if (streamMode.includes("tools")) { - const toolStreamer = new StreamToolsHandler((chunk) => stream2.push(chunk)); - const { callbacks } = config2; - if (callbacks === undefined) - config2.callbacks = [toolStreamer]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat(toolStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(toolStreamer, true); - config2.callbacks = copiedCallbacks; - } + _getCacheKey(config3) { + let toStringify = config3 ?? {}; + if (toStringify.configurable) { + const { configurable } = toStringify; + const filtered = {}; + for (const [k, v] of Object.entries(configurable)) + if (!k.startsWith("__pregel_")) + filtered[k] = v; + toStringify = { + ...toStringify, + configurable: filtered + }; } - config2.writer ??= (chunk) => { - if (!streamMode.includes("custom")) - return; - const ns3 = getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS]?.split("|").slice(0, -1); - stream2.push([ - ns3 ?? [], - "custom", - chunk - ]); - }; - config2.interrupt ??= this.userInterrupt ?? interrupt; - if (config2.serverInfo == null) - config2.serverInfo = _buildServerInfo(config2); - const callbackManagerOptions = { tracerInheritableMetadata: _getTracingMetadataDefaults(config2) }; - const runManager = await (await CallbackManager._configureSync(config2?.callbacks, undefined, config2?.tags, undefined, config2?.metadata, undefined, callbackManagerOptions))?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), runId, undefined, undefined, undefined, config2?.runName ?? this.getName()); - const channelSpecs = getOnlyChannels(this.channels); - let loop; - let loopError; - const createAndRunLoop = async () => { - try { - loop = await PregelLoop.initialize({ - input: validInput, - config: config2, - checkpointer, - nodes: this.nodes, - channelSpecs, - outputKeys, - streamKeys: this.streamChannelsAsIs, - store, - cache: cache2, - stream: stream2, - interruptAfter, - interruptBefore, - manager: runManager, - debug: this.debug, - triggerToNodes: this.triggerToNodes, - durability - }); - const runner = new PregelRunner({ - loop, - nodeFinished: config2.configurable?.[CONFIG_KEY_NODE_FINISHED] - }); - if (options?.subgraphs) - loop.config.configurable = { - ...loop.config.configurable, - [CONFIG_KEY_STREAM]: loop.stream - }; - await this._runLoop({ - loop, - runner, - debug, - config: config2 - }); - if (durability === "sync") - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = e; - } finally { - try { - if (loop) { - await loop.store?.stop(); - await loop.cache?.stop(); - } - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = loopError ?? e; - } - if (loopError) - stream2.error(loopError); - else - stream2.close(); - } - }; - const runLoopPromise = createAndRunLoop(); - try { - for await (const chunk of stream2) { - if (chunk === undefined) - throw new Error("Data structure error."); - const [namespace, mode, payload, meta3] = chunk; - if (streamMode.includes(mode)) { - if (streamEncoding === "text/event-stream") { - if (streamSubgraphs) - yield [ - namespace, - mode, - payload - ]; - else - yield [ - null, - mode, - payload - ]; - continue; - } - if (streamSubgraphs && !streamModeSingle) - yield meta3 !== undefined ? [ - namespace, - mode, - payload, - meta3 - ] : [ - namespace, - mode, - payload - ]; - else if (!streamModeSingle) - yield [mode, payload]; - else if (streamSubgraphs) - yield [namespace, payload]; - else - yield payload; - } - } - } catch (e) { - await runManager?.handleChainError(loopError); - throw e; - } finally { - await runLoopPromise; - } - await runManager?.handleChainEnd(loop?.output ?? {}, runId, undefined, undefined, undefined); - } - async invoke(input, options) { - const streamMode = options?.streamMode ?? "values"; - const config2 = { - ...options, - outputKeys: options?.outputKeys ?? this.outputChannels, - streamMode, - encoding: undefined - }; - const chunks = []; - const stream2 = await this.stream(input, config2); - const interruptChunks = []; - let latest; - for await (const chunk of stream2) - if (streamMode === "values") - if (isInterrupted(chunk)) - interruptChunks.push(chunk[INTERRUPT]); - else - latest = chunk; - else - chunks.push(chunk); - if (streamMode === "values") { - if (interruptChunks.length > 0) { - const interrupts = interruptChunks.flat(1); - if (latest == null) - return { [INTERRUPT]: interrupts }; - if (typeof latest === "object") - return { - ...latest, - [INTERRUPT]: interrupts - }; - } - return latest; - } - return chunks; - } - async _runLoop(params) { - const { loop, runner, debug, config: config2 } = params; - let tickError; - try { - while (await loop.tick({ inputKeys: this.inputChannels })) { - for (const { task } of await loop._matchCachedWrites()) - loop._outputWrites(task.id, task.writes, true); - if (debug) - printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); - if (debug) - printStepTasks(loop.step, Object.values(loop.tasks)); - await runner.tick({ - timeout: this.stepTimeout, - retryPolicy: this.retryPolicy, - onStepWrite: (step, writes) => { - if (debug) - printStepWrites(step, writes, this.streamChannelsList); - }, - maxConcurrency: config2.maxConcurrency, - signal: config2.signal - }); - } - if (loop.status === "out_of_steps") - throw new GraphRecursionError([ - `Recursion limit of ${config2.recursionLimit} reached`, - "without hitting a stop condition. You can increase the", - `limit by setting the "recursionLimit" config key.` - ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); - } catch (e) { - tickError = e; - if (!await loop.finishAndHandleError(tickError)) - throw e; - } finally { - if (tickError === undefined) - await loop.finishAndHandleError(); - } - } - async clearCache() { - await this.cache?.clear([]); - } - }; - OMITTED_KEYS = new Set([ - "key", - "token", - "secret", - "password", - "auth" - ]); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js -var EphemeralValue; -var init_ephemeral_value = __esm(() => { - init_errors5(); - init_base15(); - EphemeralValue = class EphemeralValue2 extends BaseChannel { - lc_graph_name = "EphemeralValue"; - guard; - value = []; - constructor(guard = true) { - super(); - this.guard = guard; - } - fromCheckpoint(checkpoint) { - const empty = new EphemeralValue2(this.guard); - if (typeof checkpoint !== "undefined") - empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - if (values.length !== 1 && this.guard) - throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) - throw new EmptyChannelError; - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) - throw new EmptyChannelError; - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/graph.js -function isCompiledGraph(x) { - return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; -} -function _escapeMermaidKeywords(key) { - if (key === "subgraph") - return `"${key}"`; - return key; -} -var Branch = class { - path; - ends; - constructor(options) { - if (Runnable.isRunnable(options.path)) - this.path = options.path; - else - this.path = _coerceToRunnable(options.path); - this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n3) => { - acc[n3] = n3; - return acc; - }, {}) : options.pathMap; - } - run(writer, reader) { - return ChannelWrite.registerWriter(new RunnableCallable({ - name: "", - trace: false, - func: async (input, config2) => { - try { - return await this._route(input, config2, writer, reader); - } catch (e) { - if (e.name === NodeInterrupt.unminifiable_name) - console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation. -NodeInterrupt should only be thrown inside a node, not in edge conditions.`); - throw e; - } - } - })); - } - async _route(input, config2, writer, reader) { - let result = await this.path.invoke(reader ? reader(config2) : input, config2); - if (!Array.isArray(result)) - result = [result]; - let destinations; - if (this.ends) - destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); - else - destinations = result; - if (destinations.some((dest) => !dest)) - throw new Error("Branch condition returned unknown or null destination"); - if (destinations.filter(_isSend).some((packet) => packet.node === "__end__")) - throw new InvalidUpdateError("Cannot send a packet to the END node"); - return await writer(destinations, config2) ?? input; - } -}, Graph$1 = class { - nodes; - edges; - branches; - entryPoint; - compiled = false; - constructor() { - this.nodes = {}; - this.edges = /* @__PURE__ */ new Set; - this.branches = {}; - } - warnIfCompiled(message) { - if (this.compiled) - console.warn(message); - } - get allEdges() { - return this.edges; - } - addNode(...args) { - function isMutlipleNodes(args2) { - return args2.length >= 1 && typeof args2[0] !== "string"; - } - const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) - throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - for (const reservedChar of ["|", ":"]) - if (key.includes(reservedChar)) - throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) - throw new Error(`Node \`${key}\` already present.`); - if (key === "__end__") - throw new Error(`Node \`${key}\` is reserved.`); - const runnable = _coerceToRunnable(action); - this.nodes[key] = { - runnable, - metadata: options?.metadata, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends - }; - } - return this; - } - addEdge(startKey, endKey) { - this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (startKey === "__end__") - throw new Error("END cannot be a start node"); - if (endKey === "__start__") - throw new Error("START cannot be an end node"); - if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) - throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); - this.edges.add([startKey, endKey]); - return this; - } - addConditionalEdges(source, path2, pathMap) { - const options = typeof source === "object" ? source : { - source, - path: path2, - pathMap - }; - this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - if (!Runnable.isRunnable(options.path)) - options.path = _coerceToRunnable(options.path); - const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); - if (this.branches[options.source] && this.branches[options.source][name]) - throw new Error(`Condition \`${name}\` already present for node \`${source}\``); - this.branches[options.source] ??= {}; - this.branches[options.source][name] = new Branch(options); - return this; - } - setEntryPoint(key) { - this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(START, key); - } - setFinishPoint(key) { - this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(key, END); - } - compile({ checkpointer, interruptBefore, interruptAfter, name, transformers } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const compiled = new CompiledGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - [START]: new EphemeralValue, - [END]: new EphemeralValue - }, - inputChannels: START, - outputChannels: END, - streamChannels: [], - streamMode: "values", - name, - streamTransformers: transformers - }); - for (const [key, node] of Object.entries(this.nodes)) - compiled.attachNode(key, node); - for (const [start, end] of this.edges) - compiled.attachEdge(start, end); - for (const [start, branches] of Object.entries(this.branches)) - for (const [name2, branch] of Object.entries(branches)) - compiled.attachBranch(start, name2, branch); - return compiled.validate(); - } - validate(interrupt2) { - const allSources = new Set([...this.allEdges].map(([src, _]) => src)); - for (const [start] of Object.entries(this.branches)) - allSources.add(start); - for (const source of allSources) - if (source !== "__start__" && !(source in this.nodes)) - throw new Error(`Found edge starting at unknown node \`${source}\``); - const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); - for (const [start, branches] of Object.entries(this.branches)) - for (const branch of Object.values(branches)) - if (branch.ends != null) - for (const end of Object.values(branch.ends)) - allTargets.add(end); - else { - allTargets.add(END); - for (const node of Object.keys(this.nodes)) - if (node !== start) - allTargets.add(node); - } - for (const node of Object.values(this.nodes)) - for (const target of node.ends ?? []) - allTargets.add(target); - for (const node of Object.keys(this.nodes)) - if (!allTargets.has(node)) - throw new UnreachableNodeError([ - `Node \`${node}\` is not reachable.`, - "", - "If you are returning Command objects from your node,", - 'make sure you are passing names of potential destination nodes as an "ends" array', - 'into ".addNode(..., { ends: ["node1", "node2"] })".' - ].join(` -`), { lc_error_code: "UNREACHABLE_NODE" }); - for (const target of allTargets) - if (target !== "__end__" && !(target in this.nodes)) - throw new Error(`Found edge ending at unknown node \`${target}\``); - if (interrupt2) { - for (const node of interrupt2) - if (!(node in this.nodes)) - throw new Error(`Interrupt node \`${node}\` is not present`); - } - this.compiled = true; - } -}, CompiledGraph; -var init_graph2 = __esm(() => { - init_constants3(); - init_errors5(); - init_utils8(); - init_write(); - init_read(); - init_subgraph(); - init_pregel(); - init_ephemeral_value(); - init_runnables(); - init_graph(); - init_v43(); - init_wrapper(); - CompiledGraph = class extends Pregel { - builder; - constructor({ builder, ...rest }) { - super(rest); - this.builder = builder; - } - withConfig(config2) { - return super.withConfig(config2); - } - attachNode(key, node) { - this.channels[key] = new EphemeralValue; - this.nodes[key] = new PregelNode({ - channels: [], - triggers: [], - metadata: node.metadata, - subgraphs: node.subgraphs, - ends: node.ends - }).pipe(node.runnable).pipe(new ChannelWrite([{ - channel: key, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - this.streamChannels.push(key); - } - attachEdge(start, end) { - if (end === "__end__") { - if (start === "__start__") - throw new Error("Cannot have an edge from START to END"); - this.nodes[start].writers.push(new ChannelWrite([{ - channel: END, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - } else { - this.nodes[end].triggers.push(start); - this.nodes[end].channels.push(start); - } - } - attachBranch(start, name, branch) { - if (start === "__start__" && !this.nodes["__start__"]) - this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); - this.nodes[start].pipe(branch.run((dests) => { - return new ChannelWrite(dests.map((dest) => { - if (_isSend(dest)) - return dest; - return { - channel: dest === "__end__" ? END : `branch:${start}:${name}:${dest}`, - value: PASSTHROUGH - }; - }), [TAG_HIDDEN]); - })); - const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); - for (const end of ends) - if (end !== "__end__") { - const channelName = `branch:${start}:${name}:${end}`; - this.channels[channelName] = new EphemeralValue; - this.nodes[end].triggers.push(channelName); - this.nodes[end].channels.push(channelName); - } - } - async getGraphAsync(config2) { - const xray = config2?.xray; - const graph = new Graph; - const startNodes = { [START]: graph.addNode({ schema: exports_external.any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) - subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === "__end__" && endNodes["__end__"] === undefined) - endNodes[END] = graph.addNode({ schema: exports_external.any() }, END); - if (startNodes[start] === undefined) - return; - if (endNodes[end] === undefined) - throw new Error(`End node ${end} not found!`); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) - metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) - metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) - metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== undefined ? await subgraphs[key].getGraphAsync({ - ...config2, - xray: newXrayValue - }) : node.getGraph(config2); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - let _isRunnableInterface = function(thing) { - return thing ? thing.lc_runnable : false; - }, _nodeDataStr = function(id, data) { - if (id !== undefined && !validate7(id)) - return id; - else if (_isRunnableInterface(data)) - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); - } - else - return data.name ?? "UnknownSchema"; - }; - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === undefined) - throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - if (s !== undefined) - startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) - return -1; - else if (b > a) - return 1; - else - return 0; - }); - for (const [start, end] of sortedEdges) - addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== undefined) - ends = branch.ends; - else - ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) - addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - for (const [key, node] of Object.entries(this.builder.nodes)) - if (node.ends !== undefined) - for (const end of node.ends) - addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), undefined, true); - return graph; - } - getGraph(config2) { - const xray = config2?.xray; - const graph = new Graph; - const startNodes = { [START]: graph.addNode({ schema: exports_external.any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) - subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === "__end__" && endNodes["__end__"] === undefined) - endNodes[END] = graph.addNode({ schema: exports_external.any() }, END); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) - metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) - metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) - metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== undefined ? subgraphs[key].getGraph({ - ...config2, - xray: newXrayValue - }) : node.getGraph(config2); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - let _isRunnableInterface = function(thing) { - return thing ? thing.lc_runnable : false; - }, _nodeDataStr = function(id, data) { - if (id !== undefined && !validate7(id)) - return id; - else if (_isRunnableInterface(data)) - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); - } - else - return data.name ?? "UnknownSchema"; - }; - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === undefined) - throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - if (s !== undefined) - startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) - return -1; - else if (b > a) - return 1; - else - return 0; - }); - for (const [start, end] of sortedEdges) - addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== undefined) - ends = branch.ends; - else - ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) - addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - return graph; + return JSON.stringify(toStringify); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/types.js -function isStandardSchema2(schema) { - return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; -} -function isStandardJSONSchema(schema) { - return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tools/types.js +function isStructuredTool(tool) { + return tool !== undefined && Array.isArray(tool.lc_namespace); } -function isSerializableSchema2(schema) { - return isStandardSchema2(schema) && isStandardJSONSchema(schema); +function isRunnableToolLike(tool) { + return tool !== undefined && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; } -var init_types8 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/adapter.js -function getJsonSchemaFromSchema(schema) { - if (isStandardJSONSchema(schema)) - try { - return schema["~standard"].jsonSchema.input({ target: "draft-07" }); - } catch { - return; - } +function isStructuredToolParams(tool) { + return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && ("type" in tool.schema) && typeof tool.schema.type === "string" && [ + "null", + "boolean", + "object", + "array", + "number", + "string" + ].includes(tool.schema.type)); } -function getSchemaDefaultGetter(schema) { - if (schema == null) - return; - if (!isStandardSchema2(schema)) - return; - try { - const result = schema["~standard"].validate(undefined); - if (result && typeof result === "object" && !(("then" in result) && typeof result.then === "function")) { - const syncResult = result; - if (!syncResult.issues) { - const defaultValue = syncResult.value; - return () => defaultValue; - } - } - } catch {} +function isLangChainTool(tool) { + return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); } -var init_adapter = __esm(() => { - init_types8(); +var init_types4 = __esm(() => { + init_zod2(); + init_base4(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/untracked_value.js -var MISSING, UntrackedValueChannel; -var init_untracked_value = __esm(() => { - init_errors5(); - init_base15(); - MISSING = Symbol.for("langgraph.channel.missing"); - UntrackedValueChannel = class UntrackedValueChannel2 extends BaseChannel { - lc_graph_name = "UntrackedValue"; - guard; - _value = MISSING; - initialValueFactory; - constructor(options) { - super(); - this.guard = options?.guard ?? true; - this.initialValueFactory = options?.initialValueFactory; - if (this.initialValueFactory) - this._value = this.initialValueFactory(); - } - fromCheckpoint(_checkpoint) { - return new UntrackedValueChannel2({ - guard: this.guard, - initialValueFactory: this.initialValueFactory - }); - } - update(values) { - if (values.length === 0) - return false; - if (values.length !== 1 && this.guard) - throw new InvalidUpdateError("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this._value = values[values.length - 1]; - return true; - } - get() { - if (this._value === MISSING) - throw new EmptyChannelError; - return this._value; - } - checkpoint() {} - isAvailable() { - return this._value !== MISSING; - } - }; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/checks.js +var init_checks4 = __esm(() => { + init_core4(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/values/reduced.js -var REDUCED_VALUE_SYMBOL, ReducedValue; -var init_reduced = __esm(() => { - REDUCED_VALUE_SYMBOL = Symbol.for("langgraph.state.reduced_value"); - ReducedValue = class { - [REDUCED_VALUE_SYMBOL] = true; - valueSchema; - inputSchema; - reducer; - jsonSchemaExtra; - constructor(valueSchema, init) { - this.reducer = init.reducer; - this.jsonSchemaExtra = init.jsonSchemaExtra; - this.valueSchema = valueSchema; - this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; - this.jsonSchemaExtra = init.jsonSchemaExtra; - } - static isInstance(value) { - return typeof value === "object" && value !== null && REDUCED_VALUE_SYMBOL in value && value[REDUCED_VALUE_SYMBOL] === true; - } - }; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js +var exports_iso2 = {}; +__export(exports_iso2, { + time: () => time5, + duration: () => duration4, + datetime: () => datetime4, + date: () => date7, + ZodISOTime: () => ZodISOTime2, + ZodISODuration: () => ZodISODuration2, + ZodISODateTime: () => ZodISODateTime2, + ZodISODate: () => ZodISODate2 }); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/values/untracked.js -var UNTRACKED_VALUE_SYMBOL, UntrackedValue; -var init_untracked = __esm(() => { - UNTRACKED_VALUE_SYMBOL = Symbol.for("langgraph.state.untracked_value"); - UntrackedValue = class { - [UNTRACKED_VALUE_SYMBOL] = true; - schema; - guard; - constructor(schema, init) { - this.schema = schema; - this.guard = init?.guard ?? true; - } - static isInstance(value) { - return typeof value === "object" && value !== null && UNTRACKED_VALUE_SYMBOL in value; - } - }; +function datetime4(params) { + return _isoDateTime2(ZodISODateTime2, params); +} +function date7(params) { + return _isoDate2(ZodISODate2, params); +} +function time5(params) { + return _isoTime2(ZodISOTime2, params); +} +function duration4(params) { + return _isoDuration2(ZodISODuration2, params); +} +var ZodISODateTime2, ZodISODate2, ZodISOTime2, ZodISODuration2; +var init_iso2 = __esm(() => { + init_core4(); + init_schemas4(); + ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => { + $ZodISODateTime2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => { + $ZodISODate2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => { + $ZodISOTime2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => { + $ZodISODuration2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js -var areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)), NamedBarrierValue, NamedBarrierValueAfterFinish; -var init_named_barrier_value = __esm(() => { - init_errors5(); - init_base15(); - NamedBarrierValue = class NamedBarrierValue2 extends BaseChannel { - lc_graph_name = "NamedBarrierValue"; - names; - seen; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set; - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValue2(this.names); - if (typeof checkpoint !== "undefined") - empty.seen = new Set(checkpoint); - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) - if (this.names.has(nodeName)) { - if (!this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } - } else - throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!areSetsEqual(this.names, this.seen)) - throw new EmptyChannelError; - } - checkpoint() { - return [...this.seen]; - } - consume() { - if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set; - return true; - } - return false; - } - isAvailable() { - return !!this.names && areSetsEqual(this.names, this.seen); - } - }; - NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish2 extends BaseChannel { - lc_graph_name = "NamedBarrierValueAfterFinish"; - names; - seen; - finished; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set; - this.finished = false; - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValueAfterFinish2(this.names); - if (typeof checkpoint !== "undefined") { - const [seen, finished] = checkpoint; - empty.seen = new Set(seen); - empty.finished = finished; - } - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) - if (this.names.has(nodeName) && !this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } else if (!this.names.has(nodeName)) - throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!this.finished || !areSetsEqual(this.names, this.seen)) - throw new EmptyChannelError; - } - checkpoint() { - return [[...this.seen], this.finished]; - } - consume() { - if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set; - this.finished = false; - return true; - } - return false; - } - finish() { - if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { - this.finished = true; - return true; +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js +var initializer4 = (inst, issues) => { + $ZodError2.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError3(inst, mapper) + }, + flatten: { + value: (mapper) => flattenError2(inst, mapper) + }, + addIssue: { + value: (issue3) => inst.issues.push(issue3) + }, + addIssues: { + value: (issues2) => inst.issues.push(...issues2) + }, + isEmpty: { + get() { + return inst.issues.length === 0; } - return false; - } - isAvailable() { - return this.finished && !!this.names && areSetsEqual(this.names, this.seen); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/any_value.js -var init_any_value = __esm(() => { - init_errors5(); - init_base15(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js -var init_dynamic_barrier_value = __esm(() => { - init_errors5(); - init_base15(); - init_named_barrier_value(); + }); +}, ZodError4, ZodRealError2; +var init_errors6 = __esm(() => { + init_core4(); + init_core4(); + ZodError4 = $constructor2("ZodError", initializer4); + ZodRealError2 = $constructor2("ZodError", initializer4, { + Parent: Error + }); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/channels/index.js -var init_channels = __esm(() => { - init_base15(); - init_binop(); - init_last_value(); - init_topic(); - init_ephemeral_value(); - init_named_barrier_value(); - init_any_value(); - init_dynamic_barrier_value(); - init_untracked_value(); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js +var parse11, parseAsync4, safeParse4, safeParseAsync4; +var init_parse6 = __esm(() => { + init_core4(); + init_errors6(); + parse11 = /* @__PURE__ */ _parse2(ZodRealError2); + parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2); + safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2); + safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/schema.js -var STATE_SCHEMA_SYMBOL, StateSchema; -var init_schema = __esm(() => { - init_binop(); - init_last_value(); - init_types8(); - init_adapter(); - init_untracked_value(); - init_channels(); - init_reduced(); - init_untracked(); - STATE_SCHEMA_SYMBOL = Symbol.for("langgraph.state.state_schema"); - StateSchema = class { - [STATE_SCHEMA_SYMBOL] = true; - constructor(fields) { - this.fields = fields; - } - getChannels() { - const channels = {}; - for (const [key, value] of Object.entries(this.fields)) - if (ReducedValue.isInstance(value)) { - const defaultGetter = getSchemaDefaultGetter(value.valueSchema); - channels[key] = new BinaryOperatorAggregate(value.reducer, defaultGetter); - } else if (UntrackedValue.isInstance(value)) { - const defaultGetter = value.schema ? getSchemaDefaultGetter(value.schema) : undefined; - channels[key] = new UntrackedValueChannel({ - guard: value.guard, - initialValueFactory: defaultGetter - }); - } else if (isStandardSchema2(value)) - channels[key] = new LastValue(getSchemaDefaultGetter(value)); - else - throw new Error(`Invalid state field "${key}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`); - return channels; - } - getJsonSchema() { - const properties = {}; - const required2 = []; - for (const [key, value] of Object.entries(this.fields)) { - let fieldSchema; - if (ReducedValue.isInstance(value)) { - fieldSchema = getJsonSchemaFromSchema(value.valueSchema); - if (value.jsonSchemaExtra) - fieldSchema = { - ...fieldSchema ?? {}, - ...value.jsonSchemaExtra - }; - } else if (UntrackedValue.isInstance(value)) - fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : undefined; - else if (isStandardSchema2(value)) - fieldSchema = getJsonSchemaFromSchema(value); - if (fieldSchema) { - properties[key] = fieldSchema; - let hasDefault = false; - if (ReducedValue.isInstance(value)) - hasDefault = getSchemaDefaultGetter(value.valueSchema) !== undefined; - else if (UntrackedValue.isInstance(value)) - hasDefault = value.schema ? getSchemaDefaultGetter(value.schema) !== undefined : false; - else - hasDefault = getSchemaDefaultGetter(value) !== undefined; - if (!hasDefault) - required2.push(key); - } - } - return { - type: "object", - properties, - required: required2.length > 0 ? required2 : undefined - }; - } - getInputJsonSchema() { - const properties = {}; - for (const [key, value] of Object.entries(this.fields)) { - let fieldSchema; - if (ReducedValue.isInstance(value)) { - fieldSchema = getJsonSchemaFromSchema(value.inputSchema); - if (value.jsonSchemaExtra) - fieldSchema = { - ...fieldSchema ?? {}, - ...value.jsonSchemaExtra - }; - } else if (UntrackedValue.isInstance(value)) - fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : undefined; - else if (isStandardSchema2(value)) - fieldSchema = getJsonSchemaFromSchema(value); - if (fieldSchema) - properties[key] = fieldSchema; - } - return { - type: "object", - properties - }; - } - getChannelKeys() { - return Object.entries(this.fields).map(([key]) => key); - } - getAllKeys() { - return Object.keys(this.fields); - } - async validateInput(data) { - if (data == null || typeof data !== "object") - return data; - const result = {}; - for (const [key, value] of Object.entries(data)) { - const fieldDef = this.fields[key]; - if (fieldDef === undefined) { - result[key] = value; - continue; - } - let schema; - if (ReducedValue.isInstance(fieldDef)) - schema = fieldDef.inputSchema; - else if (UntrackedValue.isInstance(fieldDef)) - schema = fieldDef.schema; - else if (isStandardSchema2(fieldDef)) - schema = fieldDef; - if (schema) { - const validationResult = await schema["~standard"].validate(value); - if (validationResult.issues) - throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); - result[key] = validationResult.value; - } else - result[key] = value; - } - return result; - } - static isInstance(value) { - return typeof value === "object" && value !== null && STATE_SCHEMA_SYMBOL in value && value[STATE_SCHEMA_SYMBOL] === true; - } +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js +function string5(params) { + return _string2(ZodString3, params); +} +function email4(params) { + return _email2(ZodEmail2, params); +} +function guid4(params) { + return _guid2(ZodGUID2, params); +} +function uuid5(params) { + return _uuid2(ZodUUID2, params); +} +function uuidv42(params) { + return _uuidv42(ZodUUID2, params); +} +function uuidv62(params) { + return _uuidv62(ZodUUID2, params); +} +function uuidv72(params) { + return _uuidv72(ZodUUID2, params); +} +function url2(params) { + return _url2(ZodURL2, params); +} +function emoji4(params) { + return _emoji4(ZodEmoji2, params); +} +function nanoid4(params) { + return _nanoid2(ZodNanoID2, params); +} +function cuid6(params) { + return _cuid3(ZodCUID3, params); +} +function cuid24(params) { + return _cuid22(ZodCUID22, params); +} +function ulid4(params) { + return _ulid2(ZodULID2, params); +} +function xid4(params) { + return _xid2(ZodXID2, params); +} +function ksuid4(params) { + return _ksuid2(ZodKSUID2, params); +} +function ipv44(params) { + return _ipv42(ZodIPv42, params); +} +function ipv64(params) { + return _ipv62(ZodIPv62, params); +} +function cidrv44(params) { + return _cidrv42(ZodCIDRv42, params); +} +function cidrv64(params) { + return _cidrv62(ZodCIDRv62, params); +} +function base645(params) { + return _base642(ZodBase642, params); +} +function base64url4(params) { + return _base64url2(ZodBase64URL2, params); +} +function e1644(params) { + return _e1642(ZodE1642, params); +} +function jwt2(params) { + return _jwt2(ZodJWT2, params); +} +function stringFormat2(format3, fnOrRegex, _params = {}) { + return _stringFormat2(ZodCustomStringFormat2, format3, fnOrRegex, _params); +} +function number5(params) { + return _number2(ZodNumber3, params); +} +function int2(params) { + return _int2(ZodNumberFormat2, params); +} +function float322(params) { + return _float322(ZodNumberFormat2, params); +} +function float642(params) { + return _float642(ZodNumberFormat2, params); +} +function int322(params) { + return _int322(ZodNumberFormat2, params); +} +function uint322(params) { + return _uint322(ZodNumberFormat2, params); +} +function boolean5(params) { + return _boolean2(ZodBoolean3, params); +} +function bigint5(params) { + return _bigint2(ZodBigInt3, params); +} +function int642(params) { + return _int642(ZodBigIntFormat2, params); +} +function uint642(params) { + return _uint642(ZodBigIntFormat2, params); +} +function symbol2(params) { + return _symbol2(ZodSymbol3, params); +} +function _undefined6(params) { + return _undefined5(ZodUndefined3, params); +} +function _null6(params) { + return _null5(ZodNull3, params); +} +function any2() { + return _any2(ZodAny3); +} +function unknown2() { + return _unknown2(ZodUnknown3); +} +function never2(params) { + return _never2(ZodNever3, params); +} +function _void4(params) { + return _void3(ZodVoid3, params); +} +function date8(params) { + return _date2(ZodDate3, params); +} +function array2(element, params) { + return _array2(ZodArray3, element, params); +} +function keyof2(schema) { + const shape = schema._zod.def.shape; + return literal2(Object.keys(shape)); +} +function object2(shape, params) { + const def = { + type: "object", + get shape() { + exports_util2.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...exports_util2.normalizeParams(params) }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/messages_reducer.js -function messagesStateReducer(left, right) { - const leftArray = Array.isArray(left) ? left : [left]; - const rightArray = Array.isArray(right) ? right : [right]; - const leftMessages = leftArray.map(coerceMessageLikeToMessage); - const rightMessages = rightArray.map(coerceMessageLikeToMessage); - for (const m of leftMessages) - if (m.id === null || m.id === undefined) { - m.id = v43(); - m.lc_kwargs.id = m.id; - } - let removeAllIdx; - for (let i = 0;i < rightMessages.length; i += 1) { - const m = rightMessages[i]; - if (m.id === null || m.id === undefined) { - m.id = v43(); - m.lc_kwargs.id = m.id; - } - if (RemoveMessage.isInstance(m) && m.id === "__remove_all__") - removeAllIdx = i; - } - if (removeAllIdx != null) - return rightMessages.slice(removeAllIdx + 1); - const merged = [...leftMessages]; - const mergedById = new Map(merged.map((m, i) => [m.id, i])); - const idsToRemove = /* @__PURE__ */ new Set; - for (const m of rightMessages) { - const existingIdx = mergedById.get(m.id); - if (existingIdx !== undefined) - if (RemoveMessage.isInstance(m)) - idsToRemove.add(m.id); - else { - idsToRemove.delete(m.id); - merged[existingIdx] = m; - } - else { - if (RemoveMessage.isInstance(m)) - throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); - mergedById.set(m.id, merged.length); - merged.push(m); - } - } - return merged.filter((m) => !idsToRemove.has(m.id)); + return new ZodObject3(def); } -var REMOVE_ALL_MESSAGES = "__remove_all__"; -var init_messages_reducer = __esm(() => { - init_wrapper(); - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/prebuilt/messages.js -var MessagesValue; -var init_messages4 = __esm(() => { - init_reduced(); - init_messages_reducer(); - init_v43(); - MessagesValue = new ReducedValue(exports_external.custom().default(() => []), { - inputSchema: exports_external.custom(), - reducer: messagesStateReducer, - jsonSchemaExtra: { - langgraph_type: "messages", - description: "A list of chat messages" - } +function strictObject2(shape, params) { + return new ZodObject3({ + type: "object", + get shape() { + exports_util2.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: never2(), + ...exports_util2.normalizeParams(params) }); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/prebuilt/index.js -var init_prebuilt = __esm(() => { - init_messages4(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/values/index.js -var init_values2 = __esm(() => { - init_reduced(); - init_untracked(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/state/index.js -var init_state = __esm(() => { - init_types8(); - init_adapter(); - init_reduced(); - init_untracked(); - init_schema(); - init_messages4(); - init_prebuilt(); - init_values2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/zod/meta.js -function withLangGraph(schema, meta3) { - if (meta3.reducer && !meta3.default) { - const defaultValueGetter = getInteropZodDefaultGetter(schema); - if (defaultValueGetter != null) - meta3.default = defaultValueGetter; - } - if (meta3.reducer) { - const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta3.reducer?.schema ?? schema }); - schemaMetaRegistry.extend(schemaWithReducer, () => meta3); - return schemaWithReducer; - } else { - schemaMetaRegistry.extend(schema, () => meta3); - return schema; - } } -var SchemaMetaRegistry = class { - _map = /* @__PURE__ */ new Map; - _extensionCache = /* @__PURE__ */ new Map; - get(schema) { - return this._map.get(schema); - } - extend(schema, predicate) { - const existingMeta = this.get(schema); - this._map.set(schema, predicate(existingMeta)); - } - remove(schema) { - this._map.delete(schema); - return this; - } - has(schema) { - return this._map.has(schema); - } - getChannelsForSchema(schema) { - const channels = {}; - const shape = getInteropZodObjectShape(schema); - for (const [key, channelSchema] of Object.entries(shape)) { - const meta3 = this.get(channelSchema); - if (meta3?.reducer) - channels[key] = new BinaryOperatorAggregate(meta3.reducer.fn, meta3.default); - else - channels[key] = new LastValue(meta3?.default); - } - return channels; - } - getExtendedChannelSchemas(schema, effects) { - if (Object.keys(effects).length === 0) - return schema; - const cacheKey2 = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); - const cache2 = this._extensionCache.get(cacheKey2) ?? /* @__PURE__ */ new Map; - if (cache2.has(schema)) - return cache2.get(schema); - let modifiedSchema = schema; - if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { - const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema2]) => { - const meta3 = this.get(schema2); - let outputSchema = effects.withReducerSchema ? meta3?.reducer?.schema ?? schema2 : schema2; - if (effects.withJsonSchemaExtrasAsDescription && meta3?.jsonSchemaExtra) { - const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema2); - const strExtras = JSON.stringify({ - ...meta3.jsonSchemaExtra, - description - }); - outputSchema = outputSchema.describe(`lg:${strExtras}`); - } - return [key, outputSchema]; - }); - modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); - if (isZodSchemaV3(modifiedSchema)) - modifiedSchema._def.unknownKeys = "strip"; - } - if (effects.asPartial) - modifiedSchema = interopZodObjectPartial(modifiedSchema); - cache2.set(schema, modifiedSchema); - this._extensionCache.set(cacheKey2, cache2); - return modifiedSchema; - } -}, schemaMetaRegistry; -var init_meta = __esm(() => { - init_binop(); - init_last_value(); - init_types3(); - schemaMetaRegistry = new SchemaMetaRegistry; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/types.js -function isStateDefinitionInit(value) { - if (value == null) - return false; - if (StateSchema.isInstance(value)) - return true; - if (isInteropZodObject(value)) - return true; - if (typeof value === "object" && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot") - return true; - if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.values(value).every((v) => typeof v === "function" || isBaseChannel(v))) - return true; - return false; +function looseObject2(shape, params) { + return new ZodObject3({ + type: "object", + get shape() { + exports_util2.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown2(), + ...exports_util2.normalizeParams(params) + }); } -function isStateGraphInit(value) { - if (typeof value !== "object" || value == null) - return false; - const obj = value; - const hasState = "state" in obj && isStateDefinitionInit(obj.state); - const hasStateSchema = "stateSchema" in obj && isStateDefinitionInit(obj.stateSchema); - const hasInput = "input" in obj && isStateDefinitionInit(obj.input); - if (!hasState && !hasStateSchema && !hasInput) - return false; - if ("input" in obj && obj.input != null && !isStateDefinitionInit(obj.input)) - return false; - if ("output" in obj && obj.output != null && !isStateDefinitionInit(obj.output)) - return false; - return true; +function union2(options, params) { + return new ZodUnion3({ + type: "union", + options, + ...exports_util2.normalizeParams(params) + }); } -var init_types9 = __esm(() => { - init_constants3(); - init_base15(); - init_schema(); - init_types3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/state.js -function _getChannels(schema) { - const channels = {}; - for (const [name, val] of Object.entries(schema)) - if (name === ROOT2) - channels[name] = getChannel(val); - else - channels[name] = getChannel(val); - return channels; +function discriminatedUnion2(discriminator, options, params) { + return new ZodDiscriminatedUnion3({ + type: "union", + options, + discriminator, + ...exports_util2.normalizeParams(params) + }); } -function isStateGraphArgs(obj) { - return typeof obj === "object" && obj !== null && obj.channels !== undefined; +function intersection2(left, right) { + return new ZodIntersection3({ + type: "intersection", + left, + right + }); } -function _controlBranch(value) { - if (_isSend(value)) - return [value]; - const commands = []; - if (isCommand(value)) - commands.push(value); - else if (Array.isArray(value)) - commands.push(...value.filter(isCommand)); - const destinations = []; - for (const command of commands) { - if (command.graph === Command.PARENT) - throw new ParentCommand(command); - if (_isSend(command.goto)) - destinations.push(command.goto); - else if (typeof command.goto === "string") - destinations.push(command.goto); - else if (Array.isArray(command.goto)) - destinations.push(...command.goto); - } - return destinations; +function tuple2(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType2; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple3({ + type: "tuple", + items, + rest, + ...exports_util2.normalizeParams(params) + }); } -function _getControlBranch() { - return new Branch({ path: new RunnableCallable({ - func: _controlBranch, - tags: [TAG_HIDDEN], - trace: false, - recurse: false, - name: "" - }) }); +function record2(keyType, valueType, params) { + return new ZodRecord3({ + type: "record", + keyType, + valueType, + ...exports_util2.normalizeParams(params) + }); } -var ROOT2 = "__root__", PartialStateSchema, StateGraph, CompiledStateGraph; -var init_state2 = __esm(() => { - init_constants3(); - init_errors5(); - init_last_value(); - init_annotation(); - init_utils8(); - init_write(); - init_read(); - init_subgraph(); - init_ephemeral_value(); - init_graph2(); - init_named_barrier_value(); - init_schema(); - init_state(); - init_meta(); - init_types9(); - init_runnables(); - init_types3(); - PartialStateSchema = Symbol.for("langgraph.state.partial"); - StateGraph = class extends Graph$1 { - channels = {}; - waitingEdges = /* @__PURE__ */ new Set; - _schemaDefinition; - _schemaRuntimeDefinition; - _inputDefinition; - _inputRuntimeDefinition; - _outputDefinition; - _outputRuntimeDefinition; - _schemaDefinitions = /* @__PURE__ */ new Map; - _metaRegistry = schemaMetaRegistry; - _configSchema; - _configRuntimeSchema; - _interrupt; - _writer; - constructor(stateOrInit, options) { - super(); - const init = this._normalizeToStateGraphInit(stateOrInit, options); - const stateSchema = init.state ?? init.stateSchema ?? init.input; - if (!stateSchema) - throw new StateGraphInputError; - const stateChannelDef = this._getChannelsFromSchema(stateSchema); - this._schemaDefinition = stateChannelDef; - if (StateSchema.isInstance(stateSchema)) - this._schemaRuntimeDefinition = stateSchema; - else if (isInteropZodObject(stateSchema)) - this._schemaRuntimeDefinition = stateSchema; - if (init.input) - if (StateSchema.isInstance(init.input)) - this._inputRuntimeDefinition = init.input; - else if (isInteropZodObject(init.input)) - this._inputRuntimeDefinition = init.input; - else - this._inputRuntimeDefinition = PartialStateSchema; - else - this._inputRuntimeDefinition = PartialStateSchema; - if (init.output) - if (StateSchema.isInstance(init.output)) - this._outputRuntimeDefinition = init.output; - else if (isInteropZodObject(init.output)) - this._outputRuntimeDefinition = init.output; - else - this._outputRuntimeDefinition = this._schemaRuntimeDefinition; - else - this._outputRuntimeDefinition = this._schemaRuntimeDefinition; - const inputChannelDef = init.input ? this._getChannelsFromSchema(init.input) : stateChannelDef; - const outputChannelDef = init.output ? this._getChannelsFromSchema(init.output) : stateChannelDef; - this._inputDefinition = inputChannelDef; - this._outputDefinition = outputChannelDef; - this._addSchema(this._schemaDefinition); - this._addSchema(this._inputDefinition); - this._addSchema(this._outputDefinition); - if (init.context) { - if (isInteropZodObject(init.context)) - this._configRuntimeSchema = init.context; - } - this._interrupt = init.interrupt; - this._writer = init.writer; - } - _normalizeToStateGraphInit(stateOrInit, options) { - if (isStateGraphInit(stateOrInit)) { - if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) - return { - ...stateOrInit, - context: options - }; - const opts = options; - return { - ...stateOrInit, - input: stateOrInit.input ?? opts?.input, - output: stateOrInit.output ?? opts?.output, - context: stateOrInit.context ?? opts?.context, - interrupt: stateOrInit.interrupt ?? opts?.interrupt, - writer: stateOrInit.writer ?? opts?.writer, - nodes: stateOrInit.nodes ?? opts?.nodes - }; - } - if (isStateDefinitionInit(stateOrInit)) { - if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) - return { - state: stateOrInit, - context: options - }; - const opts = options; - return { - state: stateOrInit, - input: opts?.input, - output: opts?.output, - context: opts?.context, - interrupt: opts?.interrupt, - writer: opts?.writer, - nodes: opts?.nodes - }; - } - if (isStateGraphArgs(stateOrInit)) - return { state: _getChannels(stateOrInit.channels) }; - throw new StateGraphInputError; - } - _getChannelsFromSchema(schema) { - if (StateSchema.isInstance(schema)) - return schema.getChannels(); - if (isInteropZodObject(schema)) - return this._metaRegistry.getChannelsForSchema(schema); - if (typeof schema === "object" && "lc_graph_name" in schema && schema.lc_graph_name === "AnnotationRoot") - return schema.spec; - if (typeof schema === "object" && !Array.isArray(schema) && Object.keys(schema).length > 0) - return schema; - throw new StateGraphInputError("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition."); - } - get allEdges() { - return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); - } - _addSchema(stateDefinition) { - if (this._schemaDefinitions.has(stateDefinition)) - return; - this._schemaDefinitions.set(stateDefinition, stateDefinition); - for (const [key, val] of Object.entries(stateDefinition)) { - let channel; - if (typeof val === "function") - channel = val(); - else - channel = val; - if (this.channels[key] !== undefined) { - if (!this.channels[key].equals(channel)) { - if (channel.lc_graph_name !== "LastValue") - throw new Error(`Channel "${key}" already exists with a different type.`); - } - } else - this.channels[key] = channel; - } - } - addNode(...args) { - function isMultipleNodes(args2) { - return args2.length >= 1 && typeof args2[0] !== "string"; - } - const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) - throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - if (key in this.channels) - throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); - for (const reservedChar of ["|", ":"]) - if (key.includes(reservedChar)) - throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) - throw new Error(`Node \`${key}\` already present.`); - if (key === "__end__" || key === "__start__") - throw new Error(`Node \`${key}\` is reserved.`); - let inputSpec = this._schemaDefinition; - if (options?.input !== undefined) - inputSpec = this._getChannelsFromSchema(options.input); - this._addSchema(inputSpec); - let runnable; - if (Runnable.isRunnable(action)) - runnable = action; - else if (typeof action === "function") - runnable = new RunnableCallable({ - func: action, - name: key, - trace: false - }); - else - runnable = _coerceToRunnable(action); - let cachePolicy = options?.cachePolicy; - if (typeof cachePolicy === "boolean") - cachePolicy = cachePolicy ? {} : undefined; - const nodeSpec = { - runnable, - retryPolicy: options?.retryPolicy, - cachePolicy, - metadata: options?.metadata, - input: inputSpec ?? this._schemaDefinition, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends, - defer: options?.defer - }; - this.nodes[key] = nodeSpec; - } - return this; +function partialRecord2(keyType, valueType, params) { + return new ZodRecord3({ + type: "record", + keyType: union2([keyType, never2()]), + valueType, + ...exports_util2.normalizeParams(params) + }); +} +function map2(keyType, valueType, params) { + return new ZodMap3({ + type: "map", + keyType, + valueType, + ...exports_util2.normalizeParams(params) + }); +} +function set2(valueType, params) { + return new ZodSet3({ + type: "set", + valueType, + ...exports_util2.normalizeParams(params) + }); +} +function _enum4(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum3({ + type: "enum", + entries, + ...exports_util2.normalizeParams(params) + }); +} +function nativeEnum2(entries, params) { + return new ZodEnum3({ + type: "enum", + entries, + ...exports_util2.normalizeParams(params) + }); +} +function literal2(value, params) { + return new ZodLiteral3({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...exports_util2.normalizeParams(params) + }); +} +function file2(params) { + return _file2(ZodFile2, params); +} +function transform2(fn) { + return new ZodTransform2({ + type: "transform", + transform: fn + }); +} +function optional2(innerType) { + return new ZodOptional3({ + type: "optional", + innerType + }); +} +function nullable2(innerType) { + return new ZodNullable3({ + type: "nullable", + innerType + }); +} +function nullish4(innerType) { + return optional2(nullable2(innerType)); +} +function _default4(innerType, defaultValue) { + return new ZodDefault3({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; } - addEdge(startKey, endKey) { - if (typeof startKey === "string") - return super.addEdge(startKey, endKey); - if (this.compiled) - console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - for (const start of startKey) { - if (start === "__end__") - throw new Error("END cannot be a start node"); - if (!Object.keys(this.nodes).some((node) => node === start)) - throw new Error(`Need to add a node named "${start}" first`); - } - if (endKey === "__end__") - throw new Error("END cannot be an end node"); - if (!Object.keys(this.nodes).some((node) => node === endKey)) - throw new Error(`Need to add a node named "${endKey}" first`); - this.waitingEdges.add([startKey, endKey]); - return this; + }); +} +function prefault2(innerType, defaultValue) { + return new ZodPrefault2({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; } - addSequence(nodes) { - const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); - if (parsedNodes.length === 0) - throw new Error("Sequence requires at least one node."); - let previousNode; - for (const [key, action, options] of parsedNodes) { - if (key in this.nodes) - throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); - const validKey = key; - this.addNode(validKey, action, options); - if (previousNode != null) - this.addEdge(previousNode, validKey); - previousNode = validKey; + }); +} +function nonoptional2(innerType, params) { + return new ZodNonOptional2({ + type: "nonoptional", + innerType, + ...exports_util2.normalizeParams(params) + }); +} +function success2(innerType) { + return new ZodSuccess2({ + type: "success", + innerType + }); +} +function _catch4(innerType, catchValue) { + return new ZodCatch3({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +function nan2(params) { + return _nan2(ZodNaN3, params); +} +function pipe2(in_, out) { + return new ZodPipe2({ + type: "pipe", + in: in_, + out + }); +} +function readonly2(innerType) { + return new ZodReadonly3({ + type: "readonly", + innerType + }); +} +function templateLiteral2(parts, params) { + return new ZodTemplateLiteral2({ + type: "template_literal", + parts, + ...exports_util2.normalizeParams(params) + }); +} +function lazy2(getter) { + return new ZodLazy3({ + type: "lazy", + getter + }); +} +function promise2(innerType) { + return new ZodPromise3({ + type: "promise", + innerType + }); +} +function check2(fn) { + const ch = new $ZodCheck2({ + check: "custom" + }); + ch._zod.check = fn; + return ch; +} +function custom3(fn, _params) { + return _custom2(ZodCustom2, fn ?? (() => true), _params); +} +function refine2(fn, _params = {}) { + return _refine2(ZodCustom2, fn, _params); +} +function superRefine2(fn) { + const ch = check2((payload) => { + payload.addIssue = (issue3) => { + if (typeof issue3 === "string") { + payload.issues.push(exports_util2.issue(issue3, payload.value, ch._zod.def)); + } else { + const _issue = issue3; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(exports_util2.issue(_issue)); } - return this; - } - compile({ checkpointer, store, cache: cache2, interruptBefore, interruptAfter, name, description, transformers } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); - const outputChannels = outputKeys.length === 1 && outputKeys[0] === ROOT2 ? ROOT2 : outputKeys; - const streamKeys = Object.keys(this.channels); - const streamChannels = streamKeys.length === 1 && streamKeys[0] === ROOT2 ? ROOT2 : streamKeys; - const userInterrupt = this._interrupt; - const compiled = new CompiledStateGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - ...this.channels, - [START]: new EphemeralValue - }, - inputChannels: START, - outputChannels, - streamChannels, - streamMode: "updates", - store, - cache: cache2, - name, - description, - userInterrupt, - streamTransformers: transformers + }; + return fn(payload.value, payload); + }); + return ch; +} +function _instanceof2(cls, params = { + error: `Input not instance of ${cls.name}` +}) { + const inst = new ZodCustom2({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...exports_util2.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + return inst; +} +function json2(params) { + const jsonSchema = lazy2(() => { + return union2([string5(params), number5(), boolean5(), _null6(), array2(jsonSchema), record2(string5(), jsonSchema)]); + }); + return jsonSchema; +} +function preprocess2(fn, schema) { + return pipe2(transform2(fn), schema); +} +var ZodType3, _ZodString2, ZodString3, ZodStringFormat2, ZodEmail2, ZodGUID2, ZodUUID2, ZodURL2, ZodEmoji2, ZodNanoID2, ZodCUID3, ZodCUID22, ZodULID2, ZodXID2, ZodKSUID2, ZodIPv42, ZodIPv62, ZodCIDRv42, ZodCIDRv62, ZodBase642, ZodBase64URL2, ZodE1642, ZodJWT2, ZodCustomStringFormat2, ZodNumber3, ZodNumberFormat2, ZodBoolean3, ZodBigInt3, ZodBigIntFormat2, ZodSymbol3, ZodUndefined3, ZodNull3, ZodAny3, ZodUnknown3, ZodNever3, ZodVoid3, ZodDate3, ZodArray3, ZodObject3, ZodUnion3, ZodDiscriminatedUnion3, ZodIntersection3, ZodTuple3, ZodRecord3, ZodMap3, ZodSet3, ZodEnum3, ZodLiteral3, ZodFile2, ZodTransform2, ZodOptional3, ZodNullable3, ZodDefault3, ZodPrefault2, ZodNonOptional2, ZodSuccess2, ZodCatch3, ZodNaN3, ZodPipe2, ZodReadonly3, ZodTemplateLiteral2, ZodLazy3, ZodPromise3, ZodCustom2, stringbool2 = (...args) => _stringbool2({ + Pipe: ZodPipe2, + Boolean: ZodBoolean3, + String: ZodString3, + Transform: ZodTransform2 +}, ...args); +var init_schemas4 = __esm(() => { + init_core4(); + init_core4(); + init_checks4(); + init_iso2(); + init_parse6(); + ZodType3 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => { + $ZodType2.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks4) => { + return inst.clone({ + ...def, + checks: [ + ...def.checks ?? [], + ...checks4.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] }); - compiled.attachNode(START); - for (const [key, node] of Object.entries(this.nodes)) - compiled.attachNode(key, node); - compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); - for (const [key] of Object.entries(this.nodes)) - compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); - for (const [start, end] of this.edges) - compiled.attachEdge(start, end); - for (const [starts, end] of this.waitingEdges) - compiled.attachEdge(starts, end); - for (const [start, branches] of Object.entries(this.branches)) - for (const [name2, branch] of Object.entries(branches)) - compiled.attachBranch(start, name2, branch); - return compiled.validate(); - } - }; - CompiledStateGraph = class extends CompiledGraph { - description; - _metaRegistry = schemaMetaRegistry; - constructor({ description, ...rest }) { - super(rest); - this.description = description; - } - attachNode(key, node) { - let outputKeys; - if (key === "__start__") - outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); - else - outputKeys = Object.keys(this.builder.channels); - function _getRoot(input) { - if (isCommand(input)) { - if (input.graph === Command.PARENT) - return null; - return input._updateAsTuples(); - } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { - const updates = []; - for (const i of input) - if (isCommand(i)) { - if (i.graph === Command.PARENT) - continue; - updates.push(...i._updateAsTuples()); - } else - updates.push([ROOT2, i]); - return updates; - } else if (input != null) - return [[ROOT2, input]]; - return null; - } - const nodeKey = key; - function _getUpdates(input) { - if (!input) - return null; - else if (isCommand(input)) { - if (input.graph === Command.PARENT) - return null; - return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); - } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { - const updates = []; - for (const item of input) - if (isCommand(item)) { - if (item.graph === Command.PARENT) - continue; - updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); - } else { - const itemUpdates = _getUpdates(item); - if (itemUpdates) - updates.push(...itemUpdates ?? []); - } - return updates; - } else if (typeof input === "object" && !Array.isArray(input)) - return Object.entries(input).filter(([k]) => outputKeys.includes(k)); - else { - const typeofInput = Array.isArray(input) ? "array" : typeof input; - throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); - } - } - const stateWriteEntries = [{ - value: PASSTHROUGH, - mapper: new RunnableCallable({ - func: outputKeys.length && outputKeys[0] === ROOT2 ? _getRoot : _getUpdates, - trace: false, - recurse: false - }) - }]; - if (key === "__start__") - this.nodes[key] = new PregelNode({ - tags: [TAG_HIDDEN], - triggers: [START], - channels: [START], - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] - }); - else { - const inputDefinition = node?.input ?? this.builder._schemaDefinition; - const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); - const isSingleInput = Object.keys(inputValues).length === 1 && ROOT2 in inputValues; - const branchChannel = `branch:to:${key}`; - this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish : new EphemeralValue(false); - this.nodes[key] = new PregelNode({ - triggers: [branchChannel], - channels: isSingleInput ? Object.keys(inputValues) : inputValues, - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], - mapper: isSingleInput ? undefined : (input) => { - return Object.fromEntries(Object.entries(input).filter(([k]) => (k in inputValues))); - }, - bound: node?.runnable, - metadata: node?.metadata, - retryPolicy: node?.retryPolicy, - cachePolicy: node?.cachePolicy, - subgraphs: node?.subgraphs, - ends: node?.ends - }); + }; + inst.clone = (def2, params) => clone2(inst, def2, params); + inst.brand = () => inst; + inst.register = (reg, meta3) => { + reg.add(inst, meta3); + return inst; + }; + inst.parse = (data, params) => parse11(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse4(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.refine = (check2, params) => inst.check(refine2(check2, params)); + inst.superRefine = (refinement) => inst.check(superRefine2(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite2(fn)); + inst.optional = () => optional2(inst); + inst.nullable = () => nullable2(inst); + inst.nullish = () => optional2(nullable2(inst)); + inst.nonoptional = (params) => nonoptional2(inst, params); + inst.array = () => array2(inst); + inst.or = (arg) => union2([inst, arg]); + inst.and = (arg) => intersection2(inst, arg); + inst.transform = (tx) => pipe2(inst, transform2(tx)); + inst.default = (def2) => _default4(inst, def2); + inst.prefault = (def2) => prefault2(inst, def2); + inst.catch = (params) => _catch4(inst, params); + inst.pipe = (target) => pipe2(inst, target); + inst.readonly = () => readonly2(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry2.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry2.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry2.get(inst); } - } - attachEdge(starts, end) { - if (end === "__end__") - return; - if (typeof starts === "string") - this.nodes[starts].writers.push(new ChannelWrite([{ - channel: `branch:to:${end}`, - value: null - }], [TAG_HIDDEN])); - else if (Array.isArray(starts)) { - const channelName = `join:${starts.join("+")}:${end}`; - this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); - this.nodes[end].triggers.push(channelName); - for (const start of starts) - this.nodes[start].writers.push(new ChannelWrite([{ - channel: channelName, - value: start - }], [TAG_HIDDEN])); + const cl = inst.clone(); + globalRegistry2.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(undefined).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; + }); + _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => { + $ZodString2.init(inst, def); + ZodType3.init(inst, def); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex2(...args)); + inst.includes = (...args) => inst.check(_includes2(...args)); + inst.startsWith = (...args) => inst.check(_startsWith2(...args)); + inst.endsWith = (...args) => inst.check(_endsWith2(...args)); + inst.min = (...args) => inst.check(_minLength2(...args)); + inst.max = (...args) => inst.check(_maxLength2(...args)); + inst.length = (...args) => inst.check(_length2(...args)); + inst.nonempty = (...args) => inst.check(_minLength2(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase2(params)); + inst.uppercase = (params) => inst.check(_uppercase2(params)); + inst.trim = () => inst.check(_trim2()); + inst.normalize = (...args) => inst.check(_normalize2(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase2()); + inst.toUpperCase = () => inst.check(_toUpperCase2()); + }); + ZodString3 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => { + $ZodString2.init(inst, def); + _ZodString2.init(inst, def); + inst.email = (params) => inst.check(_email2(ZodEmail2, params)); + inst.url = (params) => inst.check(_url2(ZodURL2, params)); + inst.jwt = (params) => inst.check(_jwt2(ZodJWT2, params)); + inst.emoji = (params) => inst.check(_emoji4(ZodEmoji2, params)); + inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); + inst.uuid = (params) => inst.check(_uuid2(ZodUUID2, params)); + inst.uuidv4 = (params) => inst.check(_uuidv42(ZodUUID2, params)); + inst.uuidv6 = (params) => inst.check(_uuidv62(ZodUUID2, params)); + inst.uuidv7 = (params) => inst.check(_uuidv72(ZodUUID2, params)); + inst.nanoid = (params) => inst.check(_nanoid2(ZodNanoID2, params)); + inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); + inst.cuid = (params) => inst.check(_cuid3(ZodCUID3, params)); + inst.cuid2 = (params) => inst.check(_cuid22(ZodCUID22, params)); + inst.ulid = (params) => inst.check(_ulid2(ZodULID2, params)); + inst.base64 = (params) => inst.check(_base642(ZodBase642, params)); + inst.base64url = (params) => inst.check(_base64url2(ZodBase64URL2, params)); + inst.xid = (params) => inst.check(_xid2(ZodXID2, params)); + inst.ksuid = (params) => inst.check(_ksuid2(ZodKSUID2, params)); + inst.ipv4 = (params) => inst.check(_ipv42(ZodIPv42, params)); + inst.ipv6 = (params) => inst.check(_ipv62(ZodIPv62, params)); + inst.cidrv4 = (params) => inst.check(_cidrv42(ZodCIDRv42, params)); + inst.cidrv6 = (params) => inst.check(_cidrv62(ZodCIDRv62, params)); + inst.e164 = (params) => inst.check(_e1642(ZodE1642, params)); + inst.datetime = (params) => inst.check(datetime4(params)); + inst.date = (params) => inst.check(date7(params)); + inst.time = (params) => inst.check(time5(params)); + inst.duration = (params) => inst.check(duration4(params)); + }); + ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => { + $ZodStringFormat2.init(inst, def); + _ZodString2.init(inst, def); + }); + ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => { + $ZodEmail2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => { + $ZodGUID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => { + $ZodUUID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => { + $ZodURL2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => { + $ZodEmoji2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => { + $ZodNanoID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => { + $ZodCUID3.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => { + $ZodCUID22.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => { + $ZodULID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => { + $ZodXID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => { + $ZodKSUID2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => { + $ZodIPv42.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => { + $ZodIPv62.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => { + $ZodCIDRv42.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => { + $ZodCIDRv62.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => { + $ZodBase642.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => { + $ZodBase64URL2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => { + $ZodE1642.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => { + $ZodJWT2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat2.init(inst, def); + ZodStringFormat2.init(inst, def); + }); + ZodNumber3 = /* @__PURE__ */ $constructor2("ZodNumber", (inst, def) => { + $ZodNumber2.init(inst, def); + ZodType3.init(inst, def); + inst.gt = (value, params) => inst.check(_gt2(value, params)); + inst.gte = (value, params) => inst.check(_gte2(value, params)); + inst.min = (value, params) => inst.check(_gte2(value, params)); + inst.lt = (value, params) => inst.check(_lt2(value, params)); + inst.lte = (value, params) => inst.check(_lte2(value, params)); + inst.max = (value, params) => inst.check(_lte2(value, params)); + inst.int = (params) => inst.check(int2(params)); + inst.safe = (params) => inst.check(int2(params)); + inst.positive = (params) => inst.check(_gt2(0, params)); + inst.nonnegative = (params) => inst.check(_gte2(0, params)); + inst.negative = (params) => inst.check(_lt2(0, params)); + inst.nonpositive = (params) => inst.check(_lte2(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); + inst.step = (value, params) => inst.check(_multipleOf2(value, params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; + }); + ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat2.init(inst, def); + ZodNumber3.init(inst, def); + }); + ZodBoolean3 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => { + $ZodBoolean2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodBigInt3 = /* @__PURE__ */ $constructor2("ZodBigInt", (inst, def) => { + $ZodBigInt2.init(inst, def); + ZodType3.init(inst, def); + inst.gte = (value, params) => inst.check(_gte2(value, params)); + inst.min = (value, params) => inst.check(_gte2(value, params)); + inst.gt = (value, params) => inst.check(_gt2(value, params)); + inst.gte = (value, params) => inst.check(_gte2(value, params)); + inst.min = (value, params) => inst.check(_gte2(value, params)); + inst.lt = (value, params) => inst.check(_lt2(value, params)); + inst.lte = (value, params) => inst.check(_lte2(value, params)); + inst.max = (value, params) => inst.check(_lte2(value, params)); + inst.positive = (params) => inst.check(_gt2(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt2(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte2(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte2(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat2.init(inst, def); + ZodBigInt3.init(inst, def); + }); + ZodSymbol3 = /* @__PURE__ */ $constructor2("ZodSymbol", (inst, def) => { + $ZodSymbol2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodUndefined3 = /* @__PURE__ */ $constructor2("ZodUndefined", (inst, def) => { + $ZodUndefined2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodNull3 = /* @__PURE__ */ $constructor2("ZodNull", (inst, def) => { + $ZodNull2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodAny3 = /* @__PURE__ */ $constructor2("ZodAny", (inst, def) => { + $ZodAny2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodUnknown3 = /* @__PURE__ */ $constructor2("ZodUnknown", (inst, def) => { + $ZodUnknown2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodNever3 = /* @__PURE__ */ $constructor2("ZodNever", (inst, def) => { + $ZodNever2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodVoid3 = /* @__PURE__ */ $constructor2("ZodVoid", (inst, def) => { + $ZodVoid2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodDate3 = /* @__PURE__ */ $constructor2("ZodDate", (inst, def) => { + $ZodDate2.init(inst, def); + ZodType3.init(inst, def); + inst.min = (value, params) => inst.check(_gte2(value, params)); + inst.max = (value, params) => inst.check(_lte2(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; + }); + ZodArray3 = /* @__PURE__ */ $constructor2("ZodArray", (inst, def) => { + $ZodArray2.init(inst, def); + ZodType3.init(inst, def); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength2(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength2(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength2(maxLength, params)); + inst.length = (len, params) => inst.check(_length2(len, params)); + inst.unwrap = () => inst.element; + }); + ZodObject3 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def) => { + $ZodObject2.init(inst, def); + ZodType3.init(inst, def); + exports_util2.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum4(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never2() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); + inst.extend = (incoming) => { + return exports_util2.extend(inst, incoming); + }; + inst.merge = (other) => exports_util2.merge(inst, other); + inst.pick = (mask) => exports_util2.pick(inst, mask); + inst.omit = (mask) => exports_util2.omit(inst, mask); + inst.partial = (...args) => exports_util2.partial(ZodOptional3, inst, args[0]); + inst.required = (...args) => exports_util2.required(ZodNonOptional2, inst, args[0]); + }); + ZodUnion3 = /* @__PURE__ */ $constructor2("ZodUnion", (inst, def) => { + $ZodUnion2.init(inst, def); + ZodType3.init(inst, def); + inst.options = def.options; + }); + ZodDiscriminatedUnion3 = /* @__PURE__ */ $constructor2("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion3.init(inst, def); + $ZodDiscriminatedUnion2.init(inst, def); + }); + ZodIntersection3 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, def) => { + $ZodIntersection2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodTuple3 = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => { + $ZodTuple2.init(inst, def); + ZodType3.init(inst, def); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); + }); + ZodRecord3 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => { + $ZodRecord2.init(inst, def); + ZodType3.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodMap3 = /* @__PURE__ */ $constructor2("ZodMap", (inst, def) => { + $ZodMap2.init(inst, def); + ZodType3.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodSet3 = /* @__PURE__ */ $constructor2("ZodSet", (inst, def) => { + $ZodSet2.init(inst, def); + ZodType3.init(inst, def); + inst.min = (...args) => inst.check(_minSize2(...args)); + inst.nonempty = (params) => inst.check(_minSize2(1, params)); + inst.max = (...args) => inst.check(_maxSize2(...args)); + inst.size = (...args) => inst.check(_size2(...args)); + }); + ZodEnum3 = /* @__PURE__ */ $constructor2("ZodEnum", (inst, def) => { + $ZodEnum2.init(inst, def); + ZodType3.init(inst, def); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); } - } - attachBranch(start, _, branch, options = { withReader: true }) { - const branchWriter = async (packets, config2) => { - const filteredPackets = packets.filter((p) => p !== END); - if (!filteredPackets.length) - return; - const writes = filteredPackets.map((p) => { - if (_isSend(p)) - return p; - return { - channel: p === "__end__" ? p : `branch:to:${p}`, - value: start - }; - }); - await ChannelWrite.doWrite({ - ...config2, - tags: (config2.tags ?? []).concat([TAG_HIDDEN]) - }, writes); - }; - this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config2) => ChannelRead.doRead(config2, this.streamChannels ?? this.outputChannels, true) : undefined)); - } - async _validateInput(input) { - if (input == null) - return input; - const inputDef = this.builder._inputRuntimeDefinition; - const schemaDef = this.builder._schemaRuntimeDefinition; - if (StateSchema.isInstance(inputDef)) { - if (isCommand(input)) { - const parsedInput = input; - if (input.update) - parsedInput.update = await inputDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); - return parsedInput; - } - return await inputDef.validateInput(input); + return new ZodEnum3({ + ...def, + checks: [], + ...exports_util2.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); } - if (inputDef === PartialStateSchema && StateSchema.isInstance(schemaDef)) { - if (isCommand(input)) { - const parsedInput = input; - if (input.update) - parsedInput.update = await schemaDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); - return parsedInput; + return new ZodEnum3({ + ...def, + checks: [], + ...exports_util2.normalizeParams(params), + entries: newEntries + }); + }; + }); + ZodLiteral3 = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => { + $ZodLiteral2.init(inst, def); + ZodType3.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } - return await schemaDef.validateInput(input); + return def.values[0]; } - const schema = (() => { - const apply = (schema2) => { - if (schema2 == null) - return; - return this._metaRegistry.getExtendedChannelSchemas(schema2, { withReducerSchema: true }); - }; - if (isInteropZodObject(inputDef)) - return apply(inputDef); - if (inputDef === PartialStateSchema) { - if (isInteropZodObject(schemaDef)) - return interopZodObjectPartial(apply(schemaDef)); - return; + }); + }); + ZodFile2 = /* @__PURE__ */ $constructor2("ZodFile", (inst, def) => { + $ZodFile2.init(inst, def); + ZodType3.init(inst, def); + inst.min = (size, params) => inst.check(_minSize2(size, params)); + inst.max = (size, params) => inst.check(_maxSize2(size, params)); + inst.mime = (types3, params) => inst.check(_mime2(Array.isArray(types3) ? types3 : [types3], params)); + }); + ZodTransform2 = /* @__PURE__ */ $constructor2("ZodTransform", (inst, def) => { + $ZodTransform2.init(inst, def); + ZodType3.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.addIssue = (issue3) => { + if (typeof issue3 === "string") { + payload.issues.push(exports_util2.issue(issue3, payload.value, def)); + } else { + const _issue = issue3; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + _issue.continue ?? (_issue.continue = true); + payload.issues.push(exports_util2.issue(_issue)); } - })(); - if (isCommand(input)) { - const parsedInput = input; - if (input.update && schema != null) - parsedInput.update = interopParse(schema, input.update); - return parsedInput; + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); } - if (schema != null) - return interopParse(schema, input); - return input; - } - isInterrupted(input) { - return isInterrupted(input); - } - async _validateContext(config2) { - const configSchema = this.builder._configRuntimeSchema; - if (isInteropZodObject(configSchema)) - interopParse(configSchema, config2); - return config2; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/message.js -function pushMessage(message, options) { - const { stateKey: userStateKey, ...userConfig } = options ?? {}; - const config2 = ensureLangGraphConfig(userConfig); - let stateKey = userStateKey ?? "messages"; - if (userStateKey === null) - stateKey = undefined; - const validMessage = coerceMessageLikeToMessage(message); - if (!validMessage.id) - throw new Error("Message ID is required."); - const messagesHandler = (() => { - if (Array.isArray(config2.callbacks)) - return config2.callbacks; - if (typeof config2.callbacks !== "undefined") - return config2.callbacks.handlers; - return []; - })().find((cb) => ("name" in cb) && cb.name === "StreamMessagesHandler"); - if (messagesHandler) { - const metadata = config2.metadata ?? {}; - const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); - messagesHandler._emit([namespace, metadata], validMessage, undefined, false); - } - if (stateKey) - config2.configurable?.__pregel_send?.([[stateKey, validMessage]]); - return validMessage; -} -var MessageGraph; -var init_message2 = __esm(() => { - init_config2(); - init_messages_reducer(); - init_state2(); - init_messages(); - MessageGraph = class extends StateGraph { - constructor() { - super({ channels: { __root__: { - reducer: messagesStateReducer, - default: () => [] - } } }); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/func/index.js -function task(optionsOrName, func) { - const options = typeof optionsOrName === "string" ? { - name: optionsOrName, - retry: undefined, - cachePolicy: undefined - } : optionsOrName; - const { name, retry } = options; - if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) - throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); - const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : undefined); - let cache2; - if (typeof cachePolicy === "boolean") - cache2 = cachePolicy ? {} : undefined; - else - cache2 = cachePolicy; - return (...args) => { - return call({ - func, - name, - retry, - cache: cache2 - }, ...args); - }; -} -function getPreviousState() { - return AsyncLocalStorageProviderSingleton2.getRunnableConfig().configurable?.[CONFIG_KEY_PREVIOUS_STATE]; -} -var entrypoint = function entrypoint2(optionsOrName, func) { - const { name, checkpointer, store, cache: cache2 } = typeof optionsOrName === "string" ? { - name: optionsOrName, - checkpointer: undefined, - store: undefined - } : optionsOrName; - if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) - throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); - const streamMode = "updates"; - const bound = getRunnableForEntrypoint(name, func); - function isEntrypointFinal(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; - } - const pluckReturnValue = new RunnableCallable({ - name: "pluckReturnValue", - func: (value) => { - return isEntrypointFinal(value) ? value.value : value; - } + payload.value = output; + return payload; + }; }); - const pluckSaveValue = new RunnableCallable({ - name: "pluckSaveValue", - func: (value) => { - return isEntrypointFinal(value) ? value.save : value; - } + ZodOptional3 = /* @__PURE__ */ $constructor2("ZodOptional", (inst, def) => { + $ZodOptional2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; }); - const entrypointNode = new PregelNode({ - bound, - triggers: [START], - channels: [START], - writers: [new ChannelWrite([{ - channel: END, - value: PASSTHROUGH, - mapper: pluckReturnValue - }, { - channel: PREVIOUS, - value: PASSTHROUGH, - mapper: pluckSaveValue - }], [TAG_HIDDEN])] + ZodNullable3 = /* @__PURE__ */ $constructor2("ZodNullable", (inst, def) => { + $ZodNullable2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; }); - return new Pregel({ - name, - checkpointer, - nodes: { [name]: entrypointNode }, - channels: { - [START]: new EphemeralValue, - [END]: new LastValue, - [PREVIOUS]: new LastValue - }, - inputChannels: START, - outputChannels: END, - streamChannels: END, - streamMode, - store, - cache: cache2 + ZodDefault3 = /* @__PURE__ */ $constructor2("ZodDefault", (inst, def) => { + $ZodDefault2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + ZodPrefault2 = /* @__PURE__ */ $constructor2("ZodPrefault", (inst, def) => { + $ZodPrefault2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNonOptional2 = /* @__PURE__ */ $constructor2("ZodNonOptional", (inst, def) => { + $ZodNonOptional2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodSuccess2 = /* @__PURE__ */ $constructor2("ZodSuccess", (inst, def) => { + $ZodSuccess2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCatch3 = /* @__PURE__ */ $constructor2("ZodCatch", (inst, def) => { + $ZodCatch2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + ZodNaN3 = /* @__PURE__ */ $constructor2("ZodNaN", (inst, def) => { + $ZodNaN2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodPipe2 = /* @__PURE__ */ $constructor2("ZodPipe", (inst, def) => { + $ZodPipe2.init(inst, def); + ZodType3.init(inst, def); + inst.in = def.in; + inst.out = def.out; + }); + ZodReadonly3 = /* @__PURE__ */ $constructor2("ZodReadonly", (inst, def) => { + $ZodReadonly2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral2.init(inst, def); + ZodType3.init(inst, def); + }); + ZodLazy3 = /* @__PURE__ */ $constructor2("ZodLazy", (inst, def) => { + $ZodLazy2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.getter(); + }); + ZodPromise3 = /* @__PURE__ */ $constructor2("ZodPromise", (inst, def) => { + $ZodPromise2.init(inst, def); + ZodType3.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCustom2 = /* @__PURE__ */ $constructor2("ZodCustom", (inst, def) => { + $ZodCustom2.init(inst, def); + ZodType3.init(inst, def); }); -}; -var init_func = __esm(() => { - init_constants3(); - init_last_value(); - init_utils8(); - init_write(); - init_read(); - init_call(); - init_pregel(); - init_ephemeral_value(); - init_singletons(); - entrypoint.final = function final({ value, save }) { - return { - value, - save, - __lg_type: "__pregel_final" - }; - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/messages_annotation.js -var MessagesAnnotation, MessagesZodMeta, MessagesZodState; -var init_messages_annotation = __esm(() => { - init_annotation(); - init_messages_reducer(); - init_meta(); - init_v3(); - MessagesAnnotation = Annotation.Root({ messages: Annotation({ - reducer: messagesStateReducer, - default: () => [] - }) }); - MessagesZodMeta = { - reducer: { fn: messagesStateReducer }, - jsonSchemaExtra: { langgraph_type: "messages" }, - default: () => [] - }; - MessagesZodState = exports_external2.object({ messages: withLangGraph(exports_external2.custom(), MessagesZodMeta) }); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/writer.js -function writer(chunk) { - const config2 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (!config2) - throw new Error("Called interrupt() outside the context of a graph."); - const conf = config2.configurable; - if (!conf) - throw new Error("No configurable found in config"); - return conf.writer?.(chunk); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/compat.js +function setErrorMap3(map3) { + config2({ + customError: map3 + }); } -var init_writer = __esm(() => { - init_singletons(); +function getErrorMap3() { + return config2().customError; +} +var ZodIssueCode3; +var init_compat3 = __esm(() => { + init_core4(); + ZodIssueCode3 = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/index.js -var init_graph3 = __esm(() => { - init_constants3(); - init_annotation(); - init_graph2(); - init_messages_reducer(); - init_state2(); - init_message2(); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/coerce.js +var exports_coerce2 = {}; +__export(exports_coerce2, { + string: () => string6, + number: () => number6, + date: () => date9, + boolean: () => boolean6, + bigint: () => bigint6 }); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/web.js -var init_web = __esm(() => { - init_constants3(); - init_errors5(); - init_base15(); - init_binop(); - init_annotation(); - init_config2(); - init_stream_channel(); - init_convert(); - init_lifecycle(); - init_messages2(); - init_subgraphs(); - init_values(); - init_types6(); - init_run_stream(); - init_stream4(); - init_interrupt(); - init_graph2(); - init_types8(); - init_adapter(); - init_untracked_value(); - init_channels(); - init_reduced(); - init_untracked(); - init_schema(); - init_messages_reducer(); - init_messages4(); - init_state(); - init_state2(); - init_message2(); - init_graph3(); - init_func(); - init_messages_annotation(); - init_writer(); - init_dist3(); +function string6(params) { + return _coercedString2(ZodString3, params); +} +function number6(params) { + return _coercedNumber2(ZodNumber3, params); +} +function boolean6(params) { + return _coercedBoolean2(ZodBoolean3, params); +} +function bigint6(params) { + return _coercedBigint2(ZodBigInt3, params); +} +function date9(params) { + return _coercedDate2(ZodDate3, params); +} +var init_coerce2 = __esm(() => { + init_core4(); + init_schemas4(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/index.js -var exports_dist = {}; -__export(exports_dist, { - writer: () => writer, - task: () => task, - pushMessage: () => pushMessage, - messagesStateReducer: () => messagesStateReducer, - isStandardSchema: () => isStandardSchema2, - isSerializableSchema: () => isSerializableSchema2, - isParentCommand: () => isParentCommand, - isNativeTransformer: () => isNativeTransformer, - isInterrupted: () => isInterrupted, - isGraphInterrupt: () => isGraphInterrupt, - isGraphBubbleUp: () => isGraphBubbleUp, - isCommand: () => isCommand, - interrupt: () => interrupt, - getWriter: () => getWriter, - getSubgraphsSeenSet: () => getSubgraphsSeenSet, - getStore: () => getStore, - getSchemaDefaultGetter: () => getSchemaDefaultGetter, - getPreviousState: () => getPreviousState, - getJsonSchemaFromSchema: () => getJsonSchemaFromSchema, - getCurrentTaskInput: () => getCurrentTaskInput, - getConfig: () => getConfig, - filterSubgraphHandles: () => filterSubgraphHandles, - filterLifecycleEntries: () => filterLifecycleEntries, - entrypoint: () => entrypoint, - emptyCheckpoint: () => emptyCheckpoint, - createValuesTransformer: () => createValuesTransformer, - createSubgraphDiscoveryTransformer: () => createSubgraphDiscoveryTransformer, - createMessagesTransformer: () => createMessagesTransformer, - createLifecycleTransformer: () => createLifecycleTransformer, - createGraphRunStream: () => createGraphRunStream, - copyCheckpoint: () => copyCheckpoint, - convertToProtocolEvent: () => convertToProtocolEvent, - addMessages: () => messagesStateReducer, - UntrackedValueChannel: () => UntrackedValueChannel, - UntrackedValue: () => UntrackedValue, - UnreachableNodeError: () => UnreachableNodeError, - SubgraphRunStream: () => SubgraphRunStream, - StreamChannel: () => StreamChannel, - StateSchema: () => StateSchema, - StateGraphInputError: () => StateGraphInputError, - StateGraph: () => StateGraph, - Send: () => Send, - STREAM_EVENTS_V3_MODES: () => STREAM_EVENTS_V3_MODES, - START: () => START, - RemoteException: () => RemoteException, - ReducedValue: () => ReducedValue, - REMOVE_ALL_MESSAGES: () => REMOVE_ALL_MESSAGES, - ParentCommand: () => ParentCommand, - Overwrite: () => Overwrite, - NodeInterrupt: () => NodeInterrupt, - MultipleSubgraphsError: () => MultipleSubgraphsError, - MessagesZodState: () => MessagesZodState, - MessagesZodMeta: () => MessagesZodMeta, - MessagesValue: () => MessagesValue, - MessagesAnnotation: () => MessagesAnnotation, - MessageGraph: () => MessageGraph, - MemorySaver: () => MemorySaver, - InvalidUpdateError: () => InvalidUpdateError, - InMemoryStore: () => InMemoryStore2, - INTERRUPT: () => INTERRUPT, - GraphValueError: () => GraphValueError, - GraphRunStream: () => GraphRunStream, - GraphRecursionError: () => GraphRecursionError, - GraphInterrupt: () => GraphInterrupt, - GraphBubbleUp: () => GraphBubbleUp, - Graph: () => Graph$1, - EventLog: () => StreamChannel, - EmptyInputError: () => EmptyInputError, - EmptyChannelError: () => EmptyChannelError, - END: () => END, - CompiledStateGraph: () => CompiledStateGraph, - CommandInstance: () => CommandInstance, - Command: () => Command, - ChatModelStreamImpl: () => ChatModelStream, - COMMAND_SYMBOL: () => COMMAND_SYMBOL, - BinaryOperatorAggregate: () => BinaryOperatorAggregate, - BaseStore: () => BaseStore2, - BaseLangGraphError: () => BaseLangGraphError, - BaseCheckpointSaver: () => BaseCheckpointSaver, - BaseChannel: () => BaseChannel, - AsyncBatchedStore: () => AsyncBatchedStore, - Annotation: () => Annotation -}); -var init_dist4 = __esm(() => { - init_async_local_storage2(); - init_constants3(); - init_errors5(); - init_base15(); - init_binop(); - init_annotation(); - init_config2(); - init_stream_channel(); - init_convert(); - init_lifecycle(); - init_messages2(); - init_subgraphs(); - init_values(); - init_types6(); - init_run_stream(); - init_stream4(); - init_interrupt(); - init_graph2(); - init_types8(); - init_adapter(); - init_untracked_value(); - init_reduced(); - init_untracked(); - init_schema(); - init_messages_reducer(); - init_messages4(); - init_state2(); - init_message2(); - init_func(); - init_messages_annotation(); - init_writer(); - init_web(); - initializeAsyncLocalStorageSingleton(); +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js +var exports_external3 = {}; +__export(exports_external3, { + xid: () => xid4, + void: () => _void4, + uuidv7: () => uuidv72, + uuidv6: () => uuidv62, + uuidv4: () => uuidv42, + uuid: () => uuid5, + url: () => url2, + uppercase: () => _uppercase2, + unknown: () => unknown2, + union: () => union2, + undefined: () => _undefined6, + ulid: () => ulid4, + uint64: () => uint642, + uint32: () => uint322, + tuple: () => tuple2, + trim: () => _trim2, + treeifyError: () => treeifyError2, + transform: () => transform2, + toUpperCase: () => _toUpperCase2, + toLowerCase: () => _toLowerCase2, + toJSONSchema: () => toJSONSchema2, + templateLiteral: () => templateLiteral2, + symbol: () => symbol2, + superRefine: () => superRefine2, + success: () => success2, + stringbool: () => stringbool2, + stringFormat: () => stringFormat2, + string: () => string5, + strictObject: () => strictObject2, + startsWith: () => _startsWith2, + size: () => _size2, + setErrorMap: () => setErrorMap3, + set: () => set2, + safeParseAsync: () => safeParseAsync4, + safeParse: () => safeParse4, + registry: () => registry2, + regexes: () => exports_regexes2, + regex: () => _regex2, + refine: () => refine2, + record: () => record2, + readonly: () => readonly2, + property: () => _property2, + promise: () => promise2, + prettifyError: () => prettifyError2, + preprocess: () => preprocess2, + prefault: () => prefault2, + positive: () => _positive2, + pipe: () => pipe2, + partialRecord: () => partialRecord2, + parseAsync: () => parseAsync4, + parse: () => parse11, + overwrite: () => _overwrite2, + optional: () => optional2, + object: () => object2, + number: () => number5, + nullish: () => nullish4, + nullable: () => nullable2, + null: () => _null6, + normalize: () => _normalize2, + nonpositive: () => _nonpositive2, + nonoptional: () => nonoptional2, + nonnegative: () => _nonnegative2, + never: () => never2, + negative: () => _negative2, + nativeEnum: () => nativeEnum2, + nanoid: () => nanoid4, + nan: () => nan2, + multipleOf: () => _multipleOf2, + minSize: () => _minSize2, + minLength: () => _minLength2, + mime: () => _mime2, + maxSize: () => _maxSize2, + maxLength: () => _maxLength2, + map: () => map2, + lte: () => _lte2, + lt: () => _lt2, + lowercase: () => _lowercase2, + looseObject: () => looseObject2, + locales: () => exports_locales2, + literal: () => literal2, + length: () => _length2, + lazy: () => lazy2, + ksuid: () => ksuid4, + keyof: () => keyof2, + jwt: () => jwt2, + json: () => json2, + iso: () => exports_iso2, + ipv6: () => ipv64, + ipv4: () => ipv44, + intersection: () => intersection2, + int64: () => int642, + int32: () => int322, + int: () => int2, + instanceof: () => _instanceof2, + includes: () => _includes2, + guid: () => guid4, + gte: () => _gte2, + gt: () => _gt2, + globalRegistry: () => globalRegistry2, + getErrorMap: () => getErrorMap3, + function: () => _function2, + formatError: () => formatError3, + float64: () => float642, + float32: () => float322, + flattenError: () => flattenError2, + file: () => file2, + enum: () => _enum4, + endsWith: () => _endsWith2, + emoji: () => emoji4, + email: () => email4, + e164: () => e1644, + discriminatedUnion: () => discriminatedUnion2, + date: () => date8, + custom: () => custom3, + cuid2: () => cuid24, + cuid: () => cuid6, + core: () => exports_core4, + config: () => config2, + coerce: () => exports_coerce2, + clone: () => clone2, + cidrv6: () => cidrv64, + cidrv4: () => cidrv44, + check: () => check2, + catch: () => _catch4, + boolean: () => boolean5, + bigint: () => bigint5, + base64url: () => base64url4, + base64: () => base645, + array: () => array2, + any: () => any2, + _default: () => _default4, + _ZodString: () => _ZodString2, + ZodXID: () => ZodXID2, + ZodVoid: () => ZodVoid3, + ZodUnknown: () => ZodUnknown3, + ZodUnion: () => ZodUnion3, + ZodUndefined: () => ZodUndefined3, + ZodUUID: () => ZodUUID2, + ZodURL: () => ZodURL2, + ZodULID: () => ZodULID2, + ZodType: () => ZodType3, + ZodTuple: () => ZodTuple3, + ZodTransform: () => ZodTransform2, + ZodTemplateLiteral: () => ZodTemplateLiteral2, + ZodSymbol: () => ZodSymbol3, + ZodSuccess: () => ZodSuccess2, + ZodStringFormat: () => ZodStringFormat2, + ZodString: () => ZodString3, + ZodSet: () => ZodSet3, + ZodRecord: () => ZodRecord3, + ZodRealError: () => ZodRealError2, + ZodReadonly: () => ZodReadonly3, + ZodPromise: () => ZodPromise3, + ZodPrefault: () => ZodPrefault2, + ZodPipe: () => ZodPipe2, + ZodOptional: () => ZodOptional3, + ZodObject: () => ZodObject3, + ZodNumberFormat: () => ZodNumberFormat2, + ZodNumber: () => ZodNumber3, + ZodNullable: () => ZodNullable3, + ZodNull: () => ZodNull3, + ZodNonOptional: () => ZodNonOptional2, + ZodNever: () => ZodNever3, + ZodNanoID: () => ZodNanoID2, + ZodNaN: () => ZodNaN3, + ZodMap: () => ZodMap3, + ZodLiteral: () => ZodLiteral3, + ZodLazy: () => ZodLazy3, + ZodKSUID: () => ZodKSUID2, + ZodJWT: () => ZodJWT2, + ZodIssueCode: () => ZodIssueCode3, + ZodIntersection: () => ZodIntersection3, + ZodISOTime: () => ZodISOTime2, + ZodISODuration: () => ZodISODuration2, + ZodISODateTime: () => ZodISODateTime2, + ZodISODate: () => ZodISODate2, + ZodIPv6: () => ZodIPv62, + ZodIPv4: () => ZodIPv42, + ZodGUID: () => ZodGUID2, + ZodFile: () => ZodFile2, + ZodError: () => ZodError4, + ZodEnum: () => ZodEnum3, + ZodEmoji: () => ZodEmoji2, + ZodEmail: () => ZodEmail2, + ZodE164: () => ZodE1642, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion3, + ZodDefault: () => ZodDefault3, + ZodDate: () => ZodDate3, + ZodCustomStringFormat: () => ZodCustomStringFormat2, + ZodCustom: () => ZodCustom2, + ZodCatch: () => ZodCatch3, + ZodCUID2: () => ZodCUID22, + ZodCUID: () => ZodCUID3, + ZodCIDRv6: () => ZodCIDRv62, + ZodCIDRv4: () => ZodCIDRv42, + ZodBoolean: () => ZodBoolean3, + ZodBigIntFormat: () => ZodBigIntFormat2, + ZodBigInt: () => ZodBigInt3, + ZodBase64URL: () => ZodBase64URL2, + ZodBase64: () => ZodBase642, + ZodArray: () => ZodArray3, + ZodAny: () => ZodAny3, + TimePrecision: () => TimePrecision2, + NEVER: () => NEVER2, + $output: () => $output2, + $input: () => $input2, + $brand: () => $brand2 +}); +var init_external3 = __esm(() => { + init_core4(); + init_core4(); + init_en2(); + init_core4(); + init_locales2(); + init_iso2(); + init_iso2(); + init_coerce2(); + init_schemas4(); + init_checks4(); + init_errors6(); + init_parse6(); + init_compat3(); + config2(en_default2()); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/tools/headless.js -function createHeadlessTool(fields) { - const { name, description, schema } = fields; - const wrappedTool = tool(async (args, config2) => { - const { interrupt: interrupt2 } = await Promise.resolve().then(() => (init_dist4(), exports_dist)); - return interrupt2({ - type: "tool", - toolCall: { - id: config2?.toolCall?.id, - name, - args +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/index.js +var init_classic = __esm(() => { + init_external3(); + init_external3(); +}); + +// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/index.js +var init_v43 = __esm(() => { + init_classic(); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tools/index.js +function tool(func, fields) { + const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); + const isStringJSONSchema = validatesOnlyStrings(fields.schema); + if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) + return new DynamicTool({ + ...fields, + description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, + func: async (input, runManager, config3) => { + return new Promise((resolve2, reject) => { + const childConfig = patchConfig(config3, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + resolve2(func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }); } }); - }, { - name, + const schema = fields.schema; + const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; + return new DynamicStructuredTool({ + ...fields, description, schema, - metadata: { headlessTool: true } + func: async (input, runManager, config3) => { + return new Promise((resolve2, reject) => { + let listener; + const cleanup = () => { + if (config3?.signal && listener) + config3.signal.removeEventListener("abort", listener); + }; + if (config3?.signal) { + listener = () => { + cleanup(); + reject(getAbortSignalError(config3.signal)); + }; + config3.signal.addEventListener("abort", listener, { once: true }); + } + const childConfig = patchConfig(config3, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton2.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + const result = await func(input, childConfig); + if (isAsyncGenerator(result)) { + resolve2(result); + return; + } + if (config3?.signal?.aborted) { + cleanup(); + return; + } + cleanup(); + resolve2(result); + } catch (e) { + cleanup(); + reject(e); + } + }); + }); + } }); - const headlessTool = Object.assign(wrappedTool, { implement: (execute) => ({ - tool: headlessTool, - execute - }) }); - return headlessTool; } -var tool$1 = (funcOrFields, fields) => { - if (typeof funcOrFields !== "function") - return createHeadlessTool(funcOrFields); - return tool(funcOrFields, fields); +function _formatToolOutput(params) { + const { content, artifact, toolCallId, metadata } = params; + if (toolCallId && !isDirectToolOutput(content)) + if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) + return new ToolMessage({ + status: "success", + content, + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else + return new ToolMessage({ + status: "success", + content: _stringify(content), + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else + return content; +} +function _stringify(content) { + try { + return JSON.stringify(content) ?? ""; + } catch (_noOp) { + return `${content}`; + } +} +var tools_exports, StructuredTool, Tool, DynamicTool, DynamicStructuredTool, BaseToolkit = class { + getTools() { + return this.tools; + } }; -var init_headless = __esm(() => { - init_tools2(); -}); +var init_tools2 = __esm(() => { + init_runtime2(); + init_utils2(); + init_tool(); + init_manager(); + init_async_local_storage(); + init_singletons(); + init_config(); + init_signal(); + init_zod2(); + init_json_schema3(); + init_iter(); + init_base5(); + init_types4(); + init_v3(); + init_esm(); + init_v43(); + tools_exports = /* @__PURE__ */ __exportAll({ + BaseToolkit: () => BaseToolkit, + DynamicStructuredTool: () => DynamicStructuredTool, + DynamicTool: () => DynamicTool, + StructuredTool: () => StructuredTool, + Tool: () => Tool, + ToolInputParsingException: () => ToolInputParsingException, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams, + tool: () => tool + }); + StructuredTool = class extends BaseLangChain { + extras; + returnDirect = false; + verboseParsingErrors = false; + get lc_namespace() { + return ["langchain", "tools"]; + } + responseFormat = "content"; + defaultConfig; + constructor(fields) { + super(fields ?? {}); + this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; + this.responseFormat = fields?.responseFormat ?? this.responseFormat; + this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; + this.metadata = fields?.metadata ?? this.metadata; + this.extras = fields?.extras ?? this.extras; + } + async invoke(input, config3) { + let toolInput; + let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config3)); + if (_isToolCall(input)) { + toolInput = input.args; + enrichedConfig = { + ...enrichedConfig, + toolCall: input + }; + } else + toolInput = input; + return this.call(toolInput, enrichedConfig); + } + async call(arg, configArg, tags) { + const inputForValidation = _isToolCall(arg) ? arg.args : arg; + let parsed; + if (isInteropZodSchema(this.schema)) + try { + parsed = await interopParseAsync(this.schema, inputForValidation); + } catch (e) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) + message = `${message} +Details: ${e.message}`; + if (isInteropZodError(e)) + message = `${message} -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/errors.js -var MultipleToolsBoundError, MultipleStructuredOutputsError, StructuredOutputParsingError, ToolInvocationError, MiddlewareError; -var init_errors6 = __esm(() => { - init_dist4(); - MultipleToolsBoundError = class extends Error { - constructor() { - super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter."); +${exports_external3.prettifyError(e)}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + else { + const result2 = validate5(inputForValidation, this.schema); + if (!result2.valid) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) + message = `${message} +Details: ${result2.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join(` +`)}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + parsed = inputForValidation; + } + const config3 = parseCallbackConfigArg(configArg); + const callbackManager_ = CallbackManager.configure(config3.callbacks, this.callbacks, config3.tags || tags, this.tags, config3.metadata, this.metadata, { verbose: this.verbose }); + let toolCallId; + if (_isToolCall(arg)) + toolCallId = arg.id; + if (!toolCallId && _configHasToolCallId(config3)) + toolCallId = config3.toolCall.id; + const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config3.runId, undefined, undefined, undefined, config3.runName, toolCallId); + delete config3.runId; + let result; + try { + const raw2 = await this._call(parsed, runManager, config3); + result = isAsyncGenerator(raw2) ? await consumeAsyncGenerator(raw2, async (chunk) => { + try { + await runManager?.handleToolEvent(chunk); + } catch (streamError) { + await runManager?.handleToolError(streamError); + } + }) : raw2; + } catch (e) { + await runManager?.handleToolError(e); + throw e; + } + let content; + let artifact; + if (this.responseFormat === "content_and_artifact") + if (Array.isArray(result) && result.length === 2) + [content, artifact] = result; + else + throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple. +Result: ${JSON.stringify(result)}`); + else + content = result; + const formattedOutput = _formatToolOutput({ + content, + artifact, + toolCallId, + name: this.name, + metadata: this.metadata + }); + await runManager?.handleToolEnd(formattedOutput); + return formattedOutput; } }; - MultipleStructuredOutputsError = class extends Error { - toolNames; - constructor(toolNames) { - super(`The model has called multiple tools: ${toolNames.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`); - this.toolNames = toolNames; + Tool = class extends StructuredTool { + schema = exports_external2.object({ input: exports_external2.string().optional() }).transform((obj) => obj.input); + constructor(fields) { + super(fields); } - }; - StructuredOutputParsingError = class extends Error { - toolName; - errors; - constructor(toolName, errors4) { - super(`Failed to parse structured output for tool '${toolName}':${errors4.map((e) => ` - - ${e}`).join("")}.`); - this.toolName = toolName; - this.errors = errors4; + call(arg, callbacks) { + const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; + return super.call(structuredArg, callbacks); } }; - ToolInvocationError = class extends Error { - toolCall; - toolError; - constructor(toolError, toolCall) { - const error51 = toolError instanceof Error ? toolError : new Error(String(toolError)); - const toolArgs = JSON.stringify(toolCall.args); - super(`Error invoking tool '${toolCall.name}' with kwargs ${toolArgs} with error: ${error51.stack} - Please fix the error and try again.`); - this.toolCall = toolCall; - this.toolError = error51; + DynamicTool = class extends Tool { + static lc_name() { + return "DynamicTool"; } - }; - MiddlewareError = class MiddlewareError2 extends Error { - static "~brand" = "MiddlewareError"; - constructor(error51, middlewareName) { - const errorMessage = error51 instanceof Error ? error51.message : String(error51); - super(errorMessage); - this.name = error51 instanceof Error ? error51.name : `${middlewareName[0].toUpperCase() + middlewareName.slice(1)}Error`; - if (error51 instanceof Error) - this.cause = error51; + name; + description; + func; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; } - static wrap(error51, middlewareName) { - if (isGraphBubbleUp(error51)) - return error51; - return new MiddlewareError2(error51, middlewareName); + async call(arg, configArg) { + const config3 = parseCallbackConfigArg(configArg); + if (config3.runName === undefined) + config3.runName = this.name; + return super.call(arg, config3); } - static isInstance(error51) { - return error51 instanceof Error && "~brand" in error51 && error51["~brand"] === "MiddlewareError"; + _call(input, runManager, parentConfig) { + return this.func(input, runManager, parentConfig); } }; -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/model.js -function isBaseChatModel(model) { - return "invoke" in model && typeof model.invoke === "function" && "_streamResponseChunks" in model; -} -function isConfigurableModel(model) { - return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_getModelInstance" in model && typeof model._getModelInstance === "function"; -} -var init_model = () => {}; - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/responses.js -function transformResponseFormat(responseFormat, options, model) { - if (!responseFormat) - return []; - if (typeof responseFormat === "object" && responseFormat !== null && "__responseFormatUndefined" in responseFormat) - return []; - if (Array.isArray(responseFormat)) { - if (responseFormat.every((item) => item instanceof ToolStrategy || item instanceof ProviderStrategy)) - return responseFormat; - if (responseFormat.every((item) => isSerializableSchema(item))) - return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); - if (responseFormat.every((item) => isInteropZodObject(item))) - return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); - if (responseFormat.every((item) => typeof item === "object" && item !== null && !isInteropZodObject(item) && !isSerializableSchema(item))) - return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); - throw new Error(`Invalid response format: list contains mixed types. -All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`); - } - if (responseFormat instanceof ToolStrategy || responseFormat instanceof ProviderStrategy) - return [responseFormat]; - const useProviderStrategy = hasSupportForJsonSchemaOutput(model); - if (isSerializableSchema(responseFormat)) - return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; - if (isInteropZodObject(responseFormat)) - return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; - if (typeof responseFormat === "object" && responseFormat !== null && "properties" in responseFormat) - return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; - throw new Error(`Invalid response format: ${String(responseFormat)}`); -} -function hasSupportForJsonSchemaOutput(model) { - if (!model || !isBaseChatModel(model) || !("profile" in model) || typeof model.profile !== "object" || !model.profile) - return false; - return "structuredOutput" in model.profile && model.profile.structuredOutput === true; -} -var PROVIDER_STRATEGY_DEFAULT_STRICT = true, bindingIdentifier = 0, ToolStrategy = class ToolStrategy2 { - constructor(schema, tool2, options) { - this.schema = schema; - this.tool = tool2; - this.options = options; - } - get name() { - return this.tool.function.name; - } - static fromSchema(schema, outputOptions) { - function getFunctionName(name) { - return name ?? `extract-${++bindingIdentifier}`; + DynamicStructuredTool = class extends StructuredTool { + static lc_name() { + return "DynamicStructuredTool"; } - if (isSerializableSchema(schema) || isInteropZodSchema(schema)) { - const asJsonSchema = toJsonSchema(schema); - return new ToolStrategy2(asJsonSchema, { - type: "function", - function: { - name: getFunctionName(asJsonSchema.title), - strict: false, - description: asJsonSchema.description ?? "Tool for extracting structured output from the model's response.", - parameters: asJsonSchema - } - }, outputOptions); + description; + func; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; + this.schema = fields.schema; } - let functionDefinition; - if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) - functionDefinition = schema; - else - functionDefinition = { - name: getFunctionName(schema.title), - description: schema.description ?? "", - parameters: schema.schema || schema - }; - return new ToolStrategy2(toJsonSchema(schema), { - type: "function", - function: functionDefinition - }, outputOptions); - } - parse(toolArgs) { - const result = new Validator(this.schema).validate(toolArgs); - if (!result.valid) - throw new StructuredOutputParsingError(this.name, result.errors.map((e) => e.error)); - return toolArgs; - } -}, ProviderStrategy = class ProviderStrategy2 { - _schemaType; - schema; - strict; - constructor(schemaOrOptions, strict) { - if ("schema" in schemaOrOptions && typeof schemaOrOptions.schema === "object" && schemaOrOptions.schema !== null && !("type" in schemaOrOptions)) { - const options = schemaOrOptions; - this.schema = options.schema; - this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; - } else { - this.schema = schemaOrOptions; - this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; + async call(arg, configArg, tags) { + const config3 = parseCallbackConfigArg(configArg); + if (config3.runName === undefined) + config3.runName = this.name; + return super.call(arg, config3, tags); } - } - static fromSchema(schema, strict) { - return new ProviderStrategy2(toJsonSchema(schema), strict); - } - parse(response) { - let textContent; - if (typeof response.content === "string") - textContent = response.content; - else if (Array.isArray(response.content)) { - for (const block of response.content) - if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { - textContent = block.text; - break; - } + _call(arg, runManager, parentConfig) { + return this.func(arg, runManager, parentConfig); } - if (!textContent || textContent === "") - return; - try { - const content = JSON.parse(textContent); - if (!new Validator(this.schema).validate(content).valid) - return; - return content; - } catch {} - } -}; -var init_responses = __esm(() => { - init_model(); - init_errors6(); - init_types3(); - init_json_schema2(); - init_standard_schema(); + }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/utils.js -function countTokensApproximately(messages, tools) { - const charsPerToken = 4; - let totalChars = 0; - if (tools && tools.length > 0) { - let toolsChars = 0; - for (const tool2 of tools) { - const toolDict = isLangChainTool(tool2) ? convertToOpenAITool(tool2) : tool2; - toolsChars += JSON.stringify(toolDict).length; - } - totalChars += toolsChars; - } - for (const msg of messages) { - let textContent; - if (typeof msg.content === "string") - textContent = msg.content; - else if (Array.isArray(msg.content)) - textContent = msg.content.map((item) => { - if (typeof item === "string") - return item; - if (item.type === "text" && "text" in item) - return item.text; - return ""; - }).join(""); - else - textContent = ""; - if (AIMessage.isInstance(msg) && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) - textContent += JSON.stringify(msg.tool_calls); - if (ToolMessage.isInstance(msg)) - textContent += msg.tool_call_id ?? ""; - totalChars += textContent.length; - } - return Math.ceil(totalChars / charsPerToken); -} -function getHookConstraint(hook) { - if (!hook || typeof hook === "function") - return; - return hook.canJumpTo; -} -function getHookFunction(arg) { - if (typeof arg === "function") - return arg; - return arg.hook; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/setup/async_local_storage.js +import { AsyncLocalStorage } from "node:async_hooks"; +function initializeAsyncLocalStorageSingleton() { + AsyncLocalStorageProviderSingleton2.initializeGlobalInstance(new AsyncLocalStorage); } -var init_utils10 = __esm(() => { - init_messages(); - init_tools2(); - init_function_calling(); +var init_async_local_storage2 = __esm(() => { + init_singletons(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/stream.js -function isOwnEvent(ns3, path2) { - if (ns3.length < path2.length || ns3.length > path2.length + 1) +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/constants.js +function _isSendInterface(x) { + const operation = x; + return operation !== null && operation !== undefined && typeof operation.node === "string" && operation.args !== undefined; +} +function _isSend(x) { + return x instanceof Send; +} +function _getOverwriteValue(value) { + if (typeof value === "object" && value !== null && "__overwrite__" in value) + return [true, value[OVERWRITE]]; + return [false, undefined]; +} +function _isOverwriteValue(value) { + return _getOverwriteValue(value)[0]; +} +function isInterrupted(values) { + if (!values || typeof values !== "object") return false; - for (let i = 0;i < path2.length; i += 1) - if (ns3[i] !== path2[i]) - return false; - return true; + if (!("__interrupt__" in values)) + return false; + return Array.isArray(values[INTERRUPT]); } -function isHeadlessToolInterruptError(message, toolCallId) { - try { - const parsed = JSON.parse(message); - if (!Array.isArray(parsed)) - return false; - return parsed.some((entry) => { - if (entry == null || typeof entry !== "object") - return false; - const value = entry.value; - if (value == null || typeof value !== "object") - return false; - const payload = value; - return payload.type === "tool" && (toolCallId == null || payload.toolCall?.id == null || payload.toolCall.id === toolCallId); - }); - } catch { +function isCommand(x) { + if (typeof x !== "object") return false; - } + if (x === null || x === undefined) + return false; + if ("lg_name" in x && x.lg_name === "Command") + return true; + return false; } -function createToolCallTransformer(path2) { - return () => { - const toolCallsLog = StreamChannel.local(); - const pendingCalls = /* @__PURE__ */ new Map; - function createToolCallEntry(callId, name, rawInput) { - if (pendingCalls.has(callId)) - return; - const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput; - let resolveOutput; - let rejectOutput; - let resolveStatus; - let resolveError; - const output = new Promise((res, rej) => { - resolveOutput = res; - rejectOutput = rej; - }); - const status = new Promise((res) => { - resolveStatus = res; - }); - const error51 = new Promise((res) => { - resolveError = res; - }); - pendingCalls.set(callId, { - resolveOutput, - rejectOutput, - resolveStatus, - resolveError - }); - toolCallsLog.push({ - name, - callId, - input, - output, - status, - error: error51 +function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map) { + if (x !== undefined && x !== null && typeof x === "object") { + if (seen.has(x)) + return seen.get(x); + let result; + if (Array.isArray(x)) { + result = []; + seen.set(x, result); + x.forEach((item, index) => { + result[index] = _deserializeCommandSendObjectGraph(item, seen); }); + } else if (isCommand(x) && !(x instanceof Command)) { + result = new Command(x); + seen.set(x, result); + } else if (_isSendInterface(x) && !(x instanceof Send)) { + result = new Send(x.node, x.args); + seen.set(x, result); + } else if (isCommand(x) || _isSend(x)) { + result = x; + seen.set(x, result); + } else if ("lc_serializable" in x && x.lc_serializable) { + result = x; + seen.set(x, result); + } else { + result = {}; + seen.set(x, result); + for (const [key, value] of Object.entries(x)) + result[key] = _deserializeCommandSendObjectGraph(value, seen); } - return { - __native: true, - init: () => ({ toolCalls: toolCallsLog }), - process(event) { - if (!isOwnEvent(event.params.namespace, path2)) - return true; - if (event.method === "messages") { - const data = event.params.data; - if (data.event === "content-block-finish") { - const cb = data.contentBlock ?? data.content_block; - if (cb?.type === "tool_call") - createToolCallEntry(String(cb.id ?? ""), String(cb.name ?? ""), cb.args ?? cb.input); - } - } - if (event.method === "tools") { - const data = event.params.data; - const toolCallId = data.tool_call_id; - if (data.event === "tool-started") - createToolCallEntry(toolCallId, data.tool_name ?? "unknown", data.input); - const pending = toolCallId ? pendingCalls.get(toolCallId) : undefined; - if (pending) { - if (data.event === "tool-finished") { - pending.resolveOutput(data.output); - pending.resolveStatus("finished"); - pending.resolveError(undefined); - pendingCalls.delete(toolCallId); - } else if (data.event === "tool-error") { - const message = data.message ?? "unknown error"; - if (isHeadlessToolInterruptError(message, toolCallId)) - return true; - pending.rejectOutput(new Error(message)); - pending.resolveStatus("error"); - pending.resolveError(message); - pendingCalls.delete(toolCallId); - } - } - } - return true; - }, - finalize() { - for (const pending of pendingCalls.values()) { - pending.resolveStatus("finished"); - pending.resolveError(undefined); - pending.resolveOutput(undefined); - } - pendingCalls.clear(); - toolCallsLog.close(); - }, - fail(err) { - for (const pending of pendingCalls.values()) { - pending.resolveStatus("error"); - pending.resolveError(err instanceof Error ? err.message : String(err)); - pending.rejectOutput(err); - } - pendingCalls.clear(); - toolCallsLog.fail(err); - } - }; - }; -} -var init_stream6 = __esm(() => { - init_dist4(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/types.js -var MIDDLEWARE_BRAND; -var init_types10 = __esm(() => { - MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware"); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware.js -function createMiddleware(config2) { - return { - [MIDDLEWARE_BRAND]: true, - name: config2.name, - stateSchema: config2.stateSchema, - contextSchema: config2.contextSchema, - wrapToolCall: config2.wrapToolCall, - wrapModelCall: config2.wrapModelCall, - beforeAgent: config2.beforeAgent, - beforeModel: config2.beforeModel, - afterModel: config2.afterModel, - afterAgent: config2.afterAgent, - tools: config2.tools - }; + return result; + } + return x; } -var init_middleware = __esm(() => { - init_types10(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/tests/utils.js -var init_utils11 = __esm(() => { - init_messages(); - init_chat_models(); - init_runnables(); - init_tools2(); - init_dist3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/zod/plugin.js -function applyPluginPrototype(prototype) { - const cache2 = globalThis[metaSymbol]; - if (cache2.has(prototype)) - return; - Object.defineProperty(prototype, "langgraph", { get() { - const zodThis = this; +var START = "__start__", END = "__end__", INPUT = "__input__", ERROR2 = "__error__", CACHE_NS_WRITES = "__pregel_ns_writes", CONFIG_KEY_SEND = "__pregel_send", CONFIG_KEY_CALL = "__pregel_call", CONFIG_KEY_READ = "__pregel_read", CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer", CONFIG_KEY_RESUMING = "__pregel_resuming", CONFIG_KEY_TASK_ID = "__pregel_task_id", CONFIG_KEY_STREAM = "__pregel_stream", CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value", CONFIG_KEY_RESUME_MAP = "__pregel_resume_map", CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad", CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous", CONFIG_KEY_DURABILITY = "__pregel_durability", CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id", CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns", CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished", CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map", CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals", INTERRUPT = "__interrupt__", RESUME = "__resume__", NO_WRITES = "__no_writes__", RETURN = "__return__", PREVIOUS = "__previous__", TAG_HIDDEN = "langsmith:hidden", SELF = "__self__", TASKS = "__pregel_tasks", PUSH = "__pregel_push", PULL = "__pregel_pull", NULL_TASK_ID = "00000000-0000-0000-0000-000000000000", RESERVED, COMMAND_SYMBOL, CommandInstance, Send = class { + lg_name = "Send"; + node; + args; + constructor(node, args) { + this.node = node; + this.args = _deserializeCommandSendObjectGraph(args); + } + toJSON() { return { - metadata(jsonSchemaExtra) { - return withLangGraph(zodThis, { jsonSchemaExtra }); - }, - reducer(fn, schema) { - return withLangGraph(zodThis, { - default: getInteropZodDefaultGetter(zodThis), - reducer: { - schema, - fn - } - }); - } + lg_name: this.lg_name, + node: this.node, + args: this.args }; - } }); - cache2.add(prototype); -} -var metaSymbol; -var init_plugin = __esm(() => { - init_meta(); - init_v43(); - init_types3(); - init_v3(); - metaSymbol = Symbol.for("langgraph-zod"); - if (!(metaSymbol in globalThis)) - globalThis[metaSymbol] = /* @__PURE__ */ new WeakSet; - try { - applyPluginPrototype(exports_external2.ZodType.prototype); - applyPluginPrototype(exports_external.ZodType.prototype); - } catch (error51) { - throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.", { cause: error51 }); } -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/zod/zod-registry.js -var LanggraphZodMetaRegistry, registry2; -var init_zod_registry = __esm(() => { - init_meta(); - init_types3(); - init_core2(); - LanggraphZodMetaRegistry = class extends $ZodRegistry { - constructor(parent) { - super(); - this.parent = parent; - this._map = this.parent._map; +}, OVERWRITE = "__overwrite__", Overwrite, Command; +var init_constants3 = __esm(() => { + RESERVED = [ + TAG_HIDDEN, + INPUT, + INTERRUPT, + RESUME, + ERROR2, + NO_WRITES, + CONFIG_KEY_SEND, + CONFIG_KEY_READ, + CONFIG_KEY_CHECKPOINTER, + CONFIG_KEY_DURABILITY, + CONFIG_KEY_STREAM, + CONFIG_KEY_RESUMING, + CONFIG_KEY_TASK_ID, + CONFIG_KEY_CALL, + CONFIG_KEY_RESUME_VALUE, + CONFIG_KEY_SCRATCHPAD, + CONFIG_KEY_PREVIOUS_STATE, + CONFIG_KEY_CHECKPOINT_MAP, + CONFIG_KEY_CHECKPOINT_NS, + CONFIG_KEY_CHECKPOINT_ID + ]; + COMMAND_SYMBOL = Symbol.for("langgraph.command"); + CommandInstance = class { + [COMMAND_SYMBOL]; + constructor(args) { + this[COMMAND_SYMBOL] = args; } - add(schema, ..._meta) { - const firstMeta = _meta[0]; - if (firstMeta && !firstMeta?.default) { - const defaultValueGetter = getInteropZodDefaultGetter(schema); - if (defaultValueGetter != null) - firstMeta.default = defaultValueGetter; - } - return super.add(schema, ..._meta); + }; + Overwrite = class { + lg_name = "Overwrite"; + [OVERWRITE]; + constructor(value) { + this[OVERWRITE] = value; + } + get value() { + return this[OVERWRITE]; + } + toJSON() { + return { [OVERWRITE]: this[OVERWRITE] }; + } + static isInstance(value) { + if (!value || typeof value !== "object") + return false; + if ("__overwrite__" in value) + return true; + if ("lg_name" in value && value.lg_name === "Overwrite") + return true; + return false; + } + }; + Command = class extends CommandInstance { + lg_name = "Command"; + lc_direct_tool_output = true; + graph; + update; + resume; + goto = []; + static PARENT = "__parent__"; + constructor(args) { + super(args); + this.resume = args.resume; + this.graph = args.graph; + this.update = args.update; + if (args.goto) + this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; + } + _updateAsTuples() { + if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) + return Object.entries(this.update); + else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) + return this.update; + else + return [["__root__", this.update]]; + } + toJSON() { + let serializedGoto; + if (typeof this.goto === "string") + serializedGoto = this.goto; + else if (_isSend(this.goto)) + serializedGoto = this.goto.toJSON(); + else + serializedGoto = this.goto?.map((innerGoto) => { + if (typeof innerGoto === "string") + return innerGoto; + else + return innerGoto.toJSON(); + }); + return { + lg_name: this.lg_name, + update: this.update, + resume: this.resume, + goto: serializedGoto + }; } }; - registry2 = new LanggraphZodMetaRegistry(schemaMetaRegistry); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_kxoyozq5widi3q7f66ec6onzcq/node_modules/@langchain/langgraph/dist/graph/zod/index.js -var init_zod3 = __esm(() => { - init_meta(); - init_plugin(); - init_zod_registry(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/annotation.js -function createAgentState(hasStructuredResponse = true, stateSchema, middlewareList = []) { - const stateFields = { jumpTo: new UntrackedValue }; - const inputFields = {}; - const outputFields = {}; - const applySchema = (schema) => { - if (StateSchema.isInstance(schema)) { - for (const [key, field] of Object.entries(schema.fields)) - if (!(key in stateFields)) { - stateFields[key] = field; - if (key.startsWith("_")) - continue; - if (ReducedValue.isInstance(field)) { - inputFields[key] = field.inputSchema || field.valueSchema; - outputFields[key] = field.valueSchema; - } else { - inputFields[key] = field; - outputFields[key] = field; - } - } - return; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/errors.js +function isParentCommand(e) { + return e !== undefined && e.name === ParentCommand.unminifiable_name; +} +function isGraphBubbleUp(e) { + return e !== undefined && e.is_bubble_up === true; +} +function isGraphInterrupt(e) { + return e !== undefined && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); +} +var BaseLangGraphError, GraphBubbleUp, GraphRecursionError, GraphValueError, GraphInterrupt, NodeInterrupt, ParentCommand, EmptyInputError, EmptyChannelError, InvalidUpdateError, MultipleSubgraphsError, UnreachableNodeError, RemoteException, StateGraphInputError, getSubgraphsSeenSet = () => { + if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === undefined) + globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set; + return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; +}; +var init_errors7 = __esm(() => { + BaseLangGraphError = class extends Error { + lc_error_code; + constructor(message, fields) { + let finalMessage = message ?? ""; + if (fields?.lc_error_code) + finalMessage = `${finalMessage} + +Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/ +`; + super(finalMessage); + this.lc_error_code = fields?.lc_error_code; } - const shape = getInteropZodObjectShape(schema); - for (const [key, fieldSchema] of Object.entries(shape)) { - const isPrivate = key.startsWith("_"); - if (!(key in stateFields)) { - if (isZodSchemaV4(fieldSchema)) { - const meta3 = schemaMetaRegistry.get(fieldSchema); - if (meta3?.reducer) { - if (meta3.reducer.schema) { - stateFields[key] = new ReducedValue(fieldSchema, { - inputSchema: meta3.reducer.schema, - reducer: meta3.reducer.fn - }); - if (!isPrivate) { - inputFields[key] = meta3.reducer.schema; - outputFields[key] = fieldSchema; - } - } else { - stateFields[key] = new ReducedValue(fieldSchema, { reducer: meta3.reducer.fn }); - if (!isPrivate) { - inputFields[key] = fieldSchema; - outputFields[key] = fieldSchema; - } - } - continue; - } - } - stateFields[key] = fieldSchema; - if (!isPrivate) { - inputFields[key] = fieldSchema; - outputFields[key] = fieldSchema; - } - } + }; + GraphBubbleUp = class extends BaseLangGraphError { + get is_bubble_up() { + return true; } }; - if (stateSchema && (StateSchema.isInstance(stateSchema) || isInteropZodObject(stateSchema))) - applySchema(stateSchema); - for (const middleware of middlewareList) - if (middleware.stateSchema && (StateSchema.isInstance(middleware.stateSchema) || isInteropZodObject(middleware.stateSchema))) - applySchema(middleware.stateSchema); - if (hasStructuredResponse) - outputFields.structuredResponse = new UntrackedValue; - return { - state: new StateSchema({ - messages: MessagesValue, - ...stateFields - }), - input: new StateSchema({ - messages: MessagesValue, - ...inputFields - }), - output: new StateSchema({ - messages: MessagesValue, - ...outputFields - }) + GraphRecursionError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphRecursionError"; + } + static get unminifiable_name() { + return "GraphRecursionError"; + } + }; + GraphValueError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphValueError"; + } + static get unminifiable_name() { + return "GraphValueError"; + } + }; + GraphInterrupt = class extends GraphBubbleUp { + interrupts; + constructor(interrupts, fields) { + super(JSON.stringify(interrupts, null, 2), fields); + this.name = "GraphInterrupt"; + this.interrupts = interrupts ?? []; + } + static get unminifiable_name() { + return "GraphInterrupt"; + } + }; + NodeInterrupt = class extends GraphInterrupt { + constructor(message, fields) { + super([{ value: message }], fields); + this.name = "NodeInterrupt"; + } + static get unminifiable_name() { + return "NodeInterrupt"; + } + }; + ParentCommand = class extends GraphBubbleUp { + command; + constructor(command) { + super(); + this.name = "ParentCommand"; + this.command = command; + } + static get unminifiable_name() { + return "ParentCommand"; + } + }; + EmptyInputError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyInputError"; + } + static get unminifiable_name() { + return "EmptyInputError"; + } + }; + EmptyChannelError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyChannelError"; + } + static get unminifiable_name() { + return "EmptyChannelError"; + } + }; + InvalidUpdateError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "InvalidUpdateError"; + } + static get unminifiable_name() { + return "InvalidUpdateError"; + } + }; + MultipleSubgraphsError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "MultipleSubgraphError"; + } + static get unminifiable_name() { + return "MultipleSubgraphError"; + } + }; + UnreachableNodeError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "UnreachableNodeError"; + } + static get unminifiable_name() { + return "UnreachableNodeError"; + } + }; + RemoteException = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "RemoteException"; + } + static get unminifiable_name() { + return "RemoteException"; + } + }; + StateGraphInputError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "StateGraphInputError"; + this.message = "Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."; + } + static get unminifiable_name() { + return "StateGraphInputError"; + } }; -} -var init_annotation2 = __esm(() => { - init_dist4(); - init_zod3(); - init_types3(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/utils.js -function parseMiddlewareState(stateSchema, state) { - if (StateSchema.isInstance(stateSchema)) { - const result = {}; - for (const key of Object.keys(stateSchema.fields)) - if (key in state) - result[key] = state[key]; - return result; +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/max.js +var require_max = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _default5 = exports.default = "ffffffff-ffff-ffff-ffff-ffffffffffff"; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/nil.js +var require_nil = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _default5 = exports.default = "00000000-0000-0000-0000-000000000000"; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/regex.js +var require_regex = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _default5 = exports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/validate.js +var require_validate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _regex3 = _interopRequireDefault(require_regex()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - if (isInteropZodSchema(stateSchema)) - return interopParse(stateSchema, state); - throw new Error(`Invalid state schema type: ${typeof stateSchema}`); -} -function _addInlineAgentName(message) { - if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) - return message; - if (!message.name) - return message; - const { name } = message; - if (typeof message.content === "string") - return new AIMessage({ - ...message.lc_kwargs, - content: `${name}${message.content}`, - name: undefined - }); - const updatedContent = []; - let textBlockCount = 0; - for (const contentBlock of message.content) - if (typeof contentBlock === "string") { - textBlockCount += 1; - updatedContent.push(`${name}${contentBlock}`); - } else if (typeof contentBlock === "object" && "type" in contentBlock && contentBlock.type === "text") { - textBlockCount += 1; - updatedContent.push({ - ...contentBlock, - text: `${name}${contentBlock.text}` - }); - } else - updatedContent.push(contentBlock); - if (!textBlockCount) - updatedContent.unshift({ - type: "text", - text: `${name}` - }); - return new AIMessage({ - ...message.lc_kwargs, - content: updatedContent, - name: undefined + function validate8(uuid8) { + return typeof uuid8 === "string" && _regex3.default.test(uuid8); + } + var _default5 = exports.default = validate8; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/parse.js +var require_parse = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true }); -} -function _removeInlineAgentName(message) { - if (!AIMessage.isInstance(message) || !message.content) - return message; - let updatedContent = []; - let updatedName; - if (Array.isArray(message.content)) - updatedContent = message.content.filter((block) => { - if (block.type === "text" && typeof block.text === "string") { - const nameMatch = block.text.match(NAME_PATTERN); - const contentMatch = block.text.match(CONTENT_PATTERN); - if (nameMatch && (!contentMatch || contentMatch[1] === "")) { - updatedName = nameMatch[1]; - return false; - } - return true; - } - return true; - }).map((block) => { - if (block.type === "text" && typeof block.text === "string") { - const nameMatch = block.text.match(NAME_PATTERN); - const contentMatch = block.text.match(CONTENT_PATTERN); - if (!nameMatch || !contentMatch) - return block; - updatedName = nameMatch[1]; - return { - ...block, - text: contentMatch[1] - }; - } - return block; - }); - else { - const content = message.content; - const nameMatch = content.match(NAME_PATTERN); - const contentMatch = content.match(CONTENT_PATTERN); - if (!nameMatch || !contentMatch) - return message; - updatedName = nameMatch[1]; - updatedContent = contentMatch[1]; + exports.default = undefined; + var _validate = _interopRequireDefault(require_validate()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - return new AIMessage({ - ...Object.keys(message.lc_kwargs ?? {}).length > 0 ? message.lc_kwargs : message, - content: updatedContent, - name: updatedName + function parse13(uuid8) { + if (!(0, _validate.default)(uuid8)) { + throw TypeError("Invalid UUID"); + } + let v; + const arr2 = new Uint8Array(16); + arr2[0] = (v = parseInt(uuid8.slice(0, 8), 16)) >>> 24; + arr2[1] = v >>> 16 & 255; + arr2[2] = v >>> 8 & 255; + arr2[3] = v & 255; + arr2[4] = (v = parseInt(uuid8.slice(9, 13), 16)) >>> 8; + arr2[5] = v & 255; + arr2[6] = (v = parseInt(uuid8.slice(14, 18), 16)) >>> 8; + arr2[7] = v & 255; + arr2[8] = (v = parseInt(uuid8.slice(19, 23), 16)) >>> 8; + arr2[9] = v & 255; + arr2[10] = (v = parseInt(uuid8.slice(24, 36), 16)) / 1099511627776 & 255; + arr2[11] = v / 4294967296 & 255; + arr2[12] = v >>> 24 & 255; + arr2[13] = v >>> 16 & 255; + arr2[14] = v >>> 8 & 255; + arr2[15] = v & 255; + return arr2; + } + var _default5 = exports.default = parse13; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/stringify.js +var require_stringify = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true }); -} -function isClientTool(tool2) { - return Runnable.isRunnable(tool2); -} -function _isChatModelWithBindTools(llm) { - if (!isBaseChatModel(llm)) - return false; - return "bindTools" in llm && typeof llm.bindTools === "function"; -} -function validateLLMHasNoBoundTools(llm) { - if (typeof llm === "function") - return; - let model = llm; - if (RunnableSequence.isRunnableSequence(model)) - model = model.steps.find((step) => RunnableBinding.isRunnableBinding(step)) || model; - if (isConfigurableModel(model)) - return; - if (RunnableBinding.isRunnableBinding(model)) { - const hasToolsInKwargs = model.kwargs != null && typeof model.kwargs === "object" && "tools" in model.kwargs && Array.isArray(model.kwargs.tools) && model.kwargs.tools.length > 0; - const hasToolsInConfig = model.config != null && typeof model.config === "object" && "tools" in model.config && Array.isArray(model.config.tools) && model.config.tools.length > 0; - if (hasToolsInKwargs || hasToolsInConfig) - throw new MultipleToolsBoundError; + exports.default = undefined; + exports.unsafeStringify = unsafeStringify4; + var _validate = _interopRequireDefault(require_validate()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - if ("tools" in model && model.tools !== undefined && Array.isArray(model.tools) && model.tools.length > 0) - throw new MultipleToolsBoundError; -} -function hasToolCalls(message) { - return Boolean(AIMessage.isInstance(message) && message.tool_calls && message.tool_calls.length > 0); -} -function normalizeSystemPrompt(systemPrompt) { - if (systemPrompt == null) - return new SystemMessage(""); - if (SystemMessage.isInstance(systemPrompt)) - return systemPrompt; - if (typeof systemPrompt === "string") - return new SystemMessage({ content: [{ - type: "text", - text: systemPrompt - }] }); - throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`); -} -async function bindTools(llm, toolClasses, options = {}) { - const model = _simpleBindTools(llm, toolClasses, options); - if (model) - return model; - if (isConfigurableModel(llm)) { - const model2 = _simpleBindTools(await llm._getModelInstance(), toolClasses, options); - if (model2) - return model2; + var byteToHex4 = []; + for (let i = 0;i < 256; ++i) { + byteToHex4.push((i + 256).toString(16).slice(1)); } - if (RunnableSequence.isRunnableSequence(llm)) { - const modelStep = llm.steps.findIndex((step) => RunnableBinding.isRunnableBinding(step) || isBaseChatModel(step) || isConfigurableModel(step)); - if (modelStep >= 0) { - const model2 = _simpleBindTools(llm.steps[modelStep], toolClasses, options); - if (model2) { - const nextSteps = llm.steps.slice(); - nextSteps.splice(modelStep, 1, model2); - return RunnableSequence.from(nextSteps); - } + function unsafeStringify4(arr2, offset = 0) { + return (byteToHex4[arr2[offset + 0]] + byteToHex4[arr2[offset + 1]] + byteToHex4[arr2[offset + 2]] + byteToHex4[arr2[offset + 3]] + "-" + byteToHex4[arr2[offset + 4]] + byteToHex4[arr2[offset + 5]] + "-" + byteToHex4[arr2[offset + 6]] + byteToHex4[arr2[offset + 7]] + "-" + byteToHex4[arr2[offset + 8]] + byteToHex4[arr2[offset + 9]] + "-" + byteToHex4[arr2[offset + 10]] + byteToHex4[arr2[offset + 11]] + byteToHex4[arr2[offset + 12]] + byteToHex4[arr2[offset + 13]] + byteToHex4[arr2[offset + 14]] + byteToHex4[arr2[offset + 15]]).toLowerCase(); + } + function stringify3(arr2, offset = 0) { + const uuid8 = unsafeStringify4(arr2, offset); + if (!(0, _validate.default)(uuid8)) { + throw TypeError("Stringified UUID is invalid"); } + return uuid8; } - throw new Error(`llm ${llm} must define bindTools method.`); -} -function chainToolCallHandlers(handlers) { - if (handlers.length === 0) - return; - if (handlers.length === 1) - return handlers[0]; - function composeTwo(outer, inner) { - return async (request, handler) => { - const innerHandler = async (passedRequest) => { - return inner(passedRequest, handler); - }; - return outer(request, innerHandler); - }; + var _default5 = exports.default = stringify3; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/rng.js +var require_rng = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = rng3; + var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - let result = handlers[handlers.length - 1]; - for (let i = handlers.length - 2;i >= 0; i--) - result = composeTwo(handlers[i], result); - return result; -} -function wrapToolCall(middleware) { - const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall); - if (middlewareWithWrapToolCall.length === 0) - return; - return chainToolCallHandlers(middlewareWithWrapToolCall.map((m) => { - const originalHandler = m.wrapToolCall; - const wrappedHandler = async (request, handler) => { - const originalState = request.state; - const wrappedInnerHandler = async (passedRequest) => { - const mergedState = { - ...originalState, - ...passedRequest.state - }; - return handler({ - ...passedRequest, - state: mergedState - }); - }; - try { - const result = await originalHandler({ - ...request, - state: { - messages: originalState.messages, - ...m.stateSchema ? parseMiddlewareState(m.stateSchema, { ...originalState }) : {} - } - }, wrappedInnerHandler); - if (!ToolMessage.isInstance(result) && !isCommand(result)) - throw new Error(`Invalid response from "wrapToolCall" in middleware "${m.name}": expected ToolMessage or Command, got ${typeof result}`); - return result; - } catch (error51) { - throw MiddlewareError.wrap(error51, m.name); - } - }; - return wrappedHandler; - })); -} -var NAME_PATTERN, CONTENT_PATTERN, _simpleBindTools = (llm, toolClasses, options = {}) => { - if (_isChatModelWithBindTools(llm)) - return llm.bindTools(toolClasses, options); - if (RunnableBinding.isRunnableBinding(llm) && _isChatModelWithBindTools(llm.bound)) { - const newBound = llm.bound.bindTools(toolClasses, options); - if (RunnableBinding.isRunnableBinding(newBound)) - return new RunnableBinding({ - bound: newBound.bound, - config: { - ...llm.config, - ...newBound.config - }, - kwargs: { - ...llm.kwargs, - ...newBound.kwargs - }, - configFactories: newBound.configFactories ?? llm.configFactories - }); - return new RunnableBinding({ - bound: newBound, - config: llm.config, - kwargs: llm.kwargs, - configFactories: llm.configFactories - }); + var rnds8Pool = new Uint8Array(256); + var poolPtr = rnds8Pool.length; + function rng3() { + if (poolPtr > rnds8Pool.length - 16) { + _nodeCrypto.default.randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, poolPtr += 16); } - return null; -}; -var init_utils12 = __esm(() => { - init_model(); - init_errors6(); - init_messages(); - init_runnables(); - init_dist4(); - init_types3(); - NAME_PATTERN = /(.*?)<\/name>/s; - CONTENT_PATTERN = /(.*?)<\/content>/s; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/utils.js -async function initializeMiddlewareStates(middlewareList, state) { - const middlewareStates = {}; - for (const middleware of middlewareList) { - if (!middleware.stateSchema) - continue; - let zodSchema = middleware.stateSchema; - if (StateSchema.isInstance(middleware.stateSchema)) { - const zodShape = {}; - for (const [key, field] of Object.entries(middleware.stateSchema.fields)) - if (ReducedValue.isInstance(field)) - zodShape[key] = field.inputSchema || field.valueSchema; - else - zodShape[key] = field; - zodSchema = exports_external.object(zodShape); +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v1.js +var require_v1 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _rng = _interopRequireDefault(require_rng()); + var _stringify2 = require_stringify(); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + var _nodeId; + var _clockseq; + var _lastMSecs = 0; + var _lastNSecs = 0; + function v13(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node; + let clockseq = options.clockseq; + if (!options._v6) { + if (!node) { + node = _nodeId; + } + if (clockseq == null) { + clockseq = _clockseq; + } } - const parseResult = await interopSafeParseAsync(interopZodObjectMakeFieldsOptional(zodSchema, (key) => key.startsWith("_")), state); - if (parseResult.success) { - Object.assign(middlewareStates, parseResult.data); - continue; + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + if (node == null) { + node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + if (!_nodeId && !options._v6) { + node[0] |= 1; + _nodeId = node; + } + } + if (clockseq == null) { + clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; + if (_clockseq === undefined && !options._v6) { + _clockseq = clockseq; + } + } } - const requiredFields = parseResult.error.issues.filter((issue2) => issue2.code === "invalid_type").map((issue2) => ` - ${issue2.path.join(".")}: Required`).join(` -`); - throw new Error(`Middleware "${middleware.name}" has required state fields that must be initialized: -${requiredFields} - -To fix this, either: -1. Provide default values in your middleware's state schema using .default(): - stateSchema: z.object({ - myField: z.string().default("default value") - }) + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 16383; + } + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + if (nsecs >= 1e4) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + msecs += 12219292800000; + const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; + b[i++] = tl >>> 24 & 255; + b[i++] = tl >>> 16 & 255; + b[i++] = tl >>> 8 & 255; + b[i++] = tl & 255; + const tmh = msecs / 4294967296 * 1e4 & 268435455; + b[i++] = tmh >>> 8 & 255; + b[i++] = tmh & 255; + b[i++] = tmh >>> 24 & 15 | 16; + b[i++] = tmh >>> 16 & 255; + b[i++] = clockseq >>> 8 | 128; + b[i++] = clockseq & 255; + for (let n2 = 0;n2 < 6; ++n2) { + b[i + n2] = node[n2]; + } + return buf || (0, _stringify2.unsafeStringify)(b); + } + var _default5 = exports.default = v13; +}); -2. Or make the fields optional using .optional(): - stateSchema: z.object({ - myField: z.string().optional() - }) +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v1ToV6.js +var require_v1ToV6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = v1ToV62; + var _parse3 = _interopRequireDefault(require_parse()); + var _stringify2 = require_stringify(); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function v1ToV62(uuid8) { + const v1Bytes2 = typeof uuid8 === "string" ? (0, _parse3.default)(uuid8) : uuid8; + const v6Bytes = _v1ToV62(v1Bytes2); + return typeof uuid8 === "string" ? (0, _stringify2.unsafeStringify)(v6Bytes) : v6Bytes; + } + function _v1ToV62(v1Bytes2, randomize = false) { + return Uint8Array.of((v1Bytes2[6] & 15) << 4 | v1Bytes2[7] >> 4 & 15, (v1Bytes2[7] & 15) << 4 | (v1Bytes2[4] & 240) >> 4, (v1Bytes2[4] & 15) << 4 | (v1Bytes2[5] & 240) >> 4, (v1Bytes2[5] & 15) << 4 | (v1Bytes2[0] & 240) >> 4, (v1Bytes2[0] & 15) << 4 | (v1Bytes2[1] & 240) >> 4, (v1Bytes2[1] & 15) << 4 | (v1Bytes2[2] & 240) >> 4, 96 | v1Bytes2[2] & 15, v1Bytes2[3], v1Bytes2[8], v1Bytes2[9], v1Bytes2[10], v1Bytes2[11], v1Bytes2[12], v1Bytes2[13], v1Bytes2[14], v1Bytes2[15]); + } +}); -3. Or ensure you pass these values when invoking the agent: - agent.invoke({ - messages: [...], - ${parseResult.error.issues[0]?.path.join(".")}: "value" - })`); +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v35.js +var require_v35 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.URL = exports.DNS = undefined; + exports.default = v354; + var _stringify2 = require_stringify(); + var _parse3 = _interopRequireDefault(require_parse()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - return middlewareStates; -} -function derivePrivateState(stateSchema) { - const builtInStateSchema = { - messages: exports_external.custom(() => []), - structuredResponse: exports_external.any().optional() - }; - if (!stateSchema) - return exports_external.object(builtInStateSchema); - let shape; - if (StateSchema.isInstance(stateSchema)) { - shape = {}; - for (const [key, field] of Object.entries(stateSchema.fields)) - if (ReducedValue.isInstance(field)) - shape[key] = field.inputSchema || field.valueSchema; - else - shape[key] = field; - } else - shape = getInteropZodObjectShape(stateSchema); - const privateShape = { ...builtInStateSchema }; - for (const [key, value] of Object.entries(shape)) - if (key.startsWith("_")) - privateShape[key] = value.optional(); - else - privateShape[key] = value; - return exports_external.object(privateShape); -} -function toPartialZodObject(schema) { - if (isInteropZodObject(schema)) - return interopZodObjectPartial(schema); - if (StateSchema.isInstance(schema)) { - const partialShape = {}; - for (const [key, field] of Object.entries(schema.fields)) { - let fieldSchema; - if (ReducedValue.isInstance(field)) - fieldSchema = field.inputSchema || field.valueSchema; - else - fieldSchema = field; - partialShape[key] = isZodSchemaV4(fieldSchema) ? fieldSchema.optional() : exports_external.any().optional(); + function stringToBytes4(str) { + str = unescape(encodeURIComponent(str)); + const bytes = []; + for (let i = 0;i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); } - return exports_external.object(partialShape); + return bytes; + } + var DNS4 = exports.DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + var URL5 = exports.URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + function v354(name, version5, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === "string") { + value = stringToBytes4(value); + } + if (typeof namespace === "string") { + namespace = (0, _parse3.default)(namespace); + } + if (((_namespace = namespace) === null || _namespace === undefined ? undefined : _namespace.length) !== 16) { + throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + } + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 15 | version5; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (let i = 0;i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, _stringify2.unsafeStringify)(bytes); + } + try { + generateUUID.name = name; + } catch (err) {} + generateUUID.DNS = DNS4; + generateUUID.URL = URL5; + return generateUUID; } - return exports_external.object({}); -} -function parseJumpToTarget(target) { - if (!target) - return; - if ([ - "model_request", - "tools", - END - ].includes(target)) - return target; - if (target === "model") - return "model_request"; - if (target === "tools") - return "tools"; - if (target === "end") - return END; - throw new Error(`Invalid jump target: ${target}, must be "model", "tools" or "end".`); -} -function mergeAbortSignals(...signals) { - return AbortSignal.any(signals.filter((maybeSignal) => maybeSignal !== null && maybeSignal !== undefined && typeof maybeSignal === "object" && ("aborted" in maybeSignal) && typeof maybeSignal.aborted === "boolean")); -} -var init_utils13 = __esm(() => { - init_dist4(); - init_types3(); - init_v43(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/RunnableCallable.js -var RunnableCallable2; -var init_RunnableCallable = __esm(() => { - init_runnables(); - init_singletons(); - RunnableCallable2 = class extends Runnable { - lc_namespace = ["langgraph"]; - func; - tags; - config; - trace = true; - recurse = true; - #state; - constructor(fields) { - super(); - this.name = fields.name ?? fields.func.name; - this.func = fields.func; - this.config = fields.tags ? { tags: fields.tags } : undefined; - this.recurse = fields.recurse ?? this.recurse; +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/md5.js +var require_md5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === "string") { + bytes = Buffer.from(bytes, "utf8"); } - getState() { - return this.#state; + return _nodeCrypto.default.createHash("md5").update(bytes).digest(); + } + var _default5 = exports.default = md5; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v3.js +var require_v3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _v = _interopRequireDefault(require_v35()); + var _md = _interopRequireDefault(require_md5()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + var v3 = (0, _v.default)("v3", 48, _md.default); + var _default5 = exports.default = v3; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/native.js +var require_native = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + var _default5 = exports.default = { + randomUUID: _nodeCrypto.default.randomUUID + }; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v4.js +var require_v4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _native = _interopRequireDefault(require_native()); + var _rng = _interopRequireDefault(require_rng()); + var _stringify2 = require_stringify(); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function v44(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); } - setState(state) { - this.#state = { - ...this.#state, - ...state - }; + options = options || {}; + const rnds = options.random || (options.rng || _rng.default)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (let i = 0;i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; } - async invoke(input, options) { - const mergedConfig = mergeConfigs(this.config, options); - const returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); - if (Runnable.isRunnable(returnValue) && this.recurse) - return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); - this.#state = returnValue; - return returnValue; + return (0, _stringify2.unsafeStringify)(rnds); + } + var _default5 = exports.default = v44; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/sha1.js +var require_sha1 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _nodeCrypto = _interopRequireDefault(__require("node:crypto")); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function sha14(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === "string") { + bytes = Buffer.from(bytes, "utf8"); } - }; + return _nodeCrypto.default.createHash("sha1").update(bytes).digest(); + } + var _default5 = exports.default = sha14; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/withAgentName.js -function withAgentName(model, agentNameMode) { - let processInputMessage; - let processOutputMessage; - if (agentNameMode === "inline") { - processInputMessage = _addInlineAgentName; - processOutputMessage = _removeInlineAgentName; - } else - throw new Error(`Invalid agent name mode: ${agentNameMode}. Needs to be one of: "inline"`); - function processInputMessages(messages) { - return messages.map(processInputMessage); +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v5.js +var require_v5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _v = _interopRequireDefault(require_v35()); + var _sha = _interopRequireDefault(require_sha1()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; } - return RunnableSequence.from([ - RunnableLambda.from(processInputMessages), - model, - RunnableLambda.from(processOutputMessage) - ]); -} -var init_withAgentName = __esm(() => { - init_utils12(); - init_runnables(); + var v55 = (0, _v.default)("v5", 80, _sha.default); + var _default5 = exports.default = v55; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/AgentNode.js -function isInternalModelResponse(response) { - return AIMessage.isInstance(response) || isCommand(response) || typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response; -} -var AGENT_NODE_NAME = "model_request", AgentNode; -var init_AgentNode = __esm(() => { - init_universal(); - init_model(); - init_errors6(); - init_utils12(); - init_RunnableCallable(); - init_utils13(); - init_withAgentName(); - init_responses(); - init_messages(); - init_runnables(); - init_dist4(); - init_types3(); - AgentNode = class extends RunnableCallable2 { - #options; - #systemMessage; - constructor(options) { - super({ - name: options.name ?? "model", - func: (input, config2) => this.#run(input, config2) - }); - this.#options = options; - this.#systemMessage = options.systemMessage; - } - async#getResponseFormat(model, responseFormat = this.#options.responseFormat) { - if (!responseFormat) - return; - let resolvedModel; - if (isConfigurableModel(model)) - resolvedModel = await model._getModelInstance(); - else if (typeof model !== "string") - resolvedModel = model; - const strategies = transformResponseFormat(responseFormat, undefined, resolvedModel); - if (strategies.length === 0) - return; - if (!strategies.every((format3) => format3 instanceof ProviderStrategy)) - return { - type: "tool", - tools: strategies.filter((format3) => format3 instanceof ToolStrategy).reduce((acc, format3) => { - acc[format3.name] = format3; - return acc; - }, {}) - }; - return { - type: "native", - strategy: strategies[0] - }; +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v6.js +var require_v6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = v63; + var _stringify2 = require_stringify(); + var _v = _interopRequireDefault(require_v1()); + var _v1ToV = _interopRequireDefault(require_v1ToV6()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function v63(options = {}, buf, offset = 0) { + let bytes = (0, _v.default)({ + ...options, + _v6: true + }, new Uint8Array(16)); + bytes = (0, _v1ToV.default)(bytes); + if (buf) { + for (let i = 0;i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; } - async#run(state, config2) { - const lastMessage = state.messages.at(-1); - if (lastMessage && ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name)) - return [new Command({ update: { messages: [] } })]; - const { response, lastAiMessage, collectedCommands } = await this.#invokeModel(state, config2); - if (typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response) { - const { structuredResponse, messages } = response; - return { - messages: [...state.messages, ...messages], - structuredResponse - }; + return (0, _stringify2.unsafeStringify)(bytes); + } +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v6ToV1.js +var require_v6ToV1 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = v6ToV1; + var _parse3 = _interopRequireDefault(require_parse()); + var _stringify2 = require_stringify(); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function v6ToV1(uuid8) { + const v6Bytes = typeof uuid8 === "string" ? (0, _parse3.default)(uuid8) : uuid8; + const v1Bytes2 = _v6ToV1(v6Bytes); + return typeof uuid8 === "string" ? (0, _stringify2.unsafeStringify)(v1Bytes2) : v1Bytes2; + } + function _v6ToV1(v6Bytes) { + return Uint8Array.of((v6Bytes[3] & 15) << 4 | v6Bytes[4] >> 4 & 15, (v6Bytes[4] & 15) << 4 | (v6Bytes[5] & 240) >> 4, (v6Bytes[5] & 15) << 4 | v6Bytes[6] & 15, v6Bytes[7], (v6Bytes[1] & 15) << 4 | (v6Bytes[2] & 240) >> 4, (v6Bytes[2] & 15) << 4 | (v6Bytes[3] & 240) >> 4, 16 | (v6Bytes[0] & 240) >> 4, (v6Bytes[0] & 15) << 4 | (v6Bytes[1] & 240) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); + } +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/v7.js +var require_v7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _rng = _interopRequireDefault(require_rng()); + var _stringify2 = require_stringify(); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + var _seqLow = null; + var _seqHigh = null; + var _msecs = 0; + function v74(options, buf, offset) { + options = options || {}; + let i = buf && offset || 0; + const b = buf || new Uint8Array(16); + const rnds = options.random || (options.rng || _rng.default)(); + const msecs = options.msecs !== undefined ? options.msecs : Date.now(); + let seq = options.seq !== undefined ? options.seq : null; + let seqHigh = _seqHigh; + let seqLow = _seqLow; + if (msecs > _msecs && options.msecs === undefined) { + _msecs = msecs; + if (seq !== null) { + seqHigh = null; + seqLow = null; } - const commands = []; - const aiMessage = AIMessage.isInstance(response) ? response : lastAiMessage; - if (aiMessage) { - aiMessage.name = this.name; - aiMessage.lc_kwargs.name = this.name; - if (this.#areMoreStepsNeeded(state, aiMessage)) - commands.push(new Command({ update: { messages: [new AIMessage({ - content: "Sorry, need more steps to process this request.", - name: this.name, - id: aiMessage.id - })] } })); - else - commands.push(new Command({ update: { messages: [aiMessage] } })); + } + if (seq !== null) { + if (seq > 2147483647) { + seq = 2147483647; } - if (isCommand(response) && !collectedCommands.includes(response)) - commands.push(response); - commands.push(...collectedCommands); - return commands; + seqHigh = seq >>> 19 & 4095; + seqLow = seq & 524287; } - #deriveModel() { - if (typeof this.#options.model === "string") - return initChatModel(this.#options.model); - if (this.#options.model) - return this.#options.model; - throw new Error("No model option was provided, either via `model` option."); + if (seqHigh === null || seqLow === null) { + seqHigh = rnds[6] & 127; + seqHigh = seqHigh << 8 | rnds[7]; + seqLow = rnds[8] & 63; + seqLow = seqLow << 8 | rnds[9]; + seqLow = seqLow << 5 | rnds[10] >>> 3; } - async#invokeModel(state, config2, options = {}) { - const model = await this.#deriveModel(); - const lgConfig = config2; - let currentSystemMessage = this.#systemMessage; - let lastAiMessage = null; - const collectedCommands = []; - const baseHandler = async (request) => { - validateLLMHasNoBoundTools(request.model); - const structuredResponseFormat = await this.#getResponseFormat(request.model, request.responseFormat); - const modelWithTools = await this.#bindTools(request.model, request, structuredResponseFormat); - const messages = [...currentSystemMessage.text === "" ? [] : [currentSystemMessage], ...request.messages]; - const signal = mergeAbortSignals(this.#options.signal, config2.signal); - const response = await raceWithSignal(modelWithTools.invoke(messages, { - ...config2, - signal - }), signal); - lastAiMessage = response; - if (structuredResponseFormat?.type === "native") { - const structuredResponse = structuredResponseFormat.strategy.parse(response); - if (structuredResponse) - return { - structuredResponse, - messages: [response] - }; - return response; - } - if (!structuredResponseFormat || !response.tool_calls) - return response; - const toolCalls = response.tool_calls.filter((call3) => (call3.name in structuredResponseFormat.tools)); - if (toolCalls.length === 0) - return response; - if (toolCalls.length > 1) - return this.#handleMultipleStructuredOutputs(response, toolCalls, structuredResponseFormat); - const toolMessageContent = structuredResponseFormat.tools[toolCalls[0].name]?.options?.toolMessageContent; - return this.#handleSingleStructuredOutput(response, toolCalls[0], structuredResponseFormat, toolMessageContent ?? options.lastMessage); - }; - const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? []; - let wrappedHandler = baseHandler; - for (let i = wrapperMiddleware.length - 1;i >= 0; i--) { - const middlewareEntry = wrapperMiddleware[i]; - const middleware = Array.isArray(middlewareEntry) ? middlewareEntry[0] : middlewareEntry; - if (middleware.wrapModelCall) { - const innerHandler = wrappedHandler; - const currentMiddleware = middleware; - wrappedHandler = async (request) => { - const baselineSystemMessage = currentSystemMessage; - const context2 = currentMiddleware.contextSchema ? interopParse(currentMiddleware.contextSchema, lgConfig?.context || {}) : lgConfig?.context; - const runtime = Object.freeze({ - context: context2, - store: lgConfig.store, - configurable: lgConfig.configurable, - writer: lgConfig.writer, - interrupt: lgConfig.interrupt, - signal: lgConfig.signal - }); - const requestWithStateAndRuntime = { - ...request, - state: { - ...middleware.stateSchema ? interopParse(toPartialZodObject(middleware.stateSchema), state) : {}, - messages: state.messages - }, - runtime - }; - const handlerWithValidation = async (req) => { - currentSystemMessage = baselineSystemMessage; - const modifiedTools = req.tools ?? []; - const registeredToolsByName = new Map(this.#options.toolClasses.filter(isClientTool).map((t) => [t.name, t])); - const addedClientTools = modifiedTools.filter((tool2) => isClientTool(tool2) && !registeredToolsByName.has(tool2.name)); - const replacedClientTools = modifiedTools.filter((tool2) => { - if (!isClientTool(tool2)) - return false; - const original = registeredToolsByName.get(tool2.name); - return original != null && original !== tool2; - }); - if (addedClientTools.length > 0) { - if (!this.#options.middleware?.some((m) => m.wrapToolCall != null)) - throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${addedClientTools.map((tool2) => tool2.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`); - } - if (replacedClientTools.length > 0) - throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${replacedClientTools.map((tool2) => tool2.name).join(", ")}. This is not supported.`); - let normalizedReq = req; - const hasSystemPromptChanged = req.systemPrompt !== currentSystemMessage.text; - const hasSystemMessageChanged = req.systemMessage !== currentSystemMessage; - if (hasSystemPromptChanged && hasSystemMessageChanged) - throw new Error("Cannot change both systemPrompt and systemMessage in the same request."); - if (hasSystemPromptChanged) { - currentSystemMessage = new SystemMessage({ content: [{ - type: "text", - text: req.systemPrompt - }] }); - normalizedReq = { - ...req, - systemPrompt: currentSystemMessage.text, - systemMessage: currentSystemMessage - }; - } - if (hasSystemMessageChanged) { - currentSystemMessage = new SystemMessage({ ...req.systemMessage }); - normalizedReq = { - ...req, - systemPrompt: currentSystemMessage.text, - systemMessage: currentSystemMessage - }; - } - const innerHandlerResult = await innerHandler(normalizedReq); - if (isCommand(innerHandlerResult) && lastAiMessage) { - if (!collectedCommands.includes(innerHandlerResult)) - collectedCommands.push(innerHandlerResult); - return lastAiMessage; - } - return innerHandlerResult; - }; - if (!currentMiddleware.wrapModelCall) - return handlerWithValidation(requestWithStateAndRuntime); - try { - const middlewareResponse = await currentMiddleware.wrapModelCall(requestWithStateAndRuntime, handlerWithValidation); - if (!isInternalModelResponse(middlewareResponse)) - throw new Error(`Invalid response from "wrapModelCall" in middleware "${currentMiddleware.name}": expected AIMessage or Command, got ${typeof middlewareResponse}`); - if (AIMessage.isInstance(middlewareResponse)) - lastAiMessage = middlewareResponse; - else if (isCommand(middlewareResponse)) - collectedCommands.push(middlewareResponse); - return middlewareResponse; - } catch (error51) { - throw MiddlewareError.wrap(error51, currentMiddleware.name); - } - }; + if (msecs + 1e4 > _msecs && seq === null) { + if (++seqLow > 524287) { + seqLow = 0; + if (++seqHigh > 4095) { + seqHigh = 0; + _msecs++; } } - currentSystemMessage = this.#systemMessage; - const initialRequest = { - model, - responseFormat: this.#options.responseFormat, - systemPrompt: currentSystemMessage?.text, - systemMessage: currentSystemMessage, - messages: state.messages, - tools: this.#options.toolClasses, - state, - runtime: Object.freeze({ - context: lgConfig?.context, - store: lgConfig.store, - configurable: lgConfig.configurable, - writer: lgConfig.writer, - interrupt: lgConfig.interrupt, - signal: lgConfig.signal - }) - }; - return { - response: await wrappedHandler(initialRequest), - lastAiMessage, - collectedCommands - }; + } else { + _msecs = msecs; } - #handleMultipleStructuredOutputs(response, toolCalls, responseFormat) { - const multipleStructuredOutputsError = new MultipleStructuredOutputsError(toolCalls.map((call3) => call3.name)); - return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0], responseFormat); + _seqHigh = seqHigh; + _seqLow = seqLow; + b[i++] = _msecs / 1099511627776 & 255; + b[i++] = _msecs / 4294967296 & 255; + b[i++] = _msecs / 16777216 & 255; + b[i++] = _msecs / 65536 & 255; + b[i++] = _msecs / 256 & 255; + b[i++] = _msecs & 255; + b[i++] = seqHigh >>> 4 & 15 | 112; + b[i++] = seqHigh & 255; + b[i++] = seqLow >>> 13 & 63 | 128; + b[i++] = seqLow >>> 5 & 255; + b[i++] = seqLow << 3 & 255 | rnds[10] & 7; + b[i++] = rnds[11]; + b[i++] = rnds[12]; + b[i++] = rnds[13]; + b[i++] = rnds[14]; + b[i++] = rnds[15]; + return buf || (0, _stringify2.unsafeStringify)(b); + } + var _default5 = exports.default = v74; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/version.js +var require_version = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.default = undefined; + var _validate = _interopRequireDefault(require_validate()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } + function version5(uuid8) { + if (!(0, _validate.default)(uuid8)) { + throw TypeError("Invalid UUID"); } - #handleSingleStructuredOutput(response, toolCall, responseFormat, lastMessage) { - const tool2 = responseFormat.tools[toolCall.name]; - try { - const structuredResponse = tool2.parse(toolCall.args); - return { - structuredResponse, - messages: [ - response, - new ToolMessage({ - tool_call_id: toolCall.id ?? "", - content: JSON.stringify(structuredResponse), - name: toolCall.name - }), - new AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`) - ] - }; - } catch (error51) { - return this.#handleToolStrategyError(error51, response, toolCall, responseFormat); - } + return parseInt(uuid8.slice(14, 15), 16); + } + var _default5 = exports.default = version5; +}); + +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/dist/index.js +var require_dist2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "MAX", { + enumerable: true, + get: function() { + return _max.default; } - async#handleToolStrategyError(error51, response, toolCall, responseFormat) { - const errorHandler2 = Object.values(responseFormat.tools).at(0)?.options?.handleError; - const toolCallId = toolCall.id; - if (!toolCallId) - throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID."); - if (errorHandler2 === false) - throw error51; - if (errorHandler2 === undefined || typeof errorHandler2 === "boolean" && errorHandler2 || Array.isArray(errorHandler2) && errorHandler2.some((h) => h instanceof MultipleStructuredOutputsError)) - return new Command({ - update: { messages: [response, new ToolMessage({ - content: error51.message, - tool_call_id: toolCallId - })] }, - goto: AGENT_NODE_NAME - }); - if (typeof errorHandler2 === "string") - return new Command({ - update: { messages: [response, new ToolMessage({ - content: errorHandler2, - tool_call_id: toolCallId - })] }, - goto: AGENT_NODE_NAME - }); - if (typeof errorHandler2 === "function") { - const content = await errorHandler2(error51); - if (typeof content !== "string") - throw new Error("Error handler must return a string."); - return new Command({ - update: { messages: [response, new ToolMessage({ - content, - tool_call_id: toolCallId - })] }, - goto: AGENT_NODE_NAME - }); - } - return new Command({ - update: { messages: [response, new ToolMessage({ - content: error51.message, - tool_call_id: toolCallId - })] }, - goto: AGENT_NODE_NAME - }); + }); + Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function() { + return _nil.default; } - #areMoreStepsNeeded(state, response) { - const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call3) => this.#options.shouldReturnDirect.has(call3.name)); - const remainingSteps = "remainingSteps" in state ? state.remainingSteps : undefined; - return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages.at(-1)))); + }); + Object.defineProperty(exports, "parse", { + enumerable: true, + get: function() { + return _parse3.default; } - async#bindTools(model, preparedOptions, structuredResponseFormat) { - const options = {}; - const structuredTools = Object.values(structuredResponseFormat && "tools" in structuredResponseFormat ? structuredResponseFormat.tools : {}); - const allTools = [...preparedOptions?.tools ?? this.#options.toolClasses, ...structuredTools.map((toolStrategy) => toolStrategy.tool)]; - const toolChoice = preparedOptions?.toolChoice || (structuredTools.length > 0 ? "any" : undefined); - if (structuredResponseFormat?.type === "native") { - const resolvedStrict = preparedOptions?.modelSettings?.strict ?? structuredResponseFormat?.strategy?.strict ?? true; - const jsonSchemaParams = { - name: structuredResponseFormat.strategy.schema?.name ?? "extract", - description: getSchemaDescription(structuredResponseFormat.strategy.schema), - schema: structuredResponseFormat.strategy.schema, - strict: resolvedStrict - }; - Object.assign(options, { - response_format: { - type: "json_schema", - json_schema: jsonSchemaParams - }, - outputConfig: { format: { - type: "json_schema", - schema: structuredResponseFormat.strategy.schema - } }, - responseSchema: structuredResponseFormat.strategy.schema, - ls_structured_output_format: { - kwargs: { method: "json_schema" }, - schema: structuredResponseFormat.strategy.schema - }, - strict: resolvedStrict - }); - } - const modelWithTools = await bindTools(model, allTools, { - ...options, - ...preparedOptions?.modelSettings, - tool_choice: toolChoice - }); - return this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools; + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return _stringify2.default; } - getState() { - const state = super.getState(); - return { - messages: [], - ...state && !isCommand(state) ? state : {} - }; + }); + Object.defineProperty(exports, "v1", { + enumerable: true, + get: function() { + return _v.default; } - }; + }); + Object.defineProperty(exports, "v1ToV6", { + enumerable: true, + get: function() { + return _v1ToV.default; + } + }); + Object.defineProperty(exports, "v3", { + enumerable: true, + get: function() { + return _v2.default; + } + }); + Object.defineProperty(exports, "v4", { + enumerable: true, + get: function() { + return _v3.default; + } + }); + Object.defineProperty(exports, "v5", { + enumerable: true, + get: function() { + return _v43.default; + } + }); + Object.defineProperty(exports, "v6", { + enumerable: true, + get: function() { + return _v5.default; + } + }); + Object.defineProperty(exports, "v6ToV1", { + enumerable: true, + get: function() { + return _v6ToV.default; + } + }); + Object.defineProperty(exports, "v7", { + enumerable: true, + get: function() { + return _v6.default; + } + }); + Object.defineProperty(exports, "validate", { + enumerable: true, + get: function() { + return _validate.default; + } + }); + Object.defineProperty(exports, "version", { + enumerable: true, + get: function() { + return _version.default; + } + }); + var _max = _interopRequireDefault(require_max()); + var _nil = _interopRequireDefault(require_nil()); + var _parse3 = _interopRequireDefault(require_parse()); + var _stringify2 = _interopRequireDefault(require_stringify()); + var _v = _interopRequireDefault(require_v1()); + var _v1ToV = _interopRequireDefault(require_v1ToV6()); + var _v2 = _interopRequireDefault(require_v3()); + var _v3 = _interopRequireDefault(require_v4()); + var _v43 = _interopRequireDefault(require_v5()); + var _v5 = _interopRequireDefault(require_v6()); + var _v6ToV = _interopRequireDefault(require_v6ToV1()); + var _v6 = _interopRequireDefault(require_v7()); + var _validate = _interopRequireDefault(require_validate()); + var _version = _interopRequireDefault(require_version()); + function _interopRequireDefault(e) { + return e && e.__esModule ? e : { default: e }; + } }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/ToolNode.js -function defaultHandleToolErrors(error51, toolCall) { - if (error51 instanceof ToolInvocationError) - return new ToolMessage({ - content: error51.message, - tool_call_id: toolCall.id, - name: toolCall.name - }); - return new ToolMessage({ - content: `${error51} - Please fix your mistakes.`, - tool_call_id: toolCall.id, - name: toolCall.name - }); +// ../../node_modules/.pnpm/uuid@10.0.0/node_modules/uuid/wrapper.mjs +var import_dist, v13, v1ToV62, v3, v44, v55, v63, v6ToV1, v74, NIL2, MAX2, version5, validate8, stringify3, parse13; +var init_wrapper = __esm(() => { + import_dist = __toESM(require_dist2(), 1); + v13 = import_dist.default.v1; + v1ToV62 = import_dist.default.v1ToV6; + v3 = import_dist.default.v3; + v44 = import_dist.default.v4; + v55 = import_dist.default.v5; + v63 = import_dist.default.v6; + v6ToV1 = import_dist.default.v6ToV1; + v74 = import_dist.default.v7; + NIL2 = import_dist.default.NIL; + MAX2 = import_dist.default.MAX; + version5 = import_dist.default.version; + validate8 = import_dist.default.validate; + stringify3 = import_dist.default.stringify; + parse13 = import_dist.default.parse; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/id.js +function uuid63(clockseq) { + return v63({ clockseq }); } -function isSend(x) { - return x instanceof Send; +function uuid52(name, namespace) { + const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); + return v55(name, new Uint8Array(namespaceBytes)); } -var getInvalidToolError = (toolName, availableTools) => `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(", ")}].`, TOOLS_NODE_NAME = "tools", isBaseMessageArray = (input) => Array.isArray(input) && input.every(BaseMessage.isInstance), isMessagesState = (input) => typeof input === "object" && input != null && ("messages" in input) && isBaseMessageArray(input.messages), isSendInput = (input) => typeof input === "object" && input != null && ("lg_tool_call" in input), ToolNode; -var init_ToolNode = __esm(() => { - init_errors6(); - init_RunnableCallable(); - init_utils13(); - init_messages(); - init_tools2(); - init_dist4(); - ToolNode = class extends RunnableCallable2 { - tools; - trace = false; - signal; - handleToolErrors = defaultHandleToolErrors; - wrapToolCall; - constructor(tools, options) { - const { name, tags, handleToolErrors, signal, wrapToolCall: wrapToolCall2 } = options ?? {}; - super({ - name, - tags, - func: (state, config2) => this.run(state, config2) - }); - this.options = options; - this.tools = tools; - this.handleToolErrors = handleToolErrors ?? this.handleToolErrors; - this.signal = signal; - this.wrapToolCall = wrapToolCall2; - } - #handleError(error51, call3, isMiddlewareError) { - if (isGraphInterrupt(error51)) - throw error51; - if (this.signal?.aborted) - throw error51; - if (isMiddlewareError && this.handleToolErrors !== true) - throw error51; - if (!this.handleToolErrors) - throw error51; - if (typeof this.handleToolErrors === "function") { - const result = this.handleToolErrors(error51, call3); - if (result && ToolMessage.isInstance(result)) - return result; - throw error51; - } else if (this.handleToolErrors) - return new ToolMessage({ - name: call3.name, - content: `${error51} - Please fix your mistakes.`, - tool_call_id: call3.id - }); - throw error51; +var init_id3 = __esm(() => { + init_wrapper(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js +var TASKS2 = "__pregel_tasks", ERROR3 = "__error__", SCHEDULED = "__scheduled__", INTERRUPT2 = "__interrupt__", RESUME2 = "__resume__"; +var init_types5 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js +function defaultOptions3() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; +} +function stringify4(obj, replacer, spacer, options) { + if (typeof options === "undefined") + options = defaultOptions3(); + decirc2(obj, "", 0, [], undefined, 0, options); + var res; + try { + if (replacerStack2.length === 0) + res = JSON.stringify(obj, replacer, spacer); + else + res = JSON.stringify(obj, replaceGetterValues2(replacer), spacer); + } catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (arr2.length !== 0) { + var part = arr2.pop(); + if (part.length === 4) + Object.defineProperty(part[0], part[1], part[3]); + else + part[0][part[1]] = part[2]; } - async runTool(call3, config2, state) { - const lgConfig = config2; - const runtime = { - context: lgConfig?.context, - store: lgConfig?.store, - configurable: lgConfig?.configurable, - writer: lgConfig?.writer, - interrupt: lgConfig?.interrupt, - signal: lgConfig?.signal - }; - const registeredTool = this.tools.find((t) => t.name === call3.name); - const baseHandler = async (request2) => { - const { toolCall, tool: requestTool } = request2; - const tool2 = requestTool ?? this.tools.find((t) => t.name === toolCall.name); - if (tool2 === undefined) { - const availableTools = this.tools.map((t) => t.name); - return new ToolMessage({ - content: getInvalidToolError(toolCall.name, availableTools), - tool_call_id: toolCall.id, - name: toolCall.name, - status: "error" - }); - } - const invokableTool = tool2; - try { - const output = await invokableTool.invoke({ - ...toolCall, - type: "tool_call" - }, { - ...config2, - config: config2, - toolCallId: toolCall.id, - state: config2.configurable?.__pregel_scratchpad?.currentTaskInput, - signal: mergeAbortSignals(this.signal, config2.signal) - }); - if (ToolMessage.isInstance(output) || isCommand(output)) - return output; - return new ToolMessage({ - name: invokableTool.name, - content: typeof output === "string" ? output : JSON.stringify(output), - tool_call_id: toolCall.id - }); - } catch (e) { - if (e instanceof ToolInputParsingException) - throw new ToolInvocationError(e, toolCall); - throw e; - } - }; - const request = { - toolCall: call3, - tool: registeredTool, - state, - runtime - }; - if (this.wrapToolCall) - try { - return await this.wrapToolCall(request, baseHandler); - } catch (e) { - return this.#handleError(e, call3, true); - } - if (!registeredTool) { - const availableTools = this.tools.map((t) => t.name); - return new ToolMessage({ - content: getInvalidToolError(call3.name, availableTools), - tool_call_id: call3.id, - name: call3.name, - status: "error" - }); + } + return res; +} +function setReplace2(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr2.push([ + parent, + k, + val, + propertyDescriptor + ]); + } else + replacerStack2.push([ + val, + k, + replace + ]); + else { + parent[k] = replace; + arr2.push([ + parent, + k, + val + ]); + } +} +function decirc2(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0;i < stack.length; i++) + if (stack[i] === val) { + setReplace2(CIRCULAR_REPLACE_NODE2, val, k, parent); + return; } - try { - return await baseHandler(request); - } catch (e) { - return this.#handleError(e, call3, false); + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + setReplace2(LIMIT_REPLACE_NODE2, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + setReplace2(LIMIT_REPLACE_NODE2, val, k, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) + for (i = 0;i < val.length; i++) + decirc2(val[i], i, i, stack, val, depth, options); + else { + var keys = Object.keys(val); + for (i = 0;i < keys.length; i++) { + var key = keys[i]; + decirc2(val[key], key, i, stack, val, depth, options); } } - async run(state, config2) { - let outputs; - if (isSendInput(state)) { - const { lg_tool_call: _, jumpTo: __, ...newState } = state; - outputs = [await this.runTool(state.lg_tool_call, config2, newState)]; - } else { - let messages; - if (isBaseMessageArray(state)) - messages = state; - else if (isMessagesState(state)) - messages = state.messages; - else - throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input."); - const toolMessageIds = new Set(messages.filter((msg) => msg.getType() === "tool").map((msg) => msg.tool_call_id)); - let aiMessage; - for (let i = messages.length - 1;i >= 0; i -= 1) { - const message = messages[i]; - if (AIMessage.isInstance(message)) { - aiMessage = message; - break; - } + stack.pop(); + } +} +function replaceGetterValues2(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { + return v; + }; + return function(key, val) { + if (replacerStack2.length > 0) + for (var i = 0;i < replacerStack2.length; i++) { + var part = replacerStack2[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack2.splice(i, 1); + break; } - if (!AIMessage.isInstance(aiMessage)) - throw new Error("ToolNode only accepts AIMessages as input."); - outputs = await Promise.all(aiMessage.tool_calls?.filter((call3) => call3.id == null || !toolMessageIds.has(call3.id)).map((call3) => this.runTool(call3, config2, state)) ?? []); } - if (!outputs.some(isCommand)) - return Array.isArray(state) ? outputs : { messages: outputs }; - const combinedOutputs = []; - let parentCommand = null; - for (const output of outputs) - if (isCommand(output)) - if (output.graph === Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => isSend(send))) - if (parentCommand) - parentCommand.goto.push(...output.goto); - else - parentCommand = new Command({ - graph: Command.PARENT, - goto: output.goto - }); - else - combinedOutputs.push(output); - else - combinedOutputs.push(Array.isArray(state) ? [output] : { messages: [output] }); - if (parentCommand) - combinedOutputs.push(parentCommand); - return combinedOutputs; - } + return replacer.call(this, key, val); }; +} +var LIMIT_REPLACE_NODE2 = "[...]", CIRCULAR_REPLACE_NODE2 = "[Circular]", arr2, replacerStack2; +var init_fast_safe_stringify2 = __esm(() => { + arr2 = []; + replacerStack2 = []; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/middleware.js -var AgentContext = class { -}, AgentRuntime = class { -}, MiddlewareNode; -var init_middleware2 = __esm(() => { - init_RunnableCallable(); - init_utils13(); - init_utils10(); - init_types3(); - MiddlewareNode = class extends RunnableCallable2 { - constructor(fields) { - super(fields); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/import_constants.js +var optionalImportEntrypoints; +var init_import_constants = __esm(() => { + optionalImportEntrypoints = []; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/index.js +var src_exports; +var init_dist2 = __esm(() => { + init_runtime2(); + src_exports = /* @__PURE__ */ __exportAll({}); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/agents.js +var agents_exports; +var init_agents = __esm(() => { + init_runtime2(); + agents_exports = /* @__PURE__ */ __exportAll({}); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/chat_history.js +var chat_history_exports, BaseChatMessageHistory, BaseListChatMessageHistory, InMemoryChatMessageHistory; +var init_chat_history = __esm(() => { + init_runtime2(); + init_serializable(); + init_ai(); + init_human(); + init_messages(); + chat_history_exports = /* @__PURE__ */ __exportAll({ + BaseChatMessageHistory: () => BaseChatMessageHistory, + BaseListChatMessageHistory: () => BaseListChatMessageHistory, + InMemoryChatMessageHistory: () => InMemoryChatMessageHistory + }); + BaseChatMessageHistory = class extends Serializable { + async addMessages(messages) { + for (const message of messages) + await this.addMessage(message); } - async invokeMiddleware(invokeState, config2) { - let filteredContext = {}; - if (this.middleware.contextSchema) { - const schemaShape = this.middleware.contextSchema?.shape; - if (schemaShape) { - const relevantContext = {}; - const invokeContext = config2?.context || {}; - for (const key of Object.keys(schemaShape)) - if (key in invokeContext) - relevantContext[key] = invokeContext[key]; - filteredContext = interopParse(this.middleware.contextSchema, relevantContext); - } - } - const state = { - ...invokeState, - messages: invokeState.messages - }; - const runtime = { - context: filteredContext, - store: config2?.store, - configurable: config2?.configurable, - writer: config2?.writer, - interrupt: config2?.interrupt, - signal: config2?.signal - }; - const result = await this.runHook(state, Object.freeze(Object.assign(new AgentRuntime, { - ...runtime, - context: Object.freeze(Object.assign(new AgentContext, filteredContext)) - }))); - if (!result) - return { jumpTo: undefined }; - let jumpToConstraint; - let constraint; - if (this.name?.startsWith("BeforeAgentNode_")) { - jumpToConstraint = getHookConstraint(this.middleware.beforeAgent); - constraint = "beforeAgent.canJumpTo"; - } else if (this.name?.startsWith("BeforeModelNode_")) { - jumpToConstraint = getHookConstraint(this.middleware.beforeModel); - constraint = "beforeModel.canJumpTo"; - } else if (this.name?.startsWith("AfterAgentNode_")) { - jumpToConstraint = getHookConstraint(this.middleware.afterAgent); - constraint = "afterAgent.canJumpTo"; - } else if (this.name?.startsWith("AfterModelNode_")) { - jumpToConstraint = getHookConstraint(this.middleware.afterModel); - constraint = "afterModel.canJumpTo"; - } - if (typeof result.jumpTo === "string" && !jumpToConstraint?.includes(result.jumpTo)) { - const suggestion = jumpToConstraint && jumpToConstraint.length > 0 ? `must be one of: ${jumpToConstraint?.join(", ")}.` : constraint ? `no ${constraint} defined in middleware ${this.middleware.name}` : ""; - throw new Error(`Invalid jump target: ${result.jumpTo}, ${suggestion}.`); - } - if (typeof result === "object" && "type" in result) { - if (result.type === "terminate") { - if (result.error) - throw result.error; - return { - ...state, - ...result.result || {}, - jumpTo: result.jumpTo - }; - } - throw new Error(`Invalid control action: ${JSON.stringify(result)}`); - } - return { - ...state, - ...result, - jumpTo: result.jumpTo - }; + }; + BaseListChatMessageHistory = class extends Serializable { + addUserMessage(message) { + return this.addMessage(new HumanMessage(message)); } - get nodeOptions() { - return { input: derivePrivateState(this.middleware.stateSchema) }; + addAIMessage(message) { + return this.addMessage(new AIMessage(message)); } - }; -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/BeforeAgentNode.js -var BeforeAgentNode; -var init_BeforeAgentNode = __esm(() => { - init_utils10(); - init_middleware2(); - BeforeAgentNode = class extends MiddlewareNode { - lc_namespace = [ - "langchain", - "agents", - "beforeAgentNodes" - ]; - constructor(middleware) { - super({ - name: `BeforeAgentNode_${middleware.name}`, - func: async (state, config2) => this.invokeMiddleware(state, config2) - }); - this.middleware = middleware; + async addMessages(messages) { + for (const message of messages) + await this.addMessage(message); } - runHook(state, runtime) { - return getHookFunction(this.middleware.beforeAgent)(state, runtime); + clear() { + throw new Error("Not implemented."); } }; -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/BeforeModelNode.js -var BeforeModelNode; -var init_BeforeModelNode = __esm(() => { - init_utils10(); - init_middleware2(); - BeforeModelNode = class extends MiddlewareNode { + InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { lc_namespace = [ "langchain", - "agents", - "beforeModelNodes" + "stores", + "message", + "in_memory" ]; - constructor(middleware) { - super({ - name: `BeforeModelNode_${middleware.name}`, - func: async (state, config2) => this.invokeMiddleware(state, config2) - }); - this.middleware = middleware; + messages = []; + constructor(messages) { + super(...arguments); + this.messages = messages ?? []; } - runHook(state, runtime) { - return getHookFunction(this.middleware.beforeModel)(state, runtime); + async getMessages() { + return this.messages; + } + async addMessage(message) { + this.messages.push(message); + } + async clear() { + this.messages = []; } }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/AfterModelNode.js -var AfterModelNode; -var init_AfterModelNode = __esm(() => { - init_utils10(); - init_middleware2(); - AfterModelNode = class extends MiddlewareNode { +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/documents/document.js +var Document = class { + pageContent; + metadata; + id; + constructor(fields) { + this.pageContent = fields.pageContent !== undefined ? fields.pageContent.toString() : ""; + this.metadata = fields.metadata ?? {}; + this.id = fields.id; + } +}; +var init_document = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/documents/transformers.js +var BaseDocumentTransformer, MappingDocumentTransformer; +var init_transformers2 = __esm(() => { + init_base4(); + BaseDocumentTransformer = class extends Runnable { lc_namespace = [ - "langchain", - "agents", - "afterModelNodes" + "langchain_core", + "documents", + "transformers" ]; - constructor(middleware) { - super({ - name: `AfterModelNode_${middleware.name}`, - func: async (state, config2) => this.invokeMiddleware(state, config2) - }); - this.middleware = middleware; + invoke(input, _options) { + return this.transformDocuments(input); } - runHook(state, runtime) { - return getHookFunction(this.middleware.afterModel)(state, runtime); + }; + MappingDocumentTransformer = class extends BaseDocumentTransformer { + async transformDocuments(documents) { + const newDocuments = []; + for (const document2 of documents) { + const transformedDocument = await this._transformDocument(document2); + newDocuments.push(transformedDocument); + } + return newDocuments; } }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/nodes/AfterAgentNode.js -var AfterAgentNode; -var init_AfterAgentNode = __esm(() => { - init_utils10(); - init_middleware2(); - AfterAgentNode = class extends MiddlewareNode { - lc_namespace = [ - "langchain", - "agents", - "afterAgentNodes" - ]; - constructor(middleware) { - super({ - name: `AfterAgentNode_${middleware.name}`, - func: async (state, config2) => this.invokeMiddleware(state, config2) - }); - this.middleware = middleware; - } - runHook(state, runtime) { - return getHookFunction(this.middleware.afterAgent)(state, runtime); - } - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/documents/index.js +var documents_exports; +var init_documents = __esm(() => { + init_runtime2(); + init_document(); + init_transformers2(); + documents_exports = /* @__PURE__ */ __exportAll({ + BaseDocumentTransformer: () => BaseDocumentTransformer, + Document: () => Document, + MappingDocumentTransformer: () => MappingDocumentTransformer + }); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/ReactAgent.js -var ReactAgent = class ReactAgent2 { - #graph; - #toolBehaviorVersion = "v2"; - #agentNode; - #defaultConfig; - constructor(options, defaultConfig) { - this.options = options; - this.#defaultConfig = mergeConfigs(defaultConfig ?? {}, { - metadata: { ls_integration: "langchain_create_agent" }, - configurable: { ls_agent_type: "root" } - }); - if (options.name) - this.#defaultConfig = mergeConfigs(this.#defaultConfig, { metadata: { lc_agent_name: options.name } }); - this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion; - if (!options.model) - throw new Error("`model` option is required to create an agent."); - if (typeof options.model !== "string") - validateLLMHasNoBoundTools(options.model); - const middlewareTools = this.options.middleware?.filter((m) => m.tools).flatMap((m) => m.tools) ?? []; - const toolClasses = [...options.tools ?? [], ...middlewareTools]; - const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool2) => ("returnDirect" in tool2) && tool2.returnDirect).map((tool2) => tool2.name)); - const hasDynamicStructuredResponse = Boolean(this.options.middleware?.some((middleware2) => middleware2.wrapModelCall)); - const { state, input, output } = createAgentState(this.options.responseFormat !== undefined || hasDynamicStructuredResponse, this.options.stateSchema, this.options.middleware); - const allNodeWorkflows = new StateGraph(state, { - input, - output, - context: this.options.contextSchema - }); - const beforeAgentNodes = []; - const beforeModelNodes = []; - const afterModelNodes = []; - const afterAgentNodes = []; - const wrapModelCallHookMiddleware = []; - this.#agentNode = new AgentNode({ - model: this.options.model, - systemMessage: normalizeSystemPrompt(this.options.systemPrompt), - includeAgentName: this.options.includeAgentName, - name: this.options.name, - responseFormat: this.options.responseFormat, - middleware: this.options.middleware, - toolClasses, - shouldReturnDirect, - signal: this.options.signal, - wrapModelCallHookMiddleware - }); - const middlewareNames = /* @__PURE__ */ new Set; - const middleware = this.options.middleware ?? []; - for (let i = 0;i < middleware.length; i++) { - let beforeAgentNode; - let beforeModelNode; - let afterModelNode; - let afterAgentNode; - const m = middleware[i]; - if (middlewareNames.has(m.name)) - throw new Error(`Middleware ${m.name} is defined multiple times`); - middlewareNames.add(m.name); - if (m.beforeAgent) { - beforeAgentNode = new BeforeAgentNode(m); - const name = `${m.name}.before_agent`; - beforeAgentNodes.push({ - index: i, - name, - allowed: getHookConstraint(m.beforeAgent) - }); - allNodeWorkflows.addNode(name, beforeAgentNode, beforeAgentNode.nodeOptions); - } - if (m.beforeModel) { - beforeModelNode = new BeforeModelNode(m); - const name = `${m.name}.before_model`; - beforeModelNodes.push({ - index: i, - name, - allowed: getHookConstraint(m.beforeModel) - }); - allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions); - } - if (m.afterModel) { - afterModelNode = new AfterModelNode(m); - const name = `${m.name}.after_model`; - afterModelNodes.push({ - index: i, - name, - allowed: getHookConstraint(m.afterModel) +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/document_loaders/base.js +var base_exports4, BaseDocumentLoader = class { +}; +var init_base7 = __esm(() => { + init_runtime2(); + base_exports4 = /* @__PURE__ */ __exportAll({ BaseDocumentLoader: () => BaseDocumentLoader }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/document_loaders/langsmith.js +function _stringify2(x) { + if (typeof x === "string") + return x; + else + try { + return JSON.stringify(x, null, 2); + } catch { + return String(x); + } +} +var langsmith_exports, LangSmithLoader; +var init_langsmith2 = __esm(() => { + init_runtime2(); + init_base7(); + init_langsmith(); + langsmith_exports = /* @__PURE__ */ __exportAll({ LangSmithLoader: () => LangSmithLoader }); + LangSmithLoader = class extends BaseDocumentLoader { + datasetId; + datasetName; + exampleIds; + asOf; + splits; + inlineS3Urls; + offset; + limit; + metadata; + filter; + contentKey; + formatContent; + client; + constructor(fields) { + super(); + if (fields.client && fields.clientConfig) + throw new Error("client and clientConfig cannot both be provided."); + this.client = fields.client ?? new Client(fields?.clientConfig); + this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; + this.formatContent = fields.formatContent ?? _stringify2; + this.datasetId = fields.datasetId; + this.datasetName = fields.datasetName; + this.exampleIds = fields.exampleIds; + this.asOf = fields.asOf; + this.splits = fields.splits; + this.inlineS3Urls = fields.inlineS3Urls; + this.offset = fields.offset; + this.limit = fields.limit; + this.metadata = fields.metadata; + this.filter = fields.filter; + } + async load() { + const documents = []; + for await (const example of this.client.listExamples({ + datasetId: this.datasetId, + datasetName: this.datasetName, + exampleIds: this.exampleIds, + asOf: this.asOf, + splits: this.splits, + inlineS3Urls: this.inlineS3Urls, + offset: this.offset, + limit: this.limit, + metadata: this.metadata, + filter: this.filter + })) { + let content = example.inputs; + for (const key of this.contentKey) + content = content[key]; + const contentStr = this.formatContent(content); + const metadata = example; + ["created_at", "modified_at"].forEach((k) => { + if (k in metadata) { + if (typeof metadata[k] === "object") + metadata[k] = metadata[k].toString(); + } }); - allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions); - } - if (m.afterAgent) { - afterAgentNode = new AfterAgentNode(m); - const name = `${m.name}.after_agent`; - afterAgentNodes.push({ - index: i, - name, - allowed: getHookConstraint(m.afterAgent) + documents.push({ + pageContent: contentStr, + metadata }); - allNodeWorkflows.addNode(name, afterAgentNode, afterAgentNode.nodeOptions); } - if (m.wrapModelCall) - wrapModelCallHookMiddleware.push(m); + return documents; } - allNodeWorkflows.addNode(AGENT_NODE_NAME, this.#agentNode); - const hasWrapToolCallMiddleware = middleware.some((m) => m.wrapToolCall); - const clientTools = toolClasses.filter(isClientTool); - if (clientTools.length > 0 || hasWrapToolCallMiddleware) { - const toolNode = new ToolNode(clientTools, { - signal: this.options.signal, - wrapToolCall: wrapToolCall(middleware) - }); - allNodeWorkflows.addNode(TOOLS_NODE_NAME, toolNode); + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/embeddings.js +var embeddings_exports, Embeddings = class { + caller; + constructor(params) { + this.caller = new AsyncCaller2(params ?? {}); + } +}; +var init_embeddings = __esm(() => { + init_runtime2(); + init_async_caller2(); + embeddings_exports = /* @__PURE__ */ __exportAll({ Embeddings: () => Embeddings }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/example_selectors/base.js +var BaseExampleSelector; +var init_base8 = __esm(() => { + init_serializable(); + BaseExampleSelector = class extends Serializable { + lc_namespace = [ + "langchain_core", + "example_selectors", + "base" + ]; + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/example_selectors/conditional.js +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} +var BasePromptSelector = class { + async getPromptAsync(llm, options) { + return this.getPrompt(llm).partial(options?.partialVariables ?? {}); + } +}, ConditionalPromptSelector; +var init_conditional = __esm(() => { + ConditionalPromptSelector = class extends BasePromptSelector { + defaultPrompt; + conditionals; + constructor(default_prompt, conditionals = []) { + super(); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; } - let entryNode; - if (beforeAgentNodes.length > 0) - entryNode = beforeAgentNodes[0].name; - else if (beforeModelNodes.length > 0) - entryNode = beforeModelNodes[0].name; - else - entryNode = AGENT_NODE_NAME; - const loopEntryNode = beforeModelNodes.length > 0 ? beforeModelNodes[0].name : AGENT_NODE_NAME; - const exitNode = afterAgentNodes.length > 0 ? afterAgentNodes[afterAgentNodes.length - 1].name : END; - allNodeWorkflows.addEdge(START, entryNode); - const hasToolsAvailable = clientTools.length > 0 || hasWrapToolCallMiddleware; - for (let i = 0;i < beforeAgentNodes.length; i++) { - const node = beforeAgentNodes[i]; - const current = node.name; - const nextDefault = i === beforeAgentNodes.length - 1 ? loopEntryNode : beforeAgentNodes[i + 1].name; - if (node.allowed && node.allowed.length > 0) { - const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); - const destinations = Array.from(new Set([nextDefault, ...allowedMapped.map((dest) => dest === END ? exitNode : dest)])); - allNodeWorkflows.addConditionalEdges(current, this.#createBeforeAgentRouter(clientTools, nextDefault, exitNode, hasToolsAvailable), destinations); - } else - allNodeWorkflows.addEdge(current, nextDefault); + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) + if (condition(llm)) + return prompt; + return this.defaultPrompt; } - for (let i = 0;i < beforeModelNodes.length; i++) { - const node = beforeModelNodes[i]; - const current = node.name; - const nextDefault = i === beforeModelNodes.length - 1 ? AGENT_NODE_NAME : beforeModelNodes[i + 1].name; - if (node.allowed && node.allowed.length > 0) { - const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); - const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); - allNodeWorkflows.addConditionalEdges(current, this.#createBeforeModelRouter(clientTools, nextDefault, hasToolsAvailable), destinations); - } else - allNodeWorkflows.addEdge(current, nextDefault); + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/example_selectors/length_based.js +function getLengthBased(text) { + return text.split(/\n| /).length; +} +var LengthBasedExampleSelector; +var init_length_based = __esm(() => { + init_base8(); + LengthBasedExampleSelector = class LengthBasedExampleSelector2 extends BaseExampleSelector { + examples = []; + examplePrompt; + getTextLength = getLengthBased; + maxLength = 2048; + exampleTextLengths = []; + constructor(data) { + super(data); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; } - const lastAfterModelNode = afterModelNodes.at(-1); - if (afterModelNodes.length > 0 && lastAfterModelNode) - allNodeWorkflows.addEdge(AGENT_NODE_NAME, lastAfterModelNode.name); - else { - const destinations = this.#getModelPaths(clientTools, false, hasToolsAvailable).map((p) => p === END ? exitNode : p); - if (destinations.length === 1) - allNodeWorkflows.addEdge(AGENT_NODE_NAME, destinations[0]); + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + async calculateExampleTextLengths(v, values) { + if (v.length > 0) + return v; + const { examples, examplePrompt } = values; + return (await Promise.all(examples.map((eg) => examplePrompt.format(eg)))).map((eg) => this.getTextLength(eg)); + } + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) + break; + else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + static async fromExamples(examples, args) { + const selector = new LengthBasedExampleSelector2(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js +function sortedValues(values) { + return Object.keys(values).sort().map((key) => values[key]); +} +var SemanticSimilarityExampleSelector; +var init_semantic_similarity = __esm(() => { + init_document(); + init_base8(); + SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector2 extends BaseExampleSelector { + vectorStoreRetriever; + exampleKeys; + inputKeys; + constructor(data) { + super(data); + this.exampleKeys = data.exampleKeys; + this.inputKeys = data.inputKeys; + if (data.vectorStore !== undefined) + this.vectorStoreRetriever = data.vectorStore.asRetriever({ + k: data.k ?? 4, + filter: data.filter + }); + else if (data.vectorStoreRetriever) + this.vectorStoreRetriever = data.vectorStoreRetriever; else - allNodeWorkflows.addConditionalEdges(AGENT_NODE_NAME, this.#createModelRouter(exitNode), destinations); + throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); } - for (let i = afterModelNodes.length - 1;i > 0; i--) { - const node = afterModelNodes[i]; - const current = node.name; - const nextDefault = afterModelNodes[i - 1].name; - if (node.allowed && node.allowed.length > 0) { - const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); - const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); - allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); - } else - allNodeWorkflows.addEdge(current, nextDefault); + async addExample(example) { + const stringExample = sortedValues((this.inputKeys ?? Object.keys(example)).reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})).join(" "); + await this.vectorStoreRetriever.addDocuments([new Document({ + pageContent: stringExample, + metadata: example + })]); } - if (afterModelNodes.length > 0) { - const firstAfterModel = afterModelNodes[0]; - const firstAfterModelNode = firstAfterModel.name; - const modelPaths = this.#getModelPaths(clientTools, true, hasToolsAvailable).filter((p) => p !== "tools" || hasToolsAvailable); - const allowJump = Boolean(firstAfterModel.allowed && firstAfterModel.allowed.length > 0); - const destinations = modelPaths.map((p) => p === END ? exitNode : p); - allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createAfterModelRouter(clientTools, allowJump, exitNode, hasToolsAvailable), destinations); + async selectExamples(inputVariables) { + const query3 = sortedValues((this.inputKeys ?? Object.keys(inputVariables)).reduce((acc, key) => ({ + ...acc, + [key]: inputVariables[key] + }), {})).join(" "); + const examples = (await this.vectorStoreRetriever.invoke(query3)).map((doc3) => doc3.metadata); + if (this.exampleKeys) + return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})); + return examples; } - for (let i = afterAgentNodes.length - 1;i > 0; i--) { - const node = afterAgentNodes[i]; - const current = node.name; - const nextDefault = afterAgentNodes[i - 1].name; - if (node.allowed && node.allowed.length > 0) { - const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); - const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); - allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); - } else - allNodeWorkflows.addEdge(current, nextDefault); + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {}) : example).join(" ")); + return new SemanticSimilarityExampleSelector2({ + vectorStore: await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options), + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys + }); } - if (afterAgentNodes.length > 0) { - const firstAfterAgent = afterAgentNodes[0]; - const firstAfterAgentNode = firstAfterAgent.name; - if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) { - const allowedMapped = firstAfterAgent.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); - const destinations = Array.from(new Set([END, ...allowedMapped])); - allNodeWorkflows.addConditionalEdges(firstAfterAgentNode, this.#createAfterModelSequenceRouter(clientTools, firstAfterAgent.allowed, END, hasToolsAvailable), destinations); - } else - allNodeWorkflows.addEdge(firstAfterAgentNode, END); + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/example_selectors/index.js +var example_selectors_exports; +var init_example_selectors = __esm(() => { + init_runtime2(); + init_base8(); + init_conditional(); + init_length_based(); + init_semantic_similarity(); + example_selectors_exports = /* @__PURE__ */ __exportAll({ + BaseExampleSelector: () => BaseExampleSelector, + BasePromptSelector: () => BasePromptSelector, + ConditionalPromptSelector: () => ConditionalPromptSelector, + LengthBasedExampleSelector: () => LengthBasedExampleSelector, + SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, + isChatModel: () => isChatModel, + isLLM: () => isLLM + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/indexing/record_manager.js +var UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a", RecordManager; +var init_record_manager = __esm(() => { + init_serializable(); + RecordManager = class extends Serializable { + lc_namespace = ["langchain", "recordmanagers"]; + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/indexing/base.js +function _batch(size, iterable) { + const batches = []; + let currentBatch = []; + iterable.forEach((item) => { + currentBatch.push(item); + if (currentBatch.length >= size) { + batches.push(currentBatch); + currentBatch = []; } - if (hasToolsAvailable) { - const toolReturnTarget = loopEntryNode; - if (shouldReturnDirect.size > 0) - allNodeWorkflows.addConditionalEdges(TOOLS_NODE_NAME, this.#createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget), [toolReturnTarget, exitNode]); - else - allNodeWorkflows.addEdge(TOOLS_NODE_NAME, toolReturnTarget); + }); + if (currentBatch.length > 0) + batches.push(currentBatch); + return batches; +} +function _deduplicateInOrder(hashedDocuments) { + const seen = /* @__PURE__ */ new Set; + const deduplicated = []; + for (const hashedDoc of hashedDocuments) { + if (!hashedDoc.hash_) + throw new Error("Hashed document does not have a hash"); + if (!seen.has(hashedDoc.hash_)) { + seen.add(hashedDoc.hash_); + deduplicated.push(hashedDoc); } - const compileTransformers = [createToolCallTransformer([]), ...this.options.streamTransformers ?? []]; - this.#graph = allNodeWorkflows.compile({ - checkpointer: this.options.checkpointer, - store: this.options.store, - name: this.options.name, - description: this.options.description, - transformers: compileTransformers - }); - } - get graph() { - return this.#graph; - } - get checkpointer() { - return this.#graph.checkpointer; - } - set checkpointer(value) { - this.#graph.checkpointer = value; - } - get store() { - return this.#graph.store; - } - set store(value) { - this.#graph.store = value; - } - withConfig(config2) { - return new ReactAgent2(this.options, mergeConfigs(this.#defaultConfig, config2)); - } - #getModelPaths(toolClasses, includeModelRequest = false, hasToolsAvailable = toolClasses.length > 0) { - const paths = []; - if (hasToolsAvailable) - paths.push(TOOLS_NODE_NAME); - if (includeModelRequest) - paths.push(AGENT_NODE_NAME); - paths.push(END); - return paths; - } - #createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget) { - return (state) => { - const messages = state.messages; - const lastMessage = messages[messages.length - 1]; - if (ToolMessage.isInstance(lastMessage) && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) - return this.options.responseFormat ? toolReturnTarget : exitNode; - return toolReturnTarget; - }; - } - #createModelRouter(exitNode = END) { - return (state) => { - const lastMessage = state.messages.at(-1); - if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) - return exitNode; - if (lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-"))) - return exitNode; - if (this.#toolBehaviorVersion === "v1") - return TOOLS_NODE_NAME; - const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); - if (regularToolCalls.length === 0) - return exitNode; - return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { - ...state, - lg_tool_call: toolCall - })); - }; - } - #createAfterModelRouter(toolClasses, allowJump, exitNode, hasToolsAvailable = toolClasses.length > 0) { - const hasStructuredResponse = Boolean(this.options.responseFormat); - return (state) => { - const builtInState = state; - const messages = builtInState.messages; - const lastMessage = messages.at(-1); - if (AIMessage.isInstance(lastMessage) && (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)) - return exitNode; - if (allowJump && builtInState.jumpTo) { - const destination = parseJumpToTarget(builtInState.jumpTo); - if (destination === END) - return exitNode; - if (destination === "tools") { - if (!hasToolsAvailable) - return exitNode; - return new Send(TOOLS_NODE_NAME, { - ...state, - jumpTo: undefined - }); - } - return new Send(AGENT_NODE_NAME, { - ...state, - jumpTo: undefined - }); - } - const toolMessages = messages.filter(ToolMessage.isInstance); - const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1); - const pendingToolCalls = lastAiMessage?.tool_calls?.filter((call3) => !toolMessages.some((m) => m.tool_call_id === call3.id)); - if (pendingToolCalls && pendingToolCalls.length > 0) { - if (this.#toolBehaviorVersion === "v1") - return TOOLS_NODE_NAME; - return pendingToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { - ...state, - lg_tool_call: toolCall - })); - } - const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some((toolCall) => toolCall.name.startsWith("extract-")); - if (pendingToolCalls && pendingToolCalls.length === 0 && !hasStructuredResponseCalls && hasStructuredResponse) - return AGENT_NODE_NAME; - if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) - return exitNode; - const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-")); - const hasRegularToolCalls = lastMessage.tool_calls.some((toolCall) => !toolCall.name.startsWith("extract-")); - if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) - return exitNode; - if (this.#toolBehaviorVersion === "v1") - return TOOLS_NODE_NAME; - const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); - if (regularToolCalls.length === 0) - return exitNode; - return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { - ...state, - lg_tool_call: toolCall - })); - }; } - #createAfterModelSequenceRouter(toolClasses, allowed, nextDefault, hasToolsAvailable = toolClasses.length > 0) { - const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t))); - return (state) => { - const builtInState = state; - if (builtInState.jumpTo) { - const dest = parseJumpToTarget(builtInState.jumpTo); - if (dest === END && allowedSet.has(END)) - return END; - if (dest === "tools" && allowedSet.has("tools")) { - if (!hasToolsAvailable) - return END; - return new Send(TOOLS_NODE_NAME, { - ...state, - jumpTo: undefined - }); + return deduplicated; +} +function _getSourceIdAssigner(sourceIdKey) { + if (sourceIdKey === null) + return (_doc) => null; + else if (typeof sourceIdKey === "string") + return (doc3) => doc3.metadata[sourceIdKey]; + else if (typeof sourceIdKey === "function") + return sourceIdKey; + else + throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); +} +async function index(args) { + const { docsSource, recordManager, vectorStore, options } = args; + const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1000, forceUpdate = false } = options ?? {}; + if (cleanup === "incremental" && !sourceIdKey) + throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); + const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; + const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); + const indexStartDt = await recordManager.getTime(); + let numAdded = 0; + let numDeleted = 0; + let numUpdated = 0; + let numSkipped = 0; + const batches = _batch(batchSize ?? 100, docs); + for (const batch of batches) { + const hashedDocs = _deduplicateInOrder(batch.map((doc3) => _HashedDocument.fromDocument(doc3))); + const sourceIds = hashedDocs.map((doc3) => sourceIdAssigner(doc3)); + if (cleanup === "incremental") + hashedDocs.forEach((_hashedDoc, index2) => { + if (sourceIds[index2] === null) + throw new Error("sourceIdKey must be provided when cleanup is incremental"); + }); + const batchExists = await recordManager.exists(hashedDocs.map((doc3) => doc3.uid)); + const uids = []; + const docsToIndex = []; + const docsToUpdate = []; + const seenDocs = /* @__PURE__ */ new Set; + hashedDocs.forEach((hashedDoc, i) => { + if (batchExists[i]) + if (forceUpdate) + seenDocs.add(hashedDoc.uid); + else { + docsToUpdate.push(hashedDoc.uid); + return; } - if (dest === "model_request" && allowedSet.has("model_request")) - return new Send(AGENT_NODE_NAME, { - ...state, - jumpTo: undefined - }); - } - return nextDefault; - }; - } - #createBeforeAgentRouter(toolClasses, nextDefault, exitNode, hasToolsAvailable = toolClasses.length > 0) { - return (state) => { - const builtInState = state; - if (!builtInState.jumpTo) - return nextDefault; - const destination = parseJumpToTarget(builtInState.jumpTo); - if (destination === END) - return exitNode; - if (destination === "tools") { - if (!hasToolsAvailable) - return exitNode; - return new Send(TOOLS_NODE_NAME, { - ...state, - jumpTo: undefined - }); - } - return new Send(AGENT_NODE_NAME, { - ...state, - jumpTo: undefined + uids.push(hashedDoc.uid); + docsToIndex.push(hashedDoc.toDocument()); + }); + if (docsToUpdate.length > 0) { + await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); + numSkipped += docsToUpdate.length; + } + if (docsToIndex.length > 0) { + await vectorStore.addDocuments(docsToIndex, { ids: uids }); + numAdded += docsToIndex.length - seenDocs.size; + numUpdated += seenDocs.size; + } + await recordManager.update(hashedDocs.map((doc3) => doc3.uid), { + timeAtLeast: indexStartDt, + groupIds: sourceIds + }); + if (cleanup === "incremental") { + sourceIds.forEach((sourceId) => { + if (!sourceId) + throw new Error("Source id cannot be null"); }); - }; - } - #createBeforeModelRouter(toolClasses, nextDefault, hasToolsAvailable = toolClasses.length > 0) { - return (state) => { - const builtInState = state; - if (!builtInState.jumpTo) - return nextDefault; - const destination = parseJumpToTarget(builtInState.jumpTo); - if (destination === END) - return END; - if (destination === "tools") { - if (!hasToolsAvailable) - return END; - return new Send(TOOLS_NODE_NAME, { - ...state, - jumpTo: undefined - }); - } - return new Send(AGENT_NODE_NAME, { - ...state, - jumpTo: undefined + const uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + groupIds: sourceIds }); - }; - } - async#initializeMiddlewareStates(state, config2) { - if (!this.options.middleware || this.options.middleware.length === 0 || state instanceof Command || !state) - return state; - const defaultStates = await initializeMiddlewareStates(this.options.middleware, state); - const updatedState = { - ...(await this.#graph.getState(config2).catch(() => ({ values: {} }))).values, - ...state - }; - if (!updatedState) - return updatedState; - for (const [key, value] of Object.entries(defaultStates)) - if (!(key in updatedState)) - updatedState[key] = value; - return updatedState; - } - async invoke(state, config2) { - const mergedConfig = mergeConfigs(this.#defaultConfig, config2); - const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); - return this.#graph.invoke(initializedState, mergedConfig); - } - async stream(state, config2) { - const mergedConfig = mergeConfigs(this.#defaultConfig, config2); - const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); - return this.#graph.stream(initializedState, mergedConfig); - } - streamEvents(state, config2, streamOptions) { - if (config2?.version !== "v3" || streamOptions != null) { - const mergedConfig = mergeConfigs(this.#defaultConfig, config2); - const version4 = config2?.version === "v1" || config2?.version === "v2" ? config2.version : "v2"; - return this.#graph.streamEvents(state, { - ...mergedConfig, - version: version4 - }, streamOptions); + if (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + } } - return (async () => { - const { transformers: callSiteTransformers, version: _version, ...restConfig } = config2 ?? {}; - const mergedConfig = mergeConfigs(this.#defaultConfig, restConfig); - const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); - return await this.#graph.streamEvents(initializedState, { - ...mergedConfig, - version: "v3", - transformers: callSiteTransformers - }); - })(); - } - async drawMermaidPng(params) { - const arrayBuffer = await (await (await this.#graph.getGraphAsync()).drawMermaidPng(params)).arrayBuffer(); - return new Uint8Array(arrayBuffer); } - async drawMermaid(params) { - return (await this.#graph.getGraphAsync()).drawMermaid(params); + if (cleanup === "full") { + let uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + while (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + } } - getGraphAsync(config2) { - return this.#graph.getGraphAsync(config2); + return { + numAdded, + numDeleted, + numUpdated, + numSkipped + }; +} +var _HashedDocument = class { + uid; + hash_; + contentHash; + metadataHash; + pageContent; + metadata; + keyEncoder = sha256; + constructor(fields) { + this.uid = fields.uid; + this.pageContent = fields.pageContent; + this.metadata = fields.metadata; } - getState(config2, options) { - return this.#graph.getState(config2, options); + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; } - getStateHistory(config2, options) { - return this.#graph.getStateHistory(config2, options); + calculateHashes() { + const forbiddenKeys = [ + "hash_", + "content_hash", + "metadata_hash" + ]; + for (const key of forbiddenKeys) + if (key in this.metadata) + throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); + const contentHash = this._hashStringToUUID(this.pageContent); + try { + const metadataHash = this._hashNestedDictToUUID(this.metadata); + this.contentHash = contentHash; + this.metadataHash = metadataHash; + } catch (e) { + throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); + } + this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); + if (!this.uid) + this.uid = this.hash_; } - getSubgraphs(namespace, recurse) { - return this.#graph.getSubgraphs(namespace, recurse); + toDocument() { + return new Document({ + pageContent: this.pageContent, + metadata: this.metadata + }); } - getSubgraphsAsync(namespace, recurse) { - return this.#graph.getSubgraphsAsync(namespace, recurse); + static fromDocument(document2, uid) { + const doc3 = new this({ + pageContent: document2.pageContent, + metadata: document2.metadata, + uid: uid || document2.uid + }); + doc3.calculateHashes(); + return doc3; } - updateState(inputConfig, values, asNode) { - return this.#graph.updateState(inputConfig, values, asNode); + _hashStringToUUID(inputString) { + return v53(this.keyEncoder(inputString), UUIDV5_NAMESPACE); } - get builder() { - return this.#graph.builder; + _hashNestedDictToUUID(data) { + const serialized_data = JSON.stringify(data, Object.keys(data).sort()); + return v53(this.keyEncoder(serialized_data), UUIDV5_NAMESPACE); } +}, _isBaseDocumentLoader = (arg) => { + if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") + return true; + return false; }; -var init_ReactAgent = __esm(() => { - init_annotation2(); - init_utils12(); - init_utils13(); - init_AgentNode(); - init_ToolNode(); - init_utils10(); - init_BeforeAgentNode(); - init_BeforeModelNode(); - init_AfterModelNode(); - init_AfterAgentNode(); - init_stream6(); - init_messages(); - init_runnables(); - init_dist4(); +var init_base9 = __esm(() => { + init_hash(); + init_hash2(); + init_uuid(); + init_document(); + init_record_manager(); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/index.js -function createAgent(params) { - return new ReactAgent(params); -} -var init_agents2 = __esm(() => { - init_errors6(); - init_responses(); - init_stream6(); - init_ReactAgent(); - init_types10(); - init_middleware(); - init_utils11(); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/indexing/index.js +var indexing_exports; +var init_indexing = __esm(() => { + init_runtime2(); + init_record_manager(); + init_base9(); + indexing_exports = /* @__PURE__ */ __exportAll({ + RecordManager: () => RecordManager, + UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, + _HashedDocument: () => _HashedDocument, + _batch: () => _batch, + _deduplicateInOrder: () => _deduplicateInOrder, + _getSourceIdAssigner: () => _getSourceIdAssigner, + _isBaseDocumentLoader: () => _isBaseDocumentLoader, + index: () => index + }); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/hitl.js -function humanInTheLoopMiddleware(options) { - const createActionAndConfig = async (toolCall, config2, state, runtime) => { - const toolName = toolCall.name; - const toolArgs = toolCall.args; - const descriptionValue = config2.description; - let description; - if (typeof descriptionValue === "function") - description = await descriptionValue(toolCall, state, runtime); - else if (descriptionValue !== undefined) - description = descriptionValue; - else - description = `${options.descriptionPrefix ?? "Tool execution requires approval"} +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/event.js +var event_exports; +var init_event = __esm(() => { + init_runtime2(); + event_exports = /* @__PURE__ */ __exportAll({}); +}); -Tool: ${toolName} -Args: ${JSON.stringify(toolArgs, null, 2)}`; - const actionRequest = { - name: toolName, - args: toolArgs, - description - }; - const reviewConfig = { - actionName: toolName, - allowedDecisions: config2.allowedDecisions - }; - if (config2.argsSchema) - reviewConfig.argsSchema = config2.argsSchema; - return { - actionRequest, - reviewConfig - }; - }; - const processDecision = (decision, toolCall, config2) => { - const allowedDecisions = config2.allowedDecisions; - if (decision.type === "approve" && allowedDecisions.includes("approve")) - return { - revisedToolCall: toolCall, - toolMessage: null - }; - if (decision.type === "edit" && allowedDecisions.includes("edit")) { - const editedAction = decision.editedAction; - if (!editedAction || typeof editedAction.name !== "string") - throw new Error(`Invalid edited action for tool "${toolCall.name}": name must be a string`); - if (!editedAction.args || typeof editedAction.args !== "object") - throw new Error(`Invalid edited action for tool "${toolCall.name}": args must be an object`); - return { - revisedToolCall: { - type: "tool_call", - name: editedAction.name, - args: editedAction.args, - id: toolCall.id - }, - toolMessage: null - }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/llms.js +var llms_exports, BaseLLM, LLM; +var init_llms = __esm(() => { + init_runtime2(); + init_base2(); + init_manager(); + init_stream(); + init_outputs(); + init_base5(); + llms_exports = /* @__PURE__ */ __exportAll({ + BaseLLM: () => BaseLLM, + LLM: () => LLM + }); + BaseLLM = class BaseLLM2 extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "llms", + this._llmType() + ]; + async invoke(input, options) { + const promptValue = BaseLLM2._convertInputToPromptValue(input); + return (await this.generatePrompt([promptValue], options, options?.callbacks)).generations[0][0].text; } - if (decision.type === "reject" && allowedDecisions.includes("reject")) { - if (decision.message !== undefined && typeof decision.message !== "string") - throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof decision.message}`); - return { - revisedToolCall: toolCall, - toolMessage: new ToolMessage({ - content: decision.message ?? `User rejected the tool call for \`${toolCall.name}\` with id ${toolCall.id}`, - name: toolCall.name, - tool_call_id: toolCall.id, - status: "error" - }) - }; + async* _streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); } - const msg = `Unexpected human decision: ${JSON.stringify(decision)}. Decision type '${decision.type}' is not allowed for tool '${toolCall.name}'. Expected one of ${JSON.stringify(allowedDecisions)} based on the tool's configuration.`; - throw new Error(msg); - }; - return createMiddleware({ - name: "HumanInTheLoopMiddleware", - contextSchema, - afterModel: { - canJumpTo: ["model"], - hook: async (state, runtime) => { - const config2 = interopParse(contextSchema, { - ...options, - ...runtime.context || {} + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + async* _streamIterator(input, options) { + if (this._streamResponseChunks === BaseLLM2.prototype._streamResponseChunks) + yield this.invoke(input, options); + else { + const prompt = BaseLLM2._convertInputToPromptValue(input); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const invocationParams = this.invocationParams(callOptions); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) }); - if (!config2) - return; - const { messages } = state; - if (!messages.length) - return; - const lastMessage = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); - if (!lastMessage || !lastMessage.tool_calls?.length) - return; - if (!config2.interruptOn) - return; - const resolvedConfigs = {}; - for (const [toolName, toolConfig] of Object.entries(config2.interruptOn)) - if (typeof toolConfig === "boolean") { - if (toolConfig === true) - resolvedConfigs[toolName] = { allowedDecisions: [...ALLOWED_DECISIONS] }; - } else if (toolConfig.allowedDecisions) - resolvedConfigs[toolName] = toolConfig; - const interruptToolCalls = []; - const autoApprovedToolCalls = []; - for (const toolCall of lastMessage.tool_calls) - if (toolCall.name in resolvedConfigs) - interruptToolCalls.push(toolCall); - else - autoApprovedToolCalls.push(toolCall); - if (!interruptToolCalls.length) - return; - const actionRequests = []; - const reviewConfigs = []; - for (const toolCall of interruptToolCalls) { - const interruptConfig = resolvedConfigs[toolCall.name]; - const { actionRequest, reviewConfig } = await createActionAndConfig(toolCall, interruptConfig, state, runtime); - actionRequests.push(actionRequest); - reviewConfigs.push(reviewConfig); + const extra = { + options: callOptions, + invocation_params: invocationParams, + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); + let generation = new GenerationChunk({ text: "" }); + try { + for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { + if (!generation) + generation = chunk; + else + generation = generation.concat(chunk); + if (typeof chunk.text === "string") + yield chunk.text; + } + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; } - const decisions = (await interrupt({ - actionRequests, - reviewConfigs - })).decisions; - if (!decisions || !Array.isArray(decisions)) - throw new Error("Invalid HITLResponse: decisions must be a non-empty array"); - if (decisions.length !== interruptToolCalls.length) - throw new Error(`Number of human decisions (${decisions.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`); - const revisedToolCalls = [...autoApprovedToolCalls]; - const artificialToolMessages = []; - const hasRejectedToolCalls = decisions.some((decision) => decision.type === "reject"); - for (let i = 0;i < decisions.length; i++) { - const decision = decisions[i]; - const toolCall = interruptToolCalls[i]; - const interruptConfig = resolvedConfigs[toolCall.name]; - const { revisedToolCall, toolMessage } = processDecision(decision, toolCall, interruptConfig); - if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject")) - revisedToolCalls.push(revisedToolCall); - if (toolMessage) - artificialToolMessages.push(toolMessage); + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); + } + } + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); + } + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0;i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 0) + llmResults.push({ + generations: [genList], + llmOutput: llmResult.llmOutput + }); + else { + const llmOutput = llmResult.llmOutput ? { + ...llmResult.llmOutput, + tokenUsage: {} + } : undefined; + llmResults.push({ + generations: [genList], + llmOutput + }); } - if (AIMessage.isInstance(lastMessage)) - lastMessage.tool_calls = revisedToolCalls; - const jumpTo = hasRejectedToolCalls ? "model" : undefined; - return { - messages: [lastMessage, ...artificialToolMessages], - jumpTo + } + return llmResults; + } + async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { + let runManagers; + if (startedRunManagers !== undefined && startedRunManagers.length === prompts.length) + runManagers = startedRunManagers; + else { + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: prompts.length }; + runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, undefined, extra, undefined, undefined, handledOptions?.runName); + } + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + let output; + if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM2.prototype._streamResponseChunks) + try { + const stream2 = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); + let aggregated; + for await (const chunk of stream2) + if (aggregated === undefined) + aggregated = chunk; + else + aggregated = concat(aggregated, chunk); + if (aggregated === undefined) + throw new Error("Received empty response from chat model call."); + output = { + generations: [[aggregated]], + llmOutput: {} + }; + await runManagers?.[0].handleLLMEnd(output); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + try { + output = await this._generate(prompts, parsedOptions, runManagers?.[0]); + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + const flattenedOutputs = this._flattenLLMResult(output); + await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); } + const runIds = runManagers?.map((manager) => manager.runId) || undefined; + Object.defineProperty(output, RUN_KEY, { + value: runIds ? { runIds } : undefined, + configurable: true + }); + return output; } - }); -} -var DescriptionFunctionSchema, ALLOWED_DECISIONS, DecisionType, InterruptOnConfigSchema, contextSchema; -var init_hitl = __esm(() => { - init_middleware(); - init_messages(); - init_dist4(); - init_types3(); - init_v3(); - DescriptionFunctionSchema = exports_external2.function().args(exports_external2.custom(), exports_external2.custom(), exports_external2.custom()).returns(exports_external2.union([exports_external2.string(), exports_external2.promise(exports_external2.string())])); - ALLOWED_DECISIONS = [ - "approve", - "edit", - "reject" - ]; - DecisionType = exports_external2.enum(ALLOWED_DECISIONS); - InterruptOnConfigSchema = exports_external2.object({ - allowedDecisions: exports_external2.array(DecisionType), - description: exports_external2.union([exports_external2.string(), DescriptionFunctionSchema]).optional(), - argsSchema: exports_external2.record(exports_external2.any()).optional() - }); - contextSchema = exports_external2.object({ - interruptOn: exports_external2.record(exports_external2.union([exports_external2.boolean(), InterruptOnConfigSchema])).optional(), - descriptionPrefix: exports_external2.string().default("Tool execution requires approval") - }); + async _generateCached({ prompts, cache: cache2, llmStringKey, parsedOptions, handledOptions, runId }) { + const invocationParams = this.invocationParams(parsedOptions); + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { + verbose: this.verbose, + tracerInheritableMetadata: this._filterInvocationParamsForTracing(invocationParams) + }); + const extra = { + options: parsedOptions, + invocation_params: invocationParams, + batch_size: prompts.length + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, undefined, extra, undefined, undefined, handledOptions?.runName); + const missingPromptIndices = []; + const cachedResults = (await Promise.allSettled(prompts.map(async (prompt, index2) => { + const result = await cache2.lookup(prompt, llmStringKey); + if (result == null) + missingPromptIndices.push(index2); + return result; + }))).map((result, index2) => ({ + result, + runManager: runManagers?.[index2] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result2) => { + result2.generationInfo = { + ...result2.generationInfo, + tokenUsage: {} + }; + return result2; + }); + if (result.length) + await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, undefined, undefined, undefined, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { cached: true }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : undefined, + configurable: true + }); + return output; + } + async generate(prompts, options, callbacks) { + if (!Array.isArray(prompts)) + throw new Error("Argument 'prompts' is expected to be a string[]"); + let parsedOptions; + if (Array.isArray(options)) + parsedOptions = { stop: options }; + else + parsedOptions = options; + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) + return this._generateUncached(prompts, callOptions, runnableConfig); + const { cache: cache2 } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + prompts, + cache: cache2, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + runId: runnableConfig.runId + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== undefined ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : undefined); + await Promise.all(results.generations.map(async (generation, index2) => { + const promptIndex = missingPromptIndices[index2]; + generations[promptIndex] = generation; + return cache2.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { + generations, + llmOutput + }; + } + _identifyingParams() { + return {}; + } + _modelType() { + return "base_llm"; + } + }; + LLM = class extends BaseLLM { + async _generate(prompts, options, runManager) { + return { generations: await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { + ...options, + promptIndex + }, runManager).then((text) => [{ text }]))) }; + } + }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/summarization.js -function getProfileLimits(input) { - if ("profile" in input && typeof input.profile === "object" && input.profile && "maxInputTokens" in input.profile && (typeof input.profile.maxInputTokens === "number" || input.profile.maxInputTokens == null)) - return input.profile.maxInputTokens ?? undefined; - if ("model" in input && typeof input.model === "string") - return getModelContextSize(input.model); - if ("modelName" in input && typeof input.modelName === "string") - return getModelContextSize(input.modelName); -} -var DEFAULT_SUMMARY_PROMPT = ` -Context Extraction Assistant - - - -Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below. - - - -You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history. -This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal. - - - -The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history. -You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal. - - -The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved: - -With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history. -Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context. +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/language_models/profile.js +var profile_exports; +var init_profile = __esm(() => { + init_runtime2(); + profile_exports = /* @__PURE__ */ __exportAll({}); +}); - -Messages to summarize: -{messages} -`, tokenCounterSchema, contextSizeSchema, keepSchema, contextSchema2; -var init_summarization = __esm(() => { - init_universal(); - init_utils12(); - init_utils10(); - init_middleware(); - init_messages(); - init_runnables(); - init_dist4(); - init_types3(); - init_v3(); - init_uuid(); - init_base5(); - tokenCounterSchema = exports_external2.function().args(exports_external2.array(exports_external2.custom())).returns(exports_external2.union([exports_external2.number(), exports_external2.promise(exports_external2.number())])); - contextSizeSchema = exports_external2.object({ - fraction: exports_external2.number().gt(0, "Fraction must be greater than 0").max(1, "Fraction must be less than or equal to 1").optional(), - tokens: exports_external2.number().positive("Tokens must be greater than 0").optional(), - messages: exports_external2.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional() - }).refine((data) => { - return [ - data.fraction, - data.tokens, - data.messages - ].filter((v) => v !== undefined).length >= 1; - }, { message: "At least one of fraction, tokens, or messages must be provided" }); - keepSchema = exports_external2.object({ - fraction: exports_external2.number().min(0, "Messages must be non-negative").max(1, "Fraction must be less than or equal to 1").optional(), - tokens: exports_external2.number().min(0, "Tokens must be greater than or equal to 0").optional(), - messages: exports_external2.number().int("Messages must be an integer").min(0, "Messages must be non-negative").optional() - }).refine((data) => { - return [ - data.fraction, - data.tokens, - data.messages - ].filter((v) => v !== undefined).length === 1; - }, { message: "Exactly one of fraction, tokens, or messages must be provided" }); - contextSchema2 = exports_external2.object({ - model: exports_external2.custom(), - trigger: exports_external2.union([contextSizeSchema, exports_external2.array(contextSizeSchema)]).optional(), - keep: keepSchema.optional(), - tokenCounter: tokenCounterSchema.optional(), - summaryPrompt: exports_external2.string().default(DEFAULT_SUMMARY_PROMPT), - trimTokensToSummarize: exports_external2.number().optional(), - summaryPrefix: exports_external2.string().optional(), - maxTokensBeforeSummary: exports_external2.number().optional(), - messagesToKeep: exports_external2.number().optional() +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/memory.js +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) + throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + return promptInputKeys[0]; +} +var memory_exports, BaseMemory = class { +}, getValue = (values, key) => { + if (key !== undefined) + return values[key]; + const keys = Object.keys(values); + if (keys.length === 1) + return values[keys[0]]; +}, getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) + throw new Error(`input values have ${Object.keys(inputValues).length} keys, you must specify an input key or pass only 1 key as input`); + return value; +}, getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value && value !== "") + throw new Error(`output values have ${Object.keys(outputValues).length} keys, you must specify an output key or pass only 1 key as output`); + return value; +}; +var init_memory = __esm(() => { + init_runtime2(); + memory_exports = /* @__PURE__ */ __exportAll({ + BaseMemory: () => BaseMemory, + getInputValue: () => getInputValue, + getOutputValue: () => getOutputValue, + getPromptInputKey: () => getPromptInputKey }); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/dynamicSystemPrompt.js -var init_dynamicSystemPrompt = __esm(() => { - init_middleware(); - init_messages(); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js +var OutputFunctionsParser, JsonOutputFunctionsParser, JsonKeyOutputFunctionsParser; +var init_json_output_functions_parsers = __esm(() => { + init_json(); + init_duplex(); + init_base6(); + init_transform(); + init_json_patch(); + init_json2(); + OutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "OutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + argsOnly = true; + constructor(config3) { + super(); + this.argsOnly = config3?.argsOnly ?? this.argsOnly; + } + async parseResult(generations) { + if ("message" in generations[0]) { + const functionCall = generations[0].message.additional_kwargs.function_call; + if (!functionCall) + throw new Error(`No function_call in message ${JSON.stringify(generations)}`); + if (!functionCall.arguments) + throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); + if (this.argsOnly) + return functionCall.arguments; + return JSON.stringify(functionCall); + } else + throw new Error(`No message in generations ${JSON.stringify(generations)}`); + } + }; + JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser; + argsOnly = true; + constructor(config3) { + super(config3); + this.argsOnly = config3?.argsOnly ?? this.argsOnly; + this.outputParser = new OutputFunctionsParser(config3); + } + _diff(prev, next) { + if (!next) + return; + return compare(prev ?? {}, next); + } + async parsePartialResult(generations) { + const generation = generations[0]; + if (!generation.message) + return; + const { message } = generation; + const functionCall = message.additional_kwargs.function_call; + if (!functionCall) + return; + if (this.argsOnly) + return parsePartialJson(functionCall.arguments); + return { + ...functionCall, + arguments: parsePartialJson(functionCall.arguments) + }; + } + async parseResult(generations) { + const result = await this.outputParser.parseResult(generations); + if (!result) + throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); + return this.parse(result); + } + async parse(text) { + const parsedResult = JSON.parse(text); + if (this.argsOnly) + return parsedResult; + parsedResult.arguments = JSON.parse(parsedResult.arguments); + return parsedResult; + } + getFormatInstructions() { + return ""; + } + }; + JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "JsonKeyOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser = new JsonOutputFunctionsParser; + attrName; + get lc_aliases() { + return { attrName: "key_name" }; + } + constructor(fields) { + super(fields); + this.attrName = fields.attrName; + } + async parseResult(generations) { + return (await this.outputParser.parseResult(generations))[this.attrName]; + } + }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/llmToolSelector.js -var LLMToolSelectorOptionsSchema; -var init_llmToolSelector = __esm(() => { - init_universal(); - init_middleware(); - init_messages(); - init_v3(); - init_base5(); - LLMToolSelectorOptionsSchema = exports_external2.object({ - model: exports_external2.string().or(exports_external2.instanceof(BaseLanguageModel)).optional(), - systemPrompt: exports_external2.string().optional(), - maxTools: exports_external2.number().optional(), - alwaysInclude: exports_external2.array(exports_external2.string()).optional() +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js +var openai_functions_exports; +var init_openai_functions = __esm(() => { + init_runtime2(); + init_json_output_functions_parsers(); + openai_functions_exports = /* @__PURE__ */ __exportAll({ + JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, + JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, + OutputFunctionsParser: () => OutputFunctionsParser }); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/pii.js -var contextSchema3; -var init_pii = __esm(() => { - init_middleware(); - init_messages(); - init_v3(); - init_hash2(); - contextSchema3 = exports_external2.object({ - applyToInput: exports_external2.boolean().optional(), - applyToOutput: exports_external2.boolean().optional(), - applyToToolResults: exports_external2.boolean().optional() +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js +var openai_tools_exports; +var init_openai_tools = __esm(() => { + init_runtime2(); + init_json_output_tools_parsers(); + openai_tools_exports = /* @__PURE__ */ __exportAll({ + JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, + JsonOutputToolsParser: () => JsonOutputToolsParser, + convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, + makeInvalidToolCall: () => makeInvalidToolCall, + parseToolCall: () => parseToolCall }); }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/piiRedaction.js -var contextSchema4; -var init_piiRedaction = __esm(() => { - init_middleware(); - init_messages(); - init_v3(); - contextSchema4 = exports_external2.object({ rules: exports_external2.record(exports_external2.string(), exports_external2.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional() }); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/base.js +var BasePromptTemplate; +var init_base10 = __esm(() => { + init_base4(); + BasePromptTemplate = class extends Runnable { + lc_serializable = true; + lc_namespace = [ + "langchain_core", + "prompts", + this._getPromptType() + ]; + get lc_attributes() { + return { partialVariables: undefined }; + } + inputVariables; + outputParser; + partialVariables; + metadata; + tags; + constructor(input) { + super(input); + const { inputVariables } = input; + if (inputVariables.includes("stop")) + throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); + Object.assign(this, input); + } + async mergePartialAndUserVariables(userVariables) { + const partialVariables = this.partialVariables ?? {}; + const partialValues = {}; + for (const [key, value] of Object.entries(partialVariables)) + if (typeof value === "string") + partialValues[key] = value; + else + partialValues[key] = await value(); + return { + ...partialValues, + ...userVariables + }; + } + async invoke(input, options) { + const metadata = { + ...this.metadata, + ...options?.metadata + }; + const tags = [...this.tags ?? [], ...options?.tags ?? []]; + return this._callWithConfig((input2) => this.formatPromptValue(input2), input, { + ...options, + tags, + metadata, + runType: "prompt" + }); + } + }; }); -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/contextEditing.js -var DEFAULT_TOOL_PLACEHOLDER = "[cleared]", DEFAULT_TRIGGER_TOKENS = 1e5, DEFAULT_KEEP = 3, ClearToolUsesEdit = class { - #triggerConditions; - trigger; - keep; - clearToolInputs; - excludeTools; - placeholder; - model; - clearAtLeast; - constructor(config2 = {}) { - let trigger = config2.trigger; - if (config2.triggerTokens !== undefined) { - console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."); - if (trigger === undefined) - trigger = { tokens: config2.triggerTokens }; - } - let keep = config2.keep; - if (config2.keepMessages !== undefined) { - console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."); - if (keep === undefined) - keep = { messages: config2.keepMessages }; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/string.js +var BaseStringPromptTemplate; +var init_string3 = __esm(() => { + init_prompt_values(); + init_base10(); + BaseStringPromptTemplate = class extends BasePromptTemplate { + async formatPromptValue(values) { + return new StringPromptValue(await this.format(values)); } - if (trigger === undefined) - trigger = { tokens: DEFAULT_TRIGGER_TOKENS }; - if (keep === undefined) - keep = { messages: DEFAULT_KEEP }; - if (Array.isArray(trigger)) { - this.#triggerConditions = trigger.map((t) => contextSizeSchema.parse(t)); - this.trigger = this.#triggerConditions; + }; +}); + +// ../../node_modules/.pnpm/mustache@4.2.0/node_modules/mustache/mustache.mjs +function isFunction(object3) { + return typeof object3 === "function"; +} +function typeStr(obj) { + return isArray(obj) ? "array" : typeof obj; +} +function escapeRegExp(string7) { + return string7.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); +} +function hasProperty(obj, propName) { + return obj != null && typeof obj === "object" && propName in obj; +} +function primitiveHasOwnProperty(primitive, propName) { + return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); +} +function testRegExp(re, string7) { + return regExpTest.call(re, string7); +} +function isWhitespace(string7) { + return !testRegExp(nonSpaceRe, string7); +} +function escapeHtml(string7) { + return String(string7).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) { + return entityMap[s]; + }); +} +function parseTemplate(template, tags) { + if (!template) + return []; + var lineHasNonSpace = false; + var sections = []; + var tokens = []; + var spaces = []; + var hasTag = false; + var nonSpace = false; + var indentation = ""; + var tagIndex = 0; + function stripSpace() { + if (hasTag && !nonSpace) { + while (spaces.length) + delete tokens[spaces.pop()]; } else { - const validated = contextSizeSchema.parse(trigger); - this.#triggerConditions = [validated]; - this.trigger = validated; + spaces = []; } - const validatedKeep = keepSchema.parse(keep); - this.keep = validatedKeep; - if (config2.clearAtLeast !== undefined) - console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."); - this.clearAtLeast = config2.clearAtLeast ?? 0; - this.clearToolInputs = config2.clearToolInputs ?? false; - this.excludeTools = new Set(config2.excludeTools ?? []); - this.placeholder = config2.placeholder ?? DEFAULT_TOOL_PLACEHOLDER; + hasTag = false; + nonSpace = false; } - async apply(params) { - const { messages, model, countTokens } = params; - const tokens = await countTokens(messages); - const orphanedIndices = []; - for (let i = 0;i < messages.length; i++) { - const msg = messages[i]; - if (ToolMessage.isInstance(msg)) { - const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, i), msg.tool_call_id); - if (!aiMessage) - orphanedIndices.push(i); - else if (!aiMessage.tool_calls?.find((call3) => call3.id === msg.tool_call_id)) - orphanedIndices.push(i); - } - } - for (let i = orphanedIndices.length - 1;i >= 0; i--) - messages.splice(orphanedIndices[i], 1); - let currentTokens = tokens; - if (orphanedIndices.length > 0) - currentTokens = await countTokens(messages); - if (!this.#shouldEdit(messages, currentTokens, model)) - return; - const candidates = []; - for (let i = 0;i < messages.length; i++) { - const msg = messages[i]; - if (ToolMessage.isInstance(msg)) - candidates.push({ - idx: i, - msg - }); - } - if (candidates.length === 0) - return; - const keepCount = await this.#determineKeepCount(candidates, countTokens, model); - const candidatesToClear = keepCount >= candidates.length ? [] : keepCount > 0 ? candidates.slice(0, -keepCount) : candidates; - let clearedTokens = 0; - const initialCandidatesToClear = [...candidatesToClear]; - for (const { idx, msg: toolMessage } of initialCandidatesToClear) { - if (toolMessage.response_metadata?.context_editing?.cleared) - continue; - const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, idx), toolMessage.tool_call_id); - if (!aiMessage) - continue; - const toolCall = aiMessage.tool_calls?.find((call3) => call3.id === toolMessage.tool_call_id); - if (!toolCall) - continue; - const toolName = toolMessage.name || toolCall.name; - if (this.excludeTools.has(toolName)) - continue; - messages[idx] = new ToolMessage({ - tool_call_id: toolMessage.tool_call_id, - content: this.placeholder, - name: toolMessage.name, - artifact: undefined, - response_metadata: { - ...toolMessage.response_metadata, - context_editing: { - cleared: true, - strategy: "clear_tool_uses" - } + var openingTagRe, closingTagRe, closingCurlyRe; + function compileTags(tagsToCompile) { + if (typeof tagsToCompile === "string") + tagsToCompile = tagsToCompile.split(spaceRe, 2); + if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) + throw new Error("Invalid tags: " + tagsToCompile); + openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); + closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); + closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); + } + compileTags(tags || mustache.tags); + var scanner = new Scanner(template); + var start, type, value, chr, token, openSection; + while (!scanner.eos()) { + start = scanner.pos; + value = scanner.scanUntil(openingTagRe); + if (value) { + for (var i = 0, valueLength = value.length;i < valueLength; ++i) { + chr = value.charAt(i); + if (isWhitespace(chr)) { + spaces.push(tokens.length); + indentation += chr; + } else { + nonSpace = true; + lineHasNonSpace = true; + indentation += " "; } - }); - if (this.clearToolInputs) { - const aiMsgIdx = messages.indexOf(aiMessage); - if (aiMsgIdx >= 0) - messages[aiMsgIdx] = this.#buildClearedToolInputMessage(aiMessage, toolMessage.tool_call_id); - } - const newTokenCount = await countTokens(messages); - clearedTokens = Math.max(0, currentTokens - newTokenCount); - } - if (this.clearAtLeast > 0 && clearedTokens < this.clearAtLeast) { - const remainingCandidates = keepCount > 0 && keepCount < candidates.length ? candidates.slice(-keepCount) : []; - for (let i = remainingCandidates.length - 1;i >= 0; i--) { - if (clearedTokens >= this.clearAtLeast) - break; - const { idx, msg: toolMessage } = remainingCandidates[i]; - if (toolMessage.response_metadata?.context_editing?.cleared) - continue; - const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, idx), toolMessage.tool_call_id); - if (!aiMessage) - continue; - const toolCall = aiMessage.tool_calls?.find((call3) => call3.id === toolMessage.tool_call_id); - if (!toolCall) - continue; - const toolName = toolMessage.name || toolCall.name; - if (this.excludeTools.has(toolName)) - continue; - messages[idx] = new ToolMessage({ - tool_call_id: toolMessage.tool_call_id, - content: this.placeholder, - name: toolMessage.name, - artifact: undefined, - response_metadata: { - ...toolMessage.response_metadata, - context_editing: { - cleared: true, - strategy: "clear_tool_uses" - } - } - }); - if (this.clearToolInputs) { - const aiMsgIdx = messages.indexOf(aiMessage); - if (aiMsgIdx >= 0) - messages[aiMsgIdx] = this.#buildClearedToolInputMessage(aiMessage, toolMessage.tool_call_id); + tokens.push(["text", chr, start, start + 1]); + start += 1; + if (chr === ` +`) { + stripSpace(); + indentation = ""; + tagIndex = 0; + lineHasNonSpace = false; } - const newTokenCount = await countTokens(messages); - clearedTokens = Math.max(0, currentTokens - newTokenCount); } } - } - #shouldEdit(messages, totalTokens, model) { - for (const trigger of this.#triggerConditions) { - let conditionMet = true; - let hasAnyProperty = false; - if (trigger.messages !== undefined) { - hasAnyProperty = true; - if (messages.length < trigger.messages) - conditionMet = false; - } - if (trigger.tokens !== undefined) { - hasAnyProperty = true; - if (totalTokens < trigger.tokens) - conditionMet = false; - } - if (trigger.fraction !== undefined) { - hasAnyProperty = true; - if (!model) - continue; - const maxInputTokens = getProfileLimits(model); - if (typeof maxInputTokens === "number") { - const threshold = Math.floor(maxInputTokens * trigger.fraction); - if (threshold <= 0) - continue; - if (totalTokens < threshold) - conditionMet = false; - } else - continue; - } - if (hasAnyProperty && conditionMet) - return true; + if (!scanner.scan(openingTagRe)) + break; + hasTag = true; + type = scanner.scan(tagRe) || "name"; + scanner.scan(whiteRe); + if (type === "=") { + value = scanner.scanUntil(equalsRe); + scanner.scan(equalsRe); + scanner.scanUntil(closingTagRe); + } else if (type === "{") { + value = scanner.scanUntil(closingCurlyRe); + scanner.scan(curlyRe); + scanner.scanUntil(closingTagRe); + type = "&"; + } else { + value = scanner.scanUntil(closingTagRe); } - return false; - } - async#determineKeepCount(candidates, countTokens, model) { - if ("messages" in this.keep && this.keep.messages !== undefined) - return this.keep.messages; - if ("tokens" in this.keep && this.keep.tokens !== undefined) { - const targetTokens = this.keep.tokens; - let tokenCount = 0; - let keepCount = 0; - for (let i = candidates.length - 1;i >= 0; i--) { - const candidate = candidates[i]; - const msgTokens = await countTokens([candidate.msg]); - if (tokenCount + msgTokens <= targetTokens) { - tokenCount += msgTokens; - keepCount++; - } else - break; - } - return keepCount; + if (!scanner.scan(closingTagRe)) + throw new Error("Unclosed tag at " + scanner.pos); + if (type == ">") { + token = [type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace]; + } else { + token = [type, value, start, scanner.pos]; } - if ("fraction" in this.keep && this.keep.fraction !== undefined) { - if (!model) - return DEFAULT_KEEP; - const maxInputTokens = getProfileLimits(model); - if (typeof maxInputTokens === "number") { - const targetTokens = Math.floor(maxInputTokens * this.keep.fraction); - if (targetTokens <= 0) - return DEFAULT_KEEP; - let tokenCount = 0; - let keepCount = 0; - for (let i = candidates.length - 1;i >= 0; i--) { - const candidate = candidates[i]; - const msgTokens = await countTokens([candidate.msg]); - if (tokenCount + msgTokens <= targetTokens) { - tokenCount += msgTokens; - keepCount++; - } else - break; - } - return keepCount; - } + tagIndex++; + tokens.push(token); + if (type === "#" || type === "^") { + sections.push(token); + } else if (type === "/") { + openSection = sections.pop(); + if (!openSection) + throw new Error('Unopened section "' + value + '" at ' + start); + if (openSection[1] !== value) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); + } else if (type === "name" || type === "{" || type === "&") { + nonSpace = true; + } else if (type === "=") { + compileTags(value); } - return DEFAULT_KEEP; } - #findAIMessageForToolCall(previousMessages, toolCallId) { - for (let i = previousMessages.length - 1;i >= 0; i--) { - const msg = previousMessages[i]; - if (AIMessage.isInstance(msg)) { - if (msg.tool_calls?.some((call3) => call3.id === toolCallId)) - return msg; + stripSpace(); + openSection = sections.pop(); + if (openSection) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); + return nestTokens(squashTokens(tokens)); +} +function squashTokens(tokens) { + var squashedTokens = []; + var token, lastToken; + for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { + token = tokens[i]; + if (token) { + if (token[0] === "text" && lastToken && lastToken[0] === "text") { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + squashedTokens.push(token); + lastToken = token; } } - return null; } - #buildClearedToolInputMessage(message, toolCallId) { - const updatedToolCalls = message.tool_calls?.map((toolCall) => { - if (toolCall.id === toolCallId) - return { - ...toolCall, - args: {} - }; - return toolCall; - }); - const metadata = { ...message.response_metadata }; - const contextEntry = { ...metadata.context_editing }; - const clearedIds = new Set(contextEntry.cleared_tool_inputs); - clearedIds.add(toolCallId); - contextEntry.cleared_tool_inputs = Array.from(clearedIds).sort(); - metadata.context_editing = contextEntry; - return new AIMessage({ - content: message.content, - tool_calls: updatedToolCalls, - response_metadata: metadata, - id: message.id, - name: message.name, - additional_kwargs: message.additional_kwargs - }); + return squashedTokens; +} +function nestTokens(tokens) { + var nestedTokens = []; + var collector = nestedTokens; + var sections = []; + var token, section; + for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { + token = tokens[i]; + switch (token[0]) { + case "#": + case "^": + collector.push(token); + sections.push(token); + collector = token[4] = []; + break; + case "/": + section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; + break; + default: + collector.push(token); + } } -}; -var init_contextEditing = __esm(() => { - init_utils10(); - init_middleware(); - init_summarization(); - init_messages(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/toolCallLimit.js -var VALID_EXIT_BEHAVIORS, DEFAULT_EXIT_BEHAVIOR = "continue", exitBehaviorSchema, stateSchema; -var init_toolCallLimit = __esm(() => { - init_middleware(); - init_messages(); - init_v3(); - VALID_EXIT_BEHAVIORS = [ - "continue", - "error", - "end" - ]; - exitBehaviorSchema = exports_external2.enum(VALID_EXIT_BEHAVIORS).default(DEFAULT_EXIT_BEHAVIOR); - exports_external2.object({ - toolName: exports_external2.string().optional(), - threadLimit: exports_external2.number().optional(), - runLimit: exports_external2.number().optional(), - exitBehavior: exitBehaviorSchema - }); - stateSchema = exports_external2.object({ - threadToolCallCount: exports_external2.record(exports_external2.string(), exports_external2.number()).default({}), - runToolCallCount: exports_external2.record(exports_external2.string(), exports_external2.number()).default({}) - }); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/todoListMiddleware.js -function todoListMiddleware(options) { - const writeTodos = tool(({ todos }, config2) => { - return new Command({ update: { - todos, - messages: [new ToolMessage({ - content: `Updated todo list to ${JSON.stringify(todos)}`, - tool_call_id: config2.toolCall?.id - })] - } }); - }, { - name: "write_todos", - description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION, - schema: exports_external2.object({ todos: exports_external2.array(TodoSchema).describe("List of todo items to update") }) - }); - return createMiddleware({ - name: "todoListMiddleware", - stateSchema: stateSchema2, - tools: [writeTodos], - wrapModelCall: (request, handler) => handler({ - ...request, - systemMessage: request.systemMessage.concat(` - -${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`) - }), - afterModel: (state) => { - const messages = state.messages; - if (!messages || messages.length === 0) - return; - const lastAiMsg = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); - if (!lastAiMsg || !lastAiMsg.tool_calls || lastAiMsg.tool_calls.length === 0) - return; - const writeTodosCalls = lastAiMsg.tool_calls.filter((tc) => tc.name === writeTodos.name); - if (writeTodosCalls.length > 1) - return { messages: writeTodosCalls.map((tc) => new ToolMessage({ - content: "Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.", - tool_call_id: tc.id, - status: "error" - })) }; - } - }); + return nestedTokens; } -var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. -It also helps the user understand the progress of the task and overall progress of their requests. -Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly. - -## When to Use This Tool -Use this tool in these scenarios: - -1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions -2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations -3. User explicitly requests todo list - When the user directly asks you to use the todo list -4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated) -5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful. - -## How to Use This Tool -1. When you start working on a task - Mark it as in_progress BEFORE beginning work. -2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation. -3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks. -4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress. - -## When NOT to Use This Tool -It is important to skip using this tool when: -1. There is only a single, straightforward task -2. The task is trivial and tracking it provides no benefit -3. The task can be completed in less than 3 trivial steps -4. The task is purely conversational or informational - -## Examples of When to Use the Todo List - - -User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done! -Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation. -*Creates todo list with the following items:* -1. Create dark mode toggle component in Settings page -2. Add dark mode state management (context/store) -3. Implement CSS-in-JS styles for dark theme -4. Update existing components to support theme switching -5. Run tests and build process, addressing any failures or errors that occur -*Begins working on the first task* - - -The assistant used the todo list because: -1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes -2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task -3. Both of the user's requests are complex and require multiple steps to complete. - - - - -User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases. -Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components. -*Creates todo list with the following items:* -1. Define target audience and key messaging -2. Create social media content calendar and posting schedule -3. Design email marketing sequence and automation flows -4. Draft press release and identify media contacts -5. Set up tracking and analytics for campaign performance -6. Create visual assets and brand materials -7. Coordinate launch timeline and deliverables -*Begins working on the first task* - - -The assistant used the todo list because: -1. Marketing campaign planning involves multiple distinct channels and activities -2. Each component requires careful coordination and planning -3. The systematic approach ensures all aspects of the launch are covered - - - - -User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project -Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'. -*Uses search tools to locate all instances of getCwd in the codebase* -Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes. -*Creates todo list with specific items for each file that needs updating* - - -The assistant used the todo list because: -1. The assistant searched to understand the scope of the task -2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3) -3. The todo list helps ensure every instance is tracked and updated systematically -4. This approach prevents missing any occurrences and maintains consistency. - - - - -User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow. -Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization. -*Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines* -Let's start with decluttering your desk space to create a clean foundation for the other organizational systems. - - -The assistant used the todo list because: -1. The user provided multiple distinct organizational tasks -2. Each area requires different approaches and careful planning -3. Home organization benefits from systematic, step-by-step completion -4. Progress tracking ensures all areas are addressed thoroughly - - - -## Examples of When NOT to Use the Todo List - - -User: How do I print 'Hello World' in Python? -Assistant: In Python, you can print "Hello World" with this simple code: - -\`\`\`python -print("Hello World") -\`\`\` - -This will output the text "Hello World" to the console when executed. - - -The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request. - - - - -User: What's the best way to water houseplants? -Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines: - -- Check soil moisture by inserting your finger about 1-2 inches into the soil -- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom -- Use room temperature water and water in the morning when possible -- Avoid overwatering, which is more harmful than underwatering for most plants - -Different plants have different needs, so it's important to research your specific varieties for optimal care. - - -The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities. - - - - -User: Can you add a comment to the calculateTotal function to explain what it does? -Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does. -* Uses the Edit tool to add a comment to the calculateTotal function * - - -The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization. - - - - -User: What time is it in Tokyo right now? -Assistant: I'll check the current time in Tokyo for you. - -*Searches for current time in Tokyo* - -The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9. - - -The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request. - - - - -User: I need to write a function that checks if a number is prime and then test it out. -Assistant: I'll help you write a function that checks if a number is prime and then test it out. -*Writes function that checks if a number is prime* -*Tests the function* - - -Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens. - - - - -User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. -Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. -*Orders a pizza from Dominos* -*Orders a burger from McDonald's* -*Orders a salad from Subway* - - -Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls. -Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact. - - - - -## Task States and Management - -1. **Task States**: Use these states to track progress: - - pending: Task not yet started - - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel) - - completed: Task finished successfully - -2. **Task Management**: - - Update task status in real-time as you work - - Mark tasks complete IMMEDIATELY after finishing (don't batch completions) - - Complete current tasks before starting new ones - - Remove tasks that are no longer relevant from the list entirely - - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!. - - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something. - -3. **Task Completion Requirements**: - - ONLY mark a task as completed when you have FULLY accomplished it - - If you encounter errors, blockers, or cannot finish, keep the task as in_progress - - When blocked, create a new task describing what needs to be resolved - - Never mark a task as completed if: - - There are unresolved issues or errors - - Work is partial or incomplete - - You encountered blockers that prevent completion - - You couldn't find necessary resources or dependencies - - Quality standards haven't been met - -4. **Task Breakdown**: - - Create specific, actionable items - - Break complex tasks into smaller, manageable steps - - Use clear, descriptive task names - -Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully -Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \`write_todos\` - -You have access to the \`write_todos\` tool to help you manage and plan complex objectives. -Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress. -This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps. - -It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed. -For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool. -Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests. - -## Important To-Do List Usage Notes to Remember -- The \`write_todos\` tool should never be called multiple times in parallel. -- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`, TodoStatus, TodoSchema, stateSchema2; -var init_todoListMiddleware = __esm(() => { - init_middleware(); - init_agents2(); - init_messages(); - init_tools2(); - init_dist4(); - init_v3(); - TodoStatus = exports_external2.enum([ - "pending", - "in_progress", - "completed" - ]).describe("Status of the todo"); - TodoSchema = exports_external2.object({ - content: exports_external2.string().describe("Content of the todo item"), - status: TodoStatus - }); - stateSchema2 = exports_external2.object({ todos: exports_external2.array(TodoSchema).default([]) }); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/modelCallLimit.js -var contextSchema5, stateSchema3; -var init_modelCallLimit = __esm(() => { - init_middleware(); - init_messages(); - init_v3(); - contextSchema5 = exports_external2.object({ - threadLimit: exports_external2.number().optional(), - runLimit: exports_external2.number().optional(), - exitBehavior: exports_external2.enum(["error", "end"]).optional() - }); - stateSchema3 = exports_external2.object({ - threadModelCallCount: exports_external2.number().default(0), - runModelCallCount: exports_external2.number().default(0) - }); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/modelFallback.js -var init_modelFallback = __esm(() => { - init_universal(); - init_middleware(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/constants.js -var RetrySchema; -var init_constants4 = __esm(() => { - init_v3(); - RetrySchema = exports_external2.object({ - maxRetries: exports_external2.number().min(0).default(2), - retryOn: exports_external2.union([exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.boolean()), exports_external2.array(exports_external2.custom())]).default(() => () => true), - backoffFactor: exports_external2.number().min(0).default(2), - initialDelayMs: exports_external2.number().min(0).default(1000), - maxDelayMs: exports_external2.number().min(0).default(60000), - jitter: exports_external2.boolean().default(true) - }); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/error.js -var init_error2 = () => {}; - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/modelRetry.js -var ModelRetryMiddlewareOptionsSchema; -var init_modelRetry = __esm(() => { - init_utils10(); - init_middleware(); - init_constants4(); - init_error2(); - init_messages(); - init_v3(); - ModelRetryMiddlewareOptionsSchema = exports_external2.object({ onFailure: exports_external2.union([ - exports_external2.literal("error"), - exports_external2.literal("continue"), - exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.string()) - ]).default("continue") }).merge(RetrySchema); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/toolRetry.js -var ToolRetryMiddlewareOptionsSchema; -var init_toolRetry = __esm(() => { - init_utils10(); - init_middleware(); - init_constants4(); - init_error2(); - init_messages(); - init_v3(); - ToolRetryMiddlewareOptionsSchema = exports_external2.object({ - tools: exports_external2.array(exports_external2.union([ - exports_external2.custom(), - exports_external2.custom(), - exports_external2.string() - ])).optional(), - onFailure: exports_external2.union([ - exports_external2.literal("error"), - exports_external2.literal("continue"), - exports_external2.literal("raise"), - exports_external2.literal("return_message"), - exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.string()) - ]).default("continue") - }).merge(RetrySchema); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/toolEmulator.js -var init_toolEmulator = __esm(() => { - init_universal(); - init_middleware(); - init_messages(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/provider/openai/moderation.js -var init_moderation = __esm(() => { - init_universal(); - init_middleware(); - init_messages(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/provider/anthropic/promptCaching.js -function anthropicPromptCachingMiddleware(middlewareOptions) { - return createMiddleware({ - name: "PromptCachingMiddleware", - contextSchema: contextSchema6, - wrapModelCall: (request, handler) => { - const enableCaching = request.runtime.context.enableCaching ?? middlewareOptions?.enableCaching ?? DEFAULT_ENABLE_CACHING; - const ttl = request.runtime.context.ttl ?? middlewareOptions?.ttl ?? DEFAULT_TTL; - const minMessagesToCache = request.runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache ?? DEFAULT_MIN_MESSAGES_TO_CACHE; - const unsupportedModelBehavior = request.runtime.context.unsupportedModelBehavior ?? middlewareOptions?.unsupportedModelBehavior ?? DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR; - if (!enableCaching || !request.model) - return handler(request); - if (!(request.model.getName() === "ChatAnthropic" || request.model.getName() === "ConfigurableModel" && request.model._defaultConfig?.modelProvider === "anthropic")) { - const modelName = request.model.getName(); - const baseMessage = `Unsupported model '${request.model.getName() === "ConfigurableModel" ? `${modelName} (${request.model._defaultConfig?.modelProvider})` : modelName}'. Prompt caching requires an Anthropic model`; - if (unsupportedModelBehavior === "raise") - throw new PromptCachingMiddlewareError(`${baseMessage} (e.g., 'anthropic:claude-4-0-sonnet').`); - else if (unsupportedModelBehavior === "warn") - console.warn(`PromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic model for caching benefits.`); - return handler(request); - } - if (request.state.messages.length + (request.systemPrompt ? 1 : 0) < minMessagesToCache) - return handler(request); - return handler({ - ...request, - modelSettings: { - ...request.modelSettings, - cache_control: { - type: "ephemeral", - ttl - } - } - }); - } - }); +function Scanner(string7) { + this.string = string7; + this.tail = string7; + this.pos = 0; } -var DEFAULT_ENABLE_CACHING = true, DEFAULT_TTL = "5m", DEFAULT_MIN_MESSAGES_TO_CACHE = 3, DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR = "warn", contextSchema6, PromptCachingMiddlewareError; -var init_promptCaching = __esm(() => { - init_middleware(); - init_v3(); - contextSchema6 = exports_external2.object({ - enableCaching: exports_external2.boolean().optional(), - ttl: exports_external2.enum(["5m", "1h"]).optional(), - minMessagesToCache: exports_external2.number().optional(), - unsupportedModelBehavior: exports_external2.enum([ - "ignore", - "warn", - "raise" - ]).optional() - }); - PromptCachingMiddlewareError = class extends Error { - constructor(message) { - super(message); - this.name = "PromptCachingMiddlewareError"; - } - }; -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/agents/middleware/index.js -var init_middleware3 = __esm(() => { - init_utils10(); - init_hitl(); - init_summarization(); - init_dynamicSystemPrompt(); - init_llmToolSelector(); - init_pii(); - init_piiRedaction(); - init_contextEditing(); - init_toolCallLimit(); - init_todoListMiddleware(); - init_modelCallLimit(); - init_modelFallback(); - init_modelRetry(); - init_toolRetry(); - init_toolEmulator(); - init_moderation(); - init_promptCaching(); -}); - -// ../../node_modules/.pnpm/langchain@1.4.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_tnem4icg7q4p4rajp2bvb2e73y/node_modules/langchain/dist/index.js -var init_dist5 = __esm(() => { - init_runtime(); - init_universal(); - init_headless(); - init_errors6(); - init_responses(); - init_utils10(); - init_stream6(); - init_types10(); - init_middleware(); - init_utils11(); - init_agents2(); - init_hitl(); - init_summarization(); - init_dynamicSystemPrompt(); - init_llmToolSelector(); - init_pii(); - init_piiRedaction(); - init_contextEditing(); - init_toolCallLimit(); - init_todoListMiddleware(); - init_modelCallLimit(); - init_modelFallback(); - init_modelRetry(); - init_toolRetry(); - init_toolEmulator(); - init_moderation(); - init_promptCaching(); - init_middleware3(); - init_messages(); - init_tools2(); - init_context2(); - init_stores(); - init_documents(); - init_testing(); -}); - -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js -var require_utils = __commonJS((exports) => { - exports.isInteger = (num) => { - if (typeof num === "number") { - return Number.isInteger(num); - } - if (typeof num === "string" && num.trim() !== "") { - return Number.isInteger(Number(num)); +function Context2(view, parentContext) { + this.view = view; + this.cache = { ".": this.view }; + this.parent = parentContext; +} +function Writer() { + this.templateCache = { + _cache: {}, + set: function set3(key, value) { + this._cache[key] = value; + }, + get: function get(key) { + return this._cache[key]; + }, + clear: function clear() { + this._cache = {}; } - return false; }; - exports.find = (node, type) => node.nodes.find((node2) => node2.type === type); - exports.exceedsLimit = (min, max, step = 1, limit) => { - if (limit === false) - return false; - if (!exports.isInteger(min) || !exports.isInteger(max)) - return false; - return (Number(max) - Number(min)) / Number(step) >= limit; +} +var objectToString3, isArray, regExpTest, nonSpaceRe, entityMap, whiteRe, spaceRe, equalsRe, curlyRe, tagRe, mustache, defaultWriter, mustache_default; +var init_mustache = __esm(() => { + /*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + objectToString3 = Object.prototype.toString; + isArray = Array.isArray || function isArrayPolyfill(object3) { + return objectToString3.call(object3) === "[object Array]"; }; - exports.escapeNode = (block, n3 = 0, type) => { - const node = block.nodes[n3]; - if (!node) - return; - if (type && node.type === type || node.type === "open" || node.type === "close") { - if (node.escaped !== true) { - node.value = "\\" + node.value; - node.escaped = true; - } - } + regExpTest = RegExp.prototype.test; + nonSpaceRe = /\S/; + entityMap = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + "/": "/", + "`": "`", + "=": "=" }; - exports.encloseBrace = (node) => { - if (node.type !== "brace") - return false; - if (node.commas >> 0 + node.ranges >> 0 === 0) { - node.invalid = true; - return true; - } - return false; + whiteRe = /\s*/; + spaceRe = /\s+/; + equalsRe = /\s*=/; + curlyRe = /\s*\}/; + tagRe = /#|\^|\/|>|\{|&|=|!/; + Scanner.prototype.eos = function eos() { + return this.tail === ""; }; - exports.isInvalidBrace = (block) => { - if (block.type !== "brace") - return false; - if (block.invalid === true || block.dollar) - return true; - if (block.commas >> 0 + block.ranges >> 0 === 0) { - block.invalid = true; - return true; - } - if (block.open !== true || block.close !== true) { - block.invalid = true; - return true; - } - return false; + Scanner.prototype.scan = function scan(re) { + var match2 = this.tail.match(re); + if (!match2 || match2.index !== 0) + return ""; + var string7 = match2[0]; + this.tail = this.tail.substring(string7.length); + this.pos += string7.length; + return string7; }; - exports.isOpenOrClose = (node) => { - if (node.type === "open" || node.type === "close") { - return true; + Scanner.prototype.scanUntil = function scanUntil(re) { + var index2 = this.tail.search(re), match2; + switch (index2) { + case -1: + match2 = this.tail; + this.tail = ""; + break; + case 0: + match2 = ""; + break; + default: + match2 = this.tail.substring(0, index2); + this.tail = this.tail.substring(index2); } - return node.open === true || node.close === true; + this.pos += match2.length; + return match2; }; - exports.reduce = (nodes) => nodes.reduce((acc, node) => { - if (node.type === "text") - acc.push(node.value); - if (node.type === "range") - node.type = "text"; - return acc; - }, []); - exports.flatten = (...args) => { - const result = []; - const flat = (arr3) => { - for (let i = 0;i < arr3.length; i++) { - const ele = arr3[i]; - if (Array.isArray(ele)) { - flat(ele); - continue; - } - if (ele !== undefined) { - result.push(ele); - } - } - return result; - }; - flat(args); - return result; + Context2.prototype.push = function push(view) { + return new Context2(view, this); }; -}); - -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js -var require_stringify2 = __commonJS((exports, module) => { - var utils = require_utils(); - module.exports = (ast, options = {}) => { - const stringify4 = (node, parent = {}) => { - const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); - const invalidNode = node.invalid === true && options.escapeInvalid === true; - let output = ""; - if (node.value) { - if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { - return "\\" + node.value; + Context2.prototype.lookup = function lookup(name) { + var cache2 = this.cache; + var value; + if (cache2.hasOwnProperty(name)) { + value = cache2[name]; + } else { + var context = this, intermediateValue, names, index2, lookupHit = false; + while (context) { + if (name.indexOf(".") > 0) { + intermediateValue = context.view; + names = name.split("."); + index2 = 0; + while (intermediateValue != null && index2 < names.length) { + if (index2 === names.length - 1) + lookupHit = hasProperty(intermediateValue, names[index2]) || primitiveHasOwnProperty(intermediateValue, names[index2]); + intermediateValue = intermediateValue[names[index2++]]; + } + } else { + intermediateValue = context.view[name]; + lookupHit = hasProperty(context.view, name); } - return node.value; - } - if (node.value) { - return node.value; - } - if (node.nodes) { - for (const child of node.nodes) { - output += stringify4(child); + if (lookupHit) { + value = intermediateValue; + break; } + context = context.parent; } - return output; - }; - return stringify4(ast); - }; -}); - -// ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js -var require_is_number = __commonJS((exports, module) => { - /*! - * is-number - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Released under the MIT License. - */ - module.exports = function(num) { - if (typeof num === "number") { - return num - num === 0; - } - if (typeof num === "string" && num.trim() !== "") { - return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + cache2[name] = value; } - return false; + if (isFunction(value)) + value = value.call(this.view); + return value; }; -}); - -// ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js -var require_to_regex_range = __commonJS((exports, module) => { - /*! - * to-regex-range - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Released under the MIT License. - */ - var isNumber = require_is_number(); - var toRegexRange = (min, max, options) => { - if (isNumber(min) === false) { - throw new TypeError("toRegexRange: expected the first argument to be a number"); - } - if (max === undefined || min === max) { - return String(min); - } - if (isNumber(max) === false) { - throw new TypeError("toRegexRange: expected the second argument to be a number."); - } - let opts = { relaxZeros: true, ...options }; - if (typeof opts.strictZeros === "boolean") { - opts.relaxZeros = opts.strictZeros === false; - } - let relax = String(opts.relaxZeros); - let shorthand = String(opts.shorthand); - let capture = String(opts.capture); - let wrap3 = String(opts.wrap); - let cacheKey2 = min + ":" + max + "=" + relax + shorthand + capture + wrap3; - if (toRegexRange.cache.hasOwnProperty(cacheKey2)) { - return toRegexRange.cache[cacheKey2].result; - } - let a = Math.min(min, max); - let b = Math.max(min, max); - if (Math.abs(a - b) === 1) { - let result = min + "|" + max; - if (opts.capture) { - return `(${result})`; - } - if (opts.wrap === false) { - return result; - } - return `(?:${result})`; - } - let isPadded = hasPadding(min) || hasPadding(max); - let state = { min, max, a, b }; - let positives = []; - let negatives = []; - if (isPadded) { - state.isPadded = isPadded; - state.maxLen = String(state.max).length; - } - if (a < 0) { - let newMin = b < 0 ? Math.abs(b) : 1; - negatives = splitToPatterns(newMin, Math.abs(a), state, opts); - a = state.a = 0; - } - if (b >= 0) { - positives = splitToPatterns(a, b, state, opts); - } - state.negatives = negatives; - state.positives = positives; - state.result = collatePatterns(negatives, positives, opts); - if (opts.capture === true) { - state.result = `(${state.result})`; - } else if (opts.wrap !== false && positives.length + negatives.length > 1) { - state.result = `(?:${state.result})`; + Writer.prototype.clearCache = function clearCache() { + if (typeof this.templateCache !== "undefined") { + this.templateCache.clear(); } - toRegexRange.cache[cacheKey2] = state; - return state.result; }; - function collatePatterns(neg, pos, options) { - let onlyNegative = filterPatterns(neg, pos, "-", false, options) || []; - let onlyPositive = filterPatterns(pos, neg, "", false, options) || []; - let intersected = filterPatterns(neg, pos, "-?", true, options) || []; - let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); - return subpatterns.join("|"); - } - function splitToRanges(min, max) { - let nines = 1; - let zeros = 1; - let stop = countNines(min, nines); - let stops = new Set([max]); - while (min <= stop && stop <= max) { - stops.add(stop); - nines += 1; - stop = countNines(min, nines); + Writer.prototype.parse = function parse14(template, tags) { + var cache2 = this.templateCache; + var cacheKey2 = template + ":" + (tags || mustache.tags).join(":"); + var isCacheEnabled = typeof cache2 !== "undefined"; + var tokens = isCacheEnabled ? cache2.get(cacheKey2) : undefined; + if (tokens == undefined) { + tokens = parseTemplate(template, tags); + isCacheEnabled && cache2.set(cacheKey2, tokens); } - stop = countZeros(max + 1, zeros) - 1; - while (min < stop && stop <= max) { - stops.add(stop); - zeros += 1; - stop = countZeros(max + 1, zeros) - 1; + return tokens; + }; + Writer.prototype.render = function render(template, view, partials, config3) { + var tags = this.getConfigTags(config3); + var tokens = this.parse(template, tags); + var context = view instanceof Context2 ? view : new Context2(view, undefined); + return this.renderTokens(tokens, context, partials, template, config3); + }; + Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config3) { + var buffer = ""; + var token, symbol3, value; + for (var i = 0, numTokens = tokens.length;i < numTokens; ++i) { + value = undefined; + token = tokens[i]; + symbol3 = token[0]; + if (symbol3 === "#") + value = this.renderSection(token, context, partials, originalTemplate, config3); + else if (symbol3 === "^") + value = this.renderInverted(token, context, partials, originalTemplate, config3); + else if (symbol3 === ">") + value = this.renderPartial(token, context, partials, config3); + else if (symbol3 === "&") + value = this.unescapedValue(token, context); + else if (symbol3 === "name") + value = this.escapedValue(token, context, config3); + else if (symbol3 === "text") + value = this.rawValue(token); + if (value !== undefined) + buffer += value; } - stops = [...stops]; - stops.sort(compare2); - return stops; - } - function rangeToPattern(start, stop, options) { - if (start === stop) { - return { pattern: start, count: [], digits: 0 }; + return buffer; + }; + Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config3) { + var self2 = this; + var buffer = ""; + var value = context.lookup(token[1]); + function subRender(template) { + return self2.render(template, context, partials, config3); } - let zipped = zip(start, stop); - let digits = zipped.length; - let pattern = ""; - let count = 0; - for (let i = 0;i < digits; i++) { - let [startDigit, stopDigit] = zipped[i]; - if (startDigit === stopDigit) { - pattern += startDigit; - } else if (startDigit !== "0" || stopDigit !== "9") { - pattern += toCharacterClass(startDigit, stopDigit, options); - } else { - count++; + if (!value) + return; + if (isArray(value)) { + for (var j = 0, valueLength = value.length;j < valueLength; ++j) { + buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config3); } + } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") { + buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config3); + } else if (isFunction(value)) { + if (typeof originalTemplate !== "string") + throw new Error("Cannot use higher-order sections without the original template"); + value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); + if (value != null) + buffer += value; + } else { + buffer += this.renderTokens(token[4], context, partials, originalTemplate, config3); } - if (count) { - pattern += options.shorthand === true ? "\\d" : "[0-9]"; - } - return { pattern, count: [count], digits }; - } - function splitToPatterns(min, max, tok, options) { - let ranges = splitToRanges(min, max); - let tokens = []; - let start = min; - let prev; - for (let i = 0;i < ranges.length; i++) { - let max2 = ranges[i]; - let obj = rangeToPattern(String(start), String(max2), options); - let zeros = ""; - if (!tok.isPadded && prev && prev.pattern === obj.pattern) { - if (prev.count.length > 1) { - prev.count.pop(); - } - prev.count.push(obj.count[0]); - prev.string = prev.pattern + toQuantifier(prev.count); - start = max2 + 1; - continue; - } - if (tok.isPadded) { - zeros = padZeros(max2, tok, options); + return buffer; + }; + Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config3) { + var value = context.lookup(token[1]); + if (!value || isArray(value) && value.length === 0) + return this.renderTokens(token[4], context, partials, originalTemplate, config3); + }; + Writer.prototype.indentPartial = function indentPartial(partial3, indentation, lineHasNonSpace) { + var filteredIndentation = indentation.replace(/[^ \t]/g, ""); + var partialByNl = partial3.split(` +`); + for (var i = 0;i < partialByNl.length; i++) { + if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { + partialByNl[i] = filteredIndentation + partialByNl[i]; } - obj.string = zeros + obj.pattern + toQuantifier(obj.count); - tokens.push(obj); - start = max2 + 1; - prev = obj; } - return tokens; - } - function filterPatterns(arr3, comparison, prefix, intersection2, options) { - let result = []; - for (let ele of arr3) { - let { string: string4 } = ele; - if (!intersection2 && !contains(comparison, "string", string4)) { - result.push(prefix + string4); - } - if (intersection2 && contains(comparison, "string", string4)) { - result.push(prefix + string4); + return partialByNl.join(` +`); + }; + Writer.prototype.renderPartial = function renderPartial(token, context, partials, config3) { + if (!partials) + return; + var tags = this.getConfigTags(config3); + var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; + if (value != null) { + var lineHasNonSpace = token[6]; + var tagIndex = token[5]; + var indentation = token[4]; + var indentedValue = value; + if (tagIndex == 0 && indentation) { + indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); } + var tokens = this.parse(indentedValue, tags); + return this.renderTokens(tokens, context, partials, indentedValue, config3); } - return result; - } - function zip(a, b) { - let arr3 = []; - for (let i = 0;i < a.length; i++) - arr3.push([a[i], b[i]]); - return arr3; - } - function compare2(a, b) { - return a > b ? 1 : b > a ? -1 : 0; - } - function contains(arr3, key, val) { - return arr3.some((ele) => ele[key] === val); - } - function countNines(min, len) { - return Number(String(min).slice(0, -len) + "9".repeat(len)); - } - function countZeros(integer2, zeros) { - return integer2 - integer2 % Math.pow(10, zeros); - } - function toQuantifier(digits) { - let [start = 0, stop = ""] = digits; - if (stop || start > 1) { - return `{${start + (stop ? "," + stop : "")}}`; - } - return ""; - } - function toCharacterClass(a, b, options) { - return `[${a}${b - a === 1 ? "" : "-"}${b}]`; - } - function hasPadding(str) { - return /^-?(0+)\d/.test(str); - } - function padZeros(value, tok, options) { - if (!tok.isPadded) { + }; + Writer.prototype.unescapedValue = function unescapedValue(token, context) { + var value = context.lookup(token[1]); + if (value != null) return value; - } - let diff = Math.abs(tok.maxLen - String(value).length); - let relax = options.relaxZeros !== false; - switch (diff) { - case 0: - return ""; - case 1: - return relax ? "0?" : "0"; - case 2: - return relax ? "0{0,2}" : "00"; - default: { - return relax ? `0{0,${diff}}` : `0{${diff}}`; - } - } - } - toRegexRange.cache = {}; - toRegexRange.clearCache = () => toRegexRange.cache = {}; - module.exports = toRegexRange; -}); - -// ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js -var require_fill_range = __commonJS((exports, module) => { - /*! - * fill-range - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. - */ - var util3 = __require("util"); - var toRegexRange = require_to_regex_range(); - var isObject3 = (val) => val !== null && typeof val === "object" && !Array.isArray(val); - var transform2 = (toNumber) => { - return (value) => toNumber === true ? Number(value) : String(value); }; - var isValidValue = (value) => { - return typeof value === "number" || typeof value === "string" && value !== ""; + Writer.prototype.escapedValue = function escapedValue(token, context, config3) { + var escape2 = this.getConfigEscape(config3) || mustache.escape; + var value = context.lookup(token[1]); + if (value != null) + return typeof value === "number" && escape2 === mustache.escape ? String(value) : escape2(value); }; - var isNumber = (num) => Number.isInteger(+num); - var zeros = (input) => { - let value = `${input}`; - let index2 = -1; - if (value[0] === "-") - value = value.slice(1); - if (value === "0") - return false; - while (value[++index2] === "0") - ; - return index2 > 0; + Writer.prototype.rawValue = function rawValue(token) { + return token[1]; }; - var stringify4 = (start, end, options) => { - if (typeof start === "string" || typeof end === "string") { - return true; + Writer.prototype.getConfigTags = function getConfigTags(config3) { + if (isArray(config3)) { + return config3; + } else if (config3 && typeof config3 === "object") { + return config3.tags; + } else { + return; } - return options.stringify === true; }; - var pad = (input, maxLength, toNumber) => { - if (maxLength > 0) { - let dash = input[0] === "-" ? "-" : ""; - if (dash) - input = input.slice(1); - input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0"); - } - if (toNumber === false) { - return String(input); + Writer.prototype.getConfigEscape = function getConfigEscape(config3) { + if (config3 && typeof config3 === "object" && !isArray(config3)) { + return config3.escape; + } else { + return; } - return input; }; - var toMaxLen = (input, maxLength) => { - let negative = input[0] === "-" ? "-" : ""; - if (negative) { - input = input.slice(1); - maxLength--; + mustache = { + name: "mustache.js", + version: "4.2.0", + tags: ["{{", "}}"], + clearCache: undefined, + escape: undefined, + parse: undefined, + render: undefined, + Scanner: undefined, + Context: undefined, + Writer: undefined, + set templateCache(cache2) { + defaultWriter.templateCache = cache2; + }, + get templateCache() { + return defaultWriter.templateCache; } - while (input.length < maxLength) - input = "0" + input; - return negative ? "-" + input : input; }; - var toSequence = (parts, options, maxLen) => { - parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - let prefix = options.capture ? "" : "?:"; - let positives = ""; - let negatives = ""; - let result; - if (parts.positives.length) { - positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|"); - } - if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`; - } - if (positives && negatives) { - result = `${positives}|${negatives}`; - } else { - result = positives || negatives; - } - if (options.wrap) { - return `(${prefix}${result})`; - } - return result; + defaultWriter = new Writer; + mustache.clearCache = function clearCache2() { + return defaultWriter.clearCache(); }; - var toRange = (a, b, isNumbers, options) => { - if (isNumbers) { - return toRegexRange(a, b, { wrap: false, ...options }); - } - let start = String.fromCharCode(a); - if (a === b) - return start; - let stop = String.fromCharCode(b); - return `[${start}-${stop}]`; + mustache.parse = function parse15(template, tags) { + return defaultWriter.parse(template, tags); }; - var toRegex = (start, end, options) => { - if (Array.isArray(start)) { - let wrap3 = options.wrap === true; - let prefix = options.capture ? "" : "?:"; - return wrap3 ? `(${prefix}${start.join("|")})` : start.join("|"); + mustache.render = function render2(template, view, partials, config3) { + if (typeof template !== "string") { + throw new TypeError('Invalid template! Template should be a "string" ' + 'but "' + typeStr(template) + '" was given as the first ' + "argument for mustache#render(template, view, partials)"); } - return toRegexRange(start, end, options); - }; - var rangeError = (...args) => { - return new RangeError("Invalid range arguments: " + util3.inspect(...args)); - }; - var invalidRange = (start, end, options) => { - if (options.strictRanges === true) - throw rangeError([start, end]); - return []; + return defaultWriter.render(template, view, partials, config3); }; - var invalidStep = (step, options) => { - if (options.strictRanges === true) { - throw new TypeError(`Expected step "${step}" to be a number`); - } - return []; + mustache.escape = escapeHtml; + mustache.Scanner = Scanner; + mustache.Context = Context2; + mustache.Writer = Writer; + mustache_default = mustache; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/template.js +function configureMustache() { + mustache_default.escape = (text) => text; +} +var parseFString = (template) => { + const chars = template.split(""); + const nodes = []; + const nextBracket = (bracket, start) => { + for (let i2 = start;i2 < chars.length; i2 += 1) + if (bracket.includes(chars[i2])) + return i2; + return -1; }; - var fillNumbers = (start, end, step = 1, options = {}) => { - let a = Number(start); - let b = Number(end); - if (!Number.isInteger(a) || !Number.isInteger(b)) { - if (options.strictRanges === true) - throw rangeError([start, end]); - return []; - } - if (a === 0) - a = 0; - if (b === 0) - b = 0; - let descending = a > b; - let startString = String(start); - let endString = String(end); - let stepString = String(step); - step = Math.max(Math.abs(step), 1); - let padded = zeros(startString) || zeros(endString) || zeros(stepString); - let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; - let toNumber = padded === false && stringify4(start, end, options) === false; - let format3 = options.transform || transform2(toNumber); - if (options.toRegex && step === 1) { - return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + let i = 0; + while (i < chars.length) + if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { + nodes.push({ + type: "literal", + text: "{" + }); + i += 2; + } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { + nodes.push({ + type: "literal", + text: "}" + }); + i += 2; + } else if (chars[i] === "{") { + const j = nextBracket("}", i); + if (j < 0) + throw new Error("Unclosed '{' in template."); + nodes.push({ + type: "variable", + name: chars.slice(i + 1, j).join("") + }); + i = j + 1; + } else if (chars[i] === "}") + throw new Error("Single '}' in template."); + else { + const next = nextBracket("{}", i); + const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); + nodes.push({ + type: "literal", + text + }); + i = next < 0 ? chars.length : next; } - let parts = { negatives: [], positives: [] }; - let push2 = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num)); - let range = []; - let index2 = 0; - while (descending ? a >= b : a <= b) { - if (options.toRegex === true && step > 1) { - push2(a); - } else { - range.push(pad(format3(a, index2), maxLen, toNumber)); + return nodes; +}, mustacheTemplateToNodes = (template, context = []) => { + const nodes = []; + for (const temp of template) + if (temp[0] === "name") { + const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; + nodes.push({ + type: "variable", + name + }); + } else if ([ + "#", + "&", + "^", + ">" + ].includes(temp[0])) { + nodes.push({ + type: "variable", + name: temp[1] + }); + if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { + const newContext = [...context, temp[1]]; + const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); + nodes.push(...nestedNodes); } - a = descending ? a - step : a + step; - index2++; - } - if (options.toRegex === true) { - return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); + } else + nodes.push({ + type: "literal", + text: temp[1] + }); + return nodes; +}, parseMustache = (template) => { + configureMustache(); + return mustacheTemplateToNodes(mustache_default.parse(template)); +}, interpolateFString = (template, values) => { + return parseFString(template).reduce((res, node) => { + if (node.type === "variable") { + if (node.name in values) + return res + (typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name])); + throw new Error(`(f-string) Missing value for input ${node.name}`); } - return range; + return res + node.text; + }, ""); +}, interpolateMustache = (template, values) => { + configureMustache(); + return mustache_default.render(template, values); +}, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate = (template, templateFormat, inputValues) => { + try { + return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); + } catch (e) { + throw addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); + } +}, parseTemplate2 = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template), checkValidTemplate = (template, templateFormat, inputVariables) => { + if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) + throw new Error(`Invalid template format. Got \`${templateFormat}\`; + should be one of ${Object.keys(DEFAULT_FORMATTER_MAPPING)}`); + try { + const dummyInputs = Object.fromEntries(inputVariables.map((v) => [v, "foo"])); + if (Array.isArray(template)) + template.forEach((message) => { + if (message.type === "text" && "text" in message && typeof message.text === "string") + renderTemplate(message.text, templateFormat, dummyInputs); + else if (message.type === "image_url") { + if (typeof message.image_url === "string") + renderTemplate(message.image_url, templateFormat, dummyInputs); + else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { + const imageUrl = message.image_url.url; + renderTemplate(imageUrl, templateFormat, dummyInputs); + } + } else + throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); + }); + else + renderTemplate(template, templateFormat, dummyInputs); + } catch (e) { + throw new Error(`Invalid prompt schema: ${e.message}`); + } +}; +var init_template = __esm(() => { + init_errors3(); + init_mustache(); + DEFAULT_FORMATTER_MAPPING = { + "f-string": interpolateFString, + mustache: interpolateMustache }; - var fillLetters = (start, end, step = 1, options = {}) => { - if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) { - return invalidRange(start, end, options); - } - let format3 = options.transform || ((val) => String.fromCharCode(val)); - let a = `${start}`.charCodeAt(0); - let b = `${end}`.charCodeAt(0); - let descending = a > b; - let min = Math.min(a, b); - let max = Math.max(a, b); - if (options.toRegex && step === 1) { - return toRange(min, max, false, options); + DEFAULT_PARSER_MAPPING = { + "f-string": parseFString, + mustache: parseMustache + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/prompt.js +var PromptTemplate; +var init_prompt = __esm(() => { + init_string3(); + init_template(); + PromptTemplate = class PromptTemplate2 extends BaseStringPromptTemplate { + static lc_name() { + return "PromptTemplate"; } - let range = []; - let index2 = 0; - while (descending ? a >= b : a <= b) { - range.push(format3(a, index2)); - a = descending ? a - step : a + step; - index2++; + template; + templateFormat = "f-string"; + validateTemplate = true; + additionalContentFields; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === undefined) + this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + if (this.templateFormat === "mustache") + throw new Error("Mustache templates cannot be validated."); + let totalInputVariables = this.inputVariables; + if (this.partialVariables) + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.template, this.templateFormat, totalInputVariables); + } } - if (options.toRegex === true) { - return toRegex(range, null, { wrap: false, options }); + _getPromptType() { + return "prompt"; } - return range; - }; - var fill = (start, end, step, options = {}) => { - if (end == null && isValidValue(start)) { - return [start]; + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + return renderTemplate(this.template, this.templateFormat, allValues); } - if (!isValidValue(start) || !isValidValue(end)) { - return invalidRange(start, end, options); + static fromExamples(examples, suffix, inputVariables, exampleSeparator = ` + +`, prefix = "") { + return new PromptTemplate2({ + inputVariables, + template: [ + prefix, + ...examples, + suffix + ].join(exampleSeparator) + }); } - if (typeof step === "function") { - return fill(start, end, 1, { transform: step }); + static fromTemplate(template, options) { + const { templateFormat = "f-string", ...rest } = options ?? {}; + const names = /* @__PURE__ */ new Set; + parseTemplate2(template, templateFormat).forEach((node) => { + if (node.type === "variable") + names.add(node.name); + }); + return new PromptTemplate2({ + inputVariables: [...names], + templateFormat, + template, + ...rest + }); } - if (isObject3(step)) { - return fill(start, end, 0, step); + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new PromptTemplate2({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); } - let opts = { ...options }; - if (opts.capture === true) - opts.wrap = true; - step = step || opts.step || 1; - if (!isNumber(step)) { - if (step != null && !isObject3(step)) - return invalidStep(step, opts); - return fill(start, end, 1, step); + serialize() { + if (this.outputParser !== undefined) + throw new Error("Cannot serialize a prompt template with an output parser"); + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + template: this.template, + template_format: this.templateFormat + }; } - if (isNumber(start) && isNumber(end)) { - return fillNumbers(start, end, step, opts); + static async deserialize(data) { + if (!data.template) + throw new Error("Prompt template must have a template"); + return new PromptTemplate2({ + inputVariables: data.input_variables, + template: data.template, + templateFormat: data.template_format + }); } - return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; - module.exports = fill; }); -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js -var require_compile = __commonJS((exports, module) => { - var fill = require_fill_range(); - var utils = require_utils(); - var compile = (ast, options = {}) => { - const walk = (node, parent = {}) => { - const invalidBlock = utils.isInvalidBrace(parent); - const invalidNode = node.invalid === true && options.escapeInvalid === true; - const invalid = invalidBlock === true || invalidNode === true; - const prefix = options.escapeInvalid === true ? "\\" : ""; - let output = ""; - if (node.isOpen === true) { - return prefix + node.value; - } - if (node.isClose === true) { - console.log("node.isClose", prefix, node.value); - return prefix + node.value; - } - if (node.type === "open") { - return invalid ? prefix + node.value : "("; - } - if (node.type === "close") { - return invalid ? prefix + node.value : ")"; - } - if (node.type === "comma") { - return node.prev.type === "comma" ? "" : invalid ? node.value : "|"; - } - if (node.value) { - return node.value; - } - if (node.nodes && node.ranges > 0) { - const args = utils.reduce(node.nodes); - const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); - if (range.length !== 0) { - return args.length > 1 && range.length > 1 ? `(${range})` : range; - } - } - if (node.nodes) { - for (const child of node.nodes) { - output += walk(child, node); - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/image.js +var ImagePromptTemplate; +var init_image = __esm(() => { + init_prompt_values(); + init_base10(); + init_template(); + ImagePromptTemplate = class ImagePromptTemplate2 extends BasePromptTemplate { + static lc_name() { + return "ImagePromptTemplate"; + } + lc_namespace = [ + "langchain_core", + "prompts", + "image" + ]; + template; + templateFormat = "f-string"; + validateTemplate = true; + additionalContentFields; + constructor(input) { + super(input); + this.template = input.template; + this.templateFormat = input.templateFormat ?? this.templateFormat; + this.validateTemplate = input.validateTemplate ?? this.validateTemplate; + this.additionalContentFields = input.additionalContentFields; + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate([{ + type: "image_url", + image_url: this.template + }], this.templateFormat, totalInputVariables); } + } + _getPromptType() { + return "prompt"; + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new ImagePromptTemplate2({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); + } + async format(values) { + const formatted = {}; + for (const [key, value] of Object.entries(this.template)) + if (typeof value === "string") + formatted[key] = renderTemplate(value, this.templateFormat, values); + else + formatted[key] = value; + const url3 = values.url || formatted.url; + const detail = values.detail || formatted.detail; + if (!url3) + throw new Error("Must provide either an image URL."); + if (typeof url3 !== "string") + throw new Error("url must be a string."); + const output = { url: url3 }; + if (detail) + output.detail = detail; return output; - }; - return walk(ast); - }; - module.exports = compile; -}); - -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js -var require_expand = __commonJS((exports, module) => { - var fill = require_fill_range(); - var stringify4 = require_stringify2(); - var utils = require_utils(); - var append = (queue2 = "", stash = "", enclose = false) => { - const result = []; - queue2 = [].concat(queue2); - stash = [].concat(stash); - if (!stash.length) - return queue2; - if (!queue2.length) { - return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash; } - for (const item of queue2) { - if (Array.isArray(item)) { - for (const value of item) { - result.push(append(value, stash, enclose)); - } - } else { - for (let ele of stash) { - if (enclose === true && typeof ele === "string") - ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); - } - } + async formatPromptValue(values) { + return new ImagePromptValue(await this.format(values)); } - return utils.flatten(result); - }; - var expand = (ast, options = {}) => { - const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; - const walk = (node, parent = {}) => { - node.queue = []; - let p = parent; - let q = parent.queue; - while (p.type !== "brace" && p.type !== "root" && p.parent) { - p = p.parent; - q = p.queue; - } - if (node.invalid || node.dollar) { - q.push(append(q.pop(), stringify4(node, options))); - return; - } - if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) { - q.push(append(q.pop(), ["{}"])); - return; - } - if (node.nodes && node.ranges > 0) { - const args = utils.reduce(node.nodes); - if (utils.exceedsLimit(...args, options.step, rangeLimit)) { - throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit."); - } - let range = fill(...args, options); - if (range.length === 0) { - range = stringify4(node, options); - } - q.push(append(q.pop(), range)); - node.nodes = []; - return; - } - const enclose = utils.encloseBrace(node); - let queue2 = node.queue; - let block = node; - while (block.type !== "brace" && block.type !== "root" && block.parent) { - block = block.parent; - queue2 = block.queue; - } - for (let i = 0;i < node.nodes.length; i++) { - const child = node.nodes[i]; - if (child.type === "comma" && node.type === "brace") { - if (i === 1) - queue2.push(""); - queue2.push(""); - continue; - } - if (child.type === "close") { - q.push(append(q.pop(), queue2, enclose)); - continue; - } - if (child.value && child.type !== "open") { - queue2.push(append(queue2.pop(), child.value)); - continue; - } - if (child.nodes) { - walk(child, node); - } - } - return queue2; - }; - return utils.flatten(walk(ast)); - }; - module.exports = expand; -}); - -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js -var require_constants = __commonJS((exports, module) => { - module.exports = { - MAX_LENGTH: 1e4, - CHAR_0: "0", - CHAR_9: "9", - CHAR_UPPERCASE_A: "A", - CHAR_LOWERCASE_A: "a", - CHAR_UPPERCASE_Z: "Z", - CHAR_LOWERCASE_Z: "z", - CHAR_LEFT_PARENTHESES: "(", - CHAR_RIGHT_PARENTHESES: ")", - CHAR_ASTERISK: "*", - CHAR_AMPERSAND: "&", - CHAR_AT: "@", - CHAR_BACKSLASH: "\\", - CHAR_BACKTICK: "`", - CHAR_CARRIAGE_RETURN: "\r", - CHAR_CIRCUMFLEX_ACCENT: "^", - CHAR_COLON: ":", - CHAR_COMMA: ",", - CHAR_DOLLAR: "$", - CHAR_DOT: ".", - CHAR_DOUBLE_QUOTE: '"', - CHAR_EQUAL: "=", - CHAR_EXCLAMATION_MARK: "!", - CHAR_FORM_FEED: "\f", - CHAR_FORWARD_SLASH: "/", - CHAR_HASH: "#", - CHAR_HYPHEN_MINUS: "-", - CHAR_LEFT_ANGLE_BRACKET: "<", - CHAR_LEFT_CURLY_BRACE: "{", - CHAR_LEFT_SQUARE_BRACKET: "[", - CHAR_LINE_FEED: ` -`, - CHAR_NO_BREAK_SPACE: " ", - CHAR_PERCENT: "%", - CHAR_PLUS: "+", - CHAR_QUESTION_MARK: "?", - CHAR_RIGHT_ANGLE_BRACKET: ">", - CHAR_RIGHT_CURLY_BRACE: "}", - CHAR_RIGHT_SQUARE_BRACKET: "]", - CHAR_SEMICOLON: ";", - CHAR_SINGLE_QUOTE: "'", - CHAR_SPACE: " ", - CHAR_TAB: "\t", - CHAR_UNDERSCORE: "_", - CHAR_VERTICAL_LINE: "|", - CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF" }; }); -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js -var require_parse2 = __commonJS((exports, module) => { - var stringify4 = require_stringify2(); - var { - MAX_LENGTH, - CHAR_BACKSLASH, - CHAR_BACKTICK, - CHAR_COMMA, - CHAR_DOT, - CHAR_LEFT_PARENTHESES, - CHAR_RIGHT_PARENTHESES, - CHAR_LEFT_CURLY_BRACE, - CHAR_RIGHT_CURLY_BRACE, - CHAR_LEFT_SQUARE_BRACKET, - CHAR_RIGHT_SQUARE_BRACKET, - CHAR_DOUBLE_QUOTE, - CHAR_SINGLE_QUOTE, - CHAR_NO_BREAK_SPACE, - CHAR_ZERO_WIDTH_NOBREAK_SPACE - } = require_constants(); - var parse11 = (input, options = {}) => { - if (typeof input !== "string") { - throw new TypeError("Expected a string"); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/dict.js +function _getInputVariables(template, templateFormat) { + const inputVariables = []; + for (const v of Object.values(template)) + if (typeof v === "string") + parseTemplate2(v, templateFormat).forEach((t) => { + if (t.type === "variable") + inputVariables.push(t.name); + }); + else if (Array.isArray(v)) { + for (const x of v) + if (typeof x === "string") + parseTemplate2(x, templateFormat).forEach((t) => { + if (t.type === "variable") + inputVariables.push(t.name); + }); + else if (typeof x === "object") + inputVariables.push(..._getInputVariables(x, templateFormat)); + } else if (typeof v === "object" && v !== null) + inputVariables.push(..._getInputVariables(v, templateFormat)); + return Array.from(new Set(inputVariables)); +} +function _insertInputVariables(template, inputs, templateFormat) { + const formatted = {}; + for (const [k, v] of Object.entries(template)) + if (typeof v === "string") + formatted[k] = renderTemplate(v, templateFormat, inputs); + else if (Array.isArray(v)) { + const formattedV = []; + for (const x of v) + if (typeof x === "string") + formattedV.push(renderTemplate(x, templateFormat, inputs)); + else if (typeof x === "object") + formattedV.push(_insertInputVariables(x, inputs, templateFormat)); + formatted[k] = formattedV; + } else if (typeof v === "object" && v !== null) + formatted[k] = _insertInputVariables(v, inputs, templateFormat); + else + formatted[k] = v; + return formatted; +} +var DictPromptTemplate; +var init_dict = __esm(() => { + init_base4(); + init_template(); + DictPromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "dict" + ]; + lc_serializable = true; + template; + templateFormat; + inputVariables; + static lc_name() { + return "DictPromptTemplate"; } - const opts = options || {}; - const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - if (input.length > max) { - throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + constructor(fields) { + const templateFormat = fields.templateFormat ?? "f-string"; + const inputVariables = _getInputVariables(fields.template, templateFormat); + super({ + inputVariables, + ...fields + }); + this.template = fields.template; + this.templateFormat = templateFormat; + this.inputVariables = inputVariables; } - const ast = { type: "root", input, nodes: [] }; - const stack = [ast]; - let block = ast; - let prev = ast; - let brackets = 0; - const length = input.length; - let index2 = 0; - let depth = 0; - let value; - const advance = () => input[index2++]; - const push2 = (node) => { - if (node.type === "text" && prev.type === "dot") { - prev.type = "text"; - } - if (prev && prev.type === "text" && node.type === "text") { - prev.value += node.value; - return; - } - block.nodes.push(node); - node.parent = block; - node.prev = prev; - prev = node; - return node; - }; - push2({ type: "bos" }); - while (index2 < length) { - block = stack[stack.length - 1]; - value = advance(); - if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { - continue; - } - if (value === CHAR_BACKSLASH) { - push2({ type: "text", value: (options.keepEscaping ? value : "") + advance() }); - continue; - } - if (value === CHAR_RIGHT_SQUARE_BRACKET) { - push2({ type: "text", value: "\\" + value }); - continue; - } - if (value === CHAR_LEFT_SQUARE_BRACKET) { - brackets++; - let next; - while (index2 < length && (next = advance())) { - value += next; - if (next === CHAR_LEFT_SQUARE_BRACKET) { - brackets++; - continue; - } - if (next === CHAR_BACKSLASH) { - value += advance(); - continue; - } - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - brackets--; - if (brackets === 0) { - break; - } - } - } - push2({ type: "text", value }); - continue; - } - if (value === CHAR_LEFT_PARENTHESES) { - block = push2({ type: "paren", nodes: [] }); - stack.push(block); - push2({ type: "text", value }); - continue; - } - if (value === CHAR_RIGHT_PARENTHESES) { - if (block.type !== "paren") { - push2({ type: "text", value }); - continue; - } - block = stack.pop(); - push2({ type: "text", value }); - block = stack[stack.length - 1]; - continue; - } - if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - const open = value; - let next; - if (options.keepQuotes !== true) { - value = ""; - } - while (index2 < length && (next = advance())) { - if (next === CHAR_BACKSLASH) { - value += next + advance(); - continue; - } - if (next === open) { - if (options.keepQuotes === true) - value += next; - break; - } - value += next; - } - push2({ type: "text", value }); - continue; - } - if (value === CHAR_LEFT_CURLY_BRACE) { - depth++; - const dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true; - const brace = { - type: "brace", - open: true, - close: false, - dollar, - depth, - commas: 0, - ranges: 0, - nodes: [] - }; - block = push2(brace); - stack.push(block); - push2({ type: "open", value }); - continue; - } - if (value === CHAR_RIGHT_CURLY_BRACE) { - if (block.type !== "brace") { - push2({ type: "text", value }); - continue; - } - const type = "close"; - block = stack.pop(); - block.close = true; - push2({ type, value }); - depth--; - block = stack[stack.length - 1]; - continue; - } - if (value === CHAR_COMMA && depth > 0) { - if (block.ranges > 0) { - block.ranges = 0; - const open = block.nodes.shift(); - block.nodes = [open, { type: "text", value: stringify4(block) }]; - } - push2({ type: "comma", value }); - block.commas++; - continue; - } - if (value === CHAR_DOT && depth > 0 && block.commas === 0) { - const siblings = block.nodes; - if (depth === 0 || siblings.length === 0) { - push2({ type: "text", value }); - continue; - } - if (prev.type === "dot") { - block.range = []; - prev.value += value; - prev.type = "range"; - if (block.nodes.length !== 3 && block.nodes.length !== 5) { - block.invalid = true; - block.ranges = 0; - prev.type = "text"; - continue; - } - block.ranges++; - block.args = []; - continue; - } - if (prev.type === "range") { - siblings.pop(); - const before = siblings[siblings.length - 1]; - before.value += prev.value + value; - prev = before; - block.ranges--; - continue; - } - push2({ type: "dot", value }); - continue; - } - push2({ type: "text", value }); + async format(values) { + return _insertInputVariables(this.template, values, this.templateFormat); + } + async invoke(values) { + return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); } - do { - block = stack.pop(); - if (block.type !== "root") { - block.nodes.forEach((node) => { - if (!node.nodes) { - if (node.type === "open") - node.isOpen = true; - if (node.type === "close") - node.isClose = true; - if (!node.nodes) - node.type = "text"; - node.invalid = true; - } - }); - const parent = stack[stack.length - 1]; - const index3 = parent.nodes.indexOf(block); - parent.nodes.splice(index3, 1, ...block.nodes); - } - } while (stack.length > 0); - push2({ type: "eos" }); - return ast; }; - module.exports = parse11; }); -// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js -var require_braces = __commonJS((exports, module) => { - var stringify4 = require_stringify2(); - var compile = require_compile(); - var expand = require_expand(); - var parse11 = require_parse2(); - var braces = (input, options = {}) => { - let output = []; - if (Array.isArray(input)) { - for (const pattern of input) { - const result = braces.create(pattern, options); - if (Array.isArray(result)) { - output.push(...result); - } else { - output.push(result); - } - } - } else { - output = [].concat(braces.create(input, options)); - } - if (options && options.expand === true && options.nodupes === true) { - output = [...new Set(output)]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/chat.js +function isTextTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) + return false; + return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; +} +function isImageTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) + return false; + return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && ("url" in param.image_url) && typeof param.image_url.url === "string"); +} +function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { + return typeof baseMessagePromptTemplateLike.formatMessages === "function"; +} +function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { + if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) + return messagePromptTemplateLike; + if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { + const messageContent = messagePromptTemplateLike[1]; + if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") + return new MessagesPlaceholder({ + variableName: messageContent.slice(2, -2), + optional: true + }); + else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") + return new MessagesPlaceholder({ + variableName: messageContent.slice(1, -1), + optional: true + }); + throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); + } + const message = coerceMessageLikeToMessage(messagePromptTemplateLike); + let templateData; + if (typeof message.content === "string") + templateData = message.content; + else + templateData = message.content.map((item) => { + if ("text" in item) + return { + ...item, + text: item.text + }; + else if ("image_url" in item) + return { + ...item, + image_url: item.image_url + }; + else + return item; + }); + if (message._getType() === "human") + return HumanMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "ai") + return AIMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "system") + return SystemMessagePromptTemplate.fromTemplate(templateData, extra); + else if (ChatMessage.isInstance(message)) + return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); + else + throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); +} +function isMessagesPlaceholder(x) { + return x.constructor.lc_name() === "MessagesPlaceholder"; +} +var BaseMessagePromptTemplate, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, _StringImageMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; +var init_chat2 = __esm(() => { + init_errors3(); + init_base(); + init_ai(); + init_chat(); + init_human(); + init_system(); + init_utils3(); + init_base4(); + init_messages(); + init_prompt_values(); + init_base10(); + init_string3(); + init_template(); + init_prompt(); + init_image(); + init_dict(); + BaseMessagePromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + async invoke(input, options) { + return this._callWithConfig((input2) => this.formatMessages(input2), input, { + ...options, + runType: "prompt" + }); } - return output; }; - braces.parse = (input, options = {}) => parse11(input, options); - braces.stringify = (input, options = {}) => { - if (typeof input === "string") { - return stringify4(braces.parse(input, options), options); + MessagesPlaceholder = class extends BaseMessagePromptTemplate { + static lc_name() { + return "MessagesPlaceholder"; } - return stringify4(input, options); - }; - braces.compile = (input, options = {}) => { - if (typeof input === "string") { - input = braces.parse(input, options); + variableName; + optional; + constructor(fields) { + if (typeof fields === "string") + fields = { variableName: fields }; + super(fields); + this.variableName = fields.variableName; + this.optional = fields.optional ?? false; } - return compile(input, options); - }; - braces.expand = (input, options = {}) => { - if (typeof input === "string") { - input = braces.parse(input, options); - } - let result = expand(input, options); - if (options.noempty === true) { - result = result.filter(Boolean); + get inputVariables() { + return [this.variableName]; } - if (options.nodupes === true) { - result = [...new Set(result)]; + async formatMessages(values) { + const input = values[this.variableName]; + if (this.optional && !input) + return []; + else if (!input) { + const error90 = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); + error90.name = "InputFormatError"; + throw error90; + } + let formattedMessages; + try { + if (Array.isArray(input)) + formattedMessages = input.map(coerceMessageLikeToMessage); + else + formattedMessages = [coerceMessageLikeToMessage(input)]; + } catch (e) { + const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); + const error90 = new Error([ + `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, + `Received value: ${readableInput}`, + `Additional message: ${e.message}` + ].join(` + +`)); + error90.name = "InputFormatError"; + error90.lc_error_code = e.lc_error_code; + throw error90; + } + return formattedMessages; } - return result; }; - braces.create = (input, options = {}) => { - if (input === "" || input.length < 3) { - return [input]; + BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { + prompt; + constructor(fields) { + if (!("prompt" in fields)) + fields = { prompt: fields }; + super(fields); + this.prompt = fields.prompt; } - return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); - }; - module.exports = braces; -}); - -// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/constants.js -var require_constants2 = __commonJS((exports, module) => { - var path2 = __require("path"); - var WIN_SLASH = "\\\\/"; - var WIN_NO_SLASH = `[^${WIN_SLASH}]`; - var DEFAULT_MAX_EXTGLOB_RECURSION = 0; - var DOT_LITERAL = "\\."; - var PLUS_LITERAL = "\\+"; - var QMARK_LITERAL = "\\?"; - var SLASH_LITERAL = "\\/"; - var ONE_CHAR = "(?=.)"; - var QMARK = "[^/]"; - var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; - var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; - var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; - var NO_DOT = `(?!${DOT_LITERAL})`; - var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; - var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; - var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; - var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; - var STAR = `${QMARK}*?`; - var POSIX_CHARS = { - DOT_LITERAL, - PLUS_LITERAL, - QMARK_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - QMARK, - END_ANCHOR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK_NO_DOT, - STAR, - START_ANCHOR - }; - var WINDOWS_CHARS = { - ...POSIX_CHARS, - SLASH_LITERAL: `[${WIN_SLASH}]`, - QMARK: WIN_NO_SLASH, - STAR: `${WIN_NO_SLASH}*?`, - DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, - NO_DOT: `(?!${DOT_LITERAL})`, - NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, - NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - QMARK_NO_DOT: `[^.${WIN_SLASH}]`, - START_ANCHOR: `(?:^|[${WIN_SLASH}])`, - END_ANCHOR: `(?:[${WIN_SLASH}]|$)` - }; - var POSIX_REGEX_SOURCE = { - __proto__: null, - alnum: "a-zA-Z0-9", - alpha: "a-zA-Z", - ascii: "\\x00-\\x7F", - blank: " \\t", - cntrl: "\\x00-\\x1F\\x7F", - digit: "0-9", - graph: "\\x21-\\x7E", - lower: "a-z", - print: "\\x20-\\x7E ", - punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", - space: " \\t\\r\\n\\v\\f", - upper: "A-Z", - word: "A-Za-z0-9_", - xdigit: "A-Fa-f0-9" - }; - module.exports = { - DEFAULT_MAX_EXTGLOB_RECURSION, - MAX_LENGTH: 1024 * 64, - POSIX_REGEX_SOURCE, - REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, - REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, - REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, - REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, - REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, - REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, - REPLACEMENTS: { - __proto__: null, - "***": "*", - "**/**": "**", - "**/**/**": "**" - }, - CHAR_0: 48, - CHAR_9: 57, - CHAR_UPPERCASE_A: 65, - CHAR_LOWERCASE_A: 97, - CHAR_UPPERCASE_Z: 90, - CHAR_LOWERCASE_Z: 122, - CHAR_LEFT_PARENTHESES: 40, - CHAR_RIGHT_PARENTHESES: 41, - CHAR_ASTERISK: 42, - CHAR_AMPERSAND: 38, - CHAR_AT: 64, - CHAR_BACKWARD_SLASH: 92, - CHAR_CARRIAGE_RETURN: 13, - CHAR_CIRCUMFLEX_ACCENT: 94, - CHAR_COLON: 58, - CHAR_COMMA: 44, - CHAR_DOT: 46, - CHAR_DOUBLE_QUOTE: 34, - CHAR_EQUAL: 61, - CHAR_EXCLAMATION_MARK: 33, - CHAR_FORM_FEED: 12, - CHAR_FORWARD_SLASH: 47, - CHAR_GRAVE_ACCENT: 96, - CHAR_HASH: 35, - CHAR_HYPHEN_MINUS: 45, - CHAR_LEFT_ANGLE_BRACKET: 60, - CHAR_LEFT_CURLY_BRACE: 123, - CHAR_LEFT_SQUARE_BRACKET: 91, - CHAR_LINE_FEED: 10, - CHAR_NO_BREAK_SPACE: 160, - CHAR_PERCENT: 37, - CHAR_PLUS: 43, - CHAR_QUESTION_MARK: 63, - CHAR_RIGHT_ANGLE_BRACKET: 62, - CHAR_RIGHT_CURLY_BRACE: 125, - CHAR_RIGHT_SQUARE_BRACKET: 93, - CHAR_SEMICOLON: 59, - CHAR_SINGLE_QUOTE: 39, - CHAR_SPACE: 32, - CHAR_TAB: 9, - CHAR_UNDERSCORE: 95, - CHAR_VERTICAL_LINE: 124, - CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, - SEP: path2.sep, - extglobChars(chars) { - return { - "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` }, - "?": { type: "qmark", open: "(?:", close: ")?" }, - "+": { type: "plus", open: "(?:", close: ")+" }, - "*": { type: "star", open: "(?:", close: ")*" }, - "@": { type: "at", open: "(?:", close: ")" } - }; - }, - globChars(win32) { - return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + get inputVariables() { + return this.prompt.inputVariables; } - }; -}); - -// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/utils.js -var require_utils2 = __commonJS((exports) => { - var path2 = __require("path"); - var win32 = process.platform === "win32"; - var { - REGEX_BACKSLASH, - REGEX_REMOVE_BACKSLASH, - REGEX_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_GLOBAL - } = require_constants2(); - exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); - exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); - exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str); - exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); - exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); - exports.removeBackslashes = (str) => { - return str.replace(REGEX_REMOVE_BACKSLASH, (match2) => { - return match2 === "\\" ? "" : match2; - }); - }; - exports.supportsLookbehinds = () => { - const segs = process.version.slice(1).split(".").map(Number); - if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { - return true; + async formatMessages(values) { + return [await this.format(values)]; } - return false; }; - exports.isWindows = (options) => { - if (options && typeof options.windows === "boolean") { - return options.windows; + BaseChatPromptTemplate = class extends BasePromptTemplate { + constructor(input) { + super(input); } - return win32 === true || path2.sep === "\\"; - }; - exports.escapeLast = (input, char, lastIdx) => { - const idx = input.lastIndexOf(char, lastIdx); - if (idx === -1) - return input; - if (input[idx - 1] === "\\") - return exports.escapeLast(input, char, idx - 1); - return `${input.slice(0, idx)}\\${input.slice(idx)}`; - }; - exports.removePrefix = (input, state = {}) => { - let output = input; - if (output.startsWith("./")) { - output = output.slice(2); - state.prefix = "./"; + async format(values) { + return (await this.formatPromptValue(values)).toString(); } - return output; - }; - exports.wrapOutput = (input, state = {}, options = {}) => { - const prepend = options.contains ? "" : "^"; - const append = options.contains ? "" : "$"; - let output = `${prepend}(?:${input})${append}`; - if (state.negated === true) { - output = `(?:^(?!${output}).*$)`; + async formatPromptValue(values) { + return new ChatPromptValue(await this.formatMessages(values)); } - return output; - }; -}); - -// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/scan.js -var require_scan = __commonJS((exports, module) => { - var utils = require_utils2(); - var { - CHAR_ASTERISK, - CHAR_AT, - CHAR_BACKWARD_SLASH, - CHAR_COMMA, - CHAR_DOT, - CHAR_EXCLAMATION_MARK, - CHAR_FORWARD_SLASH, - CHAR_LEFT_CURLY_BRACE, - CHAR_LEFT_PARENTHESES, - CHAR_LEFT_SQUARE_BRACKET, - CHAR_PLUS, - CHAR_QUESTION_MARK, - CHAR_RIGHT_CURLY_BRACE, - CHAR_RIGHT_PARENTHESES, - CHAR_RIGHT_SQUARE_BRACKET - } = require_constants2(); - var isPathSeparator = (code) => { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; - var depth = (token) => { - if (token.isPrefix !== true) { - token.depth = token.isGlobstar ? Infinity : 1; + ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { + static lc_name() { + return "ChatMessagePromptTemplate"; } - }; - var scan2 = (input, options) => { - const opts = options || {}; - const length = input.length - 1; - const scanToEnd = opts.parts === true || opts.scanToEnd === true; - const slashes = []; - const tokens = []; - const parts = []; - let str = input; - let index2 = -1; - let start = 0; - let lastIndex = 0; - let isBrace = false; - let isBracket = false; - let isGlob = false; - let isExtglob = false; - let isGlobstar = false; - let braceEscaped = false; - let backslashes = false; - let negated = false; - let negatedExtglob = false; - let finished = false; - let braces = 0; - let prev; - let code; - let token = { value: "", depth: 0, isGlob: false }; - const eos2 = () => index2 >= length; - const peek = () => str.charCodeAt(index2 + 1); - const advance = () => { - prev = code; - return str.charCodeAt(++index2); - }; - while (index2 < length) { - code = advance(); - let next; - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - if (code === CHAR_LEFT_CURLY_BRACE) { - braceEscaped = true; - } - continue; - } - if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { - braces++; - while (eos2() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } - if (code === CHAR_LEFT_CURLY_BRACE) { - braces++; - continue; - } - if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; - if (scanToEnd === true) { - continue; - } - break; - } - if (braceEscaped !== true && code === CHAR_COMMA) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; - if (scanToEnd === true) { - continue; - } - break; - } - if (code === CHAR_RIGHT_CURLY_BRACE) { - braces--; - if (braces === 0) { - braceEscaped = false; - isBrace = token.isBrace = true; - finished = true; - break; - } - } - } - if (scanToEnd === true) { - continue; - } - break; - } - if (code === CHAR_FORWARD_SLASH) { - slashes.push(index2); - tokens.push(token); - token = { value: "", depth: 0, isGlob: false }; - if (finished === true) - continue; - if (prev === CHAR_DOT && index2 === start + 1) { - start += 2; - continue; - } - lastIndex = index2 + 1; - continue; - } - if (opts.noext !== true) { - const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; - if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - isExtglob = token.isExtglob = true; - finished = true; - if (code === CHAR_EXCLAMATION_MARK && index2 === start) { - negatedExtglob = true; - } - if (scanToEnd === true) { - while (eos2() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - if (code === CHAR_RIGHT_PARENTHESES) { - isGlob = token.isGlob = true; - finished = true; - break; - } - } - continue; - } - break; - } - } - if (code === CHAR_ASTERISK) { - if (prev === CHAR_ASTERISK) - isGlobstar = token.isGlobstar = true; - isGlob = token.isGlob = true; - finished = true; - if (scanToEnd === true) { - continue; - } - break; - } - if (code === CHAR_QUESTION_MARK) { - isGlob = token.isGlob = true; - finished = true; - if (scanToEnd === true) { - continue; - } - break; - } - if (code === CHAR_LEFT_SQUARE_BRACKET) { - while (eos2() !== true && (next = advance())) { - if (next === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - isBracket = token.isBracket = true; - isGlob = token.isGlob = true; - finished = true; - break; - } - } - if (scanToEnd === true) { - continue; - } - break; - } - if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index2 === start) { - negated = token.negated = true; - start++; - continue; - } - if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - if (scanToEnd === true) { - while (eos2() !== true && (code = advance())) { - if (code === CHAR_LEFT_PARENTHESES) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - if (code === CHAR_RIGHT_PARENTHESES) { - finished = true; - break; - } - } - continue; - } - break; - } - if (isGlob === true) { - finished = true; - if (scanToEnd === true) { - continue; - } - break; - } + role; + constructor(fields, role) { + if (!("prompt" in fields)) + fields = { + prompt: fields, + role + }; + super(fields); + this.role = fields.role; } - if (opts.noext === true) { - isExtglob = false; - isGlob = false; + async format(values) { + return new ChatMessage(await this.prompt.format(values), this.role); } - let base = str; - let prefix = ""; - let glob = ""; - if (start > 0) { - prefix = str.slice(0, start); - str = str.slice(start); - lastIndex -= start; + static fromTemplate(template, role, options) { + return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); } - if (base && isGlob === true && lastIndex > 0) { - base = str.slice(0, lastIndex); - glob = str.slice(lastIndex); - } else if (isGlob === true) { - base = ""; - glob = str; - } else { - base = str; + }; + _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + inputVariables = []; + additionalOptions = {}; + prompt; + messageClass; + static _messageClass() { + throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); } - if (base && base !== "" && base !== "/" && base !== str) { - if (isPathSeparator(base.charCodeAt(base.length - 1))) { - base = base.slice(0, -1); - } + chatMessageClass; + constructor(fields, additionalOptions) { + if (!("prompt" in fields)) + fields = { prompt: fields }; + super(fields); + this.prompt = fields.prompt; + if (Array.isArray(this.prompt)) { + let inputVariables = []; + this.prompt.forEach((prompt) => { + if ("inputVariables" in prompt) + inputVariables = inputVariables.concat(prompt.inputVariables); + }); + this.inputVariables = inputVariables; + } else + this.inputVariables = this.prompt.inputVariables; + this.additionalOptions = additionalOptions ?? this.additionalOptions; } - if (opts.unescape === true) { - if (glob) - glob = utils.removeBackslashes(glob); - if (base && backslashes === true) { - base = utils.removeBackslashes(base); - } + createMessage(content) { + const constructor = this.constructor; + if (constructor._messageClass()) + return new (constructor._messageClass())({ content }); + else if (constructor.chatMessageClass) { + const MsgClass = constructor.chatMessageClass(); + return new MsgClass({ + content, + role: this.getRoleFromMessageClass(MsgClass.lc_name()) + }); + } else + throw new Error("No message class defined"); } - const state = { - prefix, - input, - start, - base, - glob, - isBrace, - isBracket, - isGlob, - isExtglob, - isGlobstar, - negated, - negatedExtglob - }; - if (opts.tokens === true) { - state.maxDepth = 0; - if (!isPathSeparator(code)) { - tokens.push(token); + getRoleFromMessageClass(name) { + switch (name) { + case "HumanMessage": + return "human"; + case "AIMessage": + return "ai"; + case "SystemMessage": + return "system"; + case "ChatMessage": + return "chat"; + default: + throw new Error("Invalid message class name"); } - state.tokens = tokens; } - if (opts.parts === true || opts.tokens === true) { - let prevIndex; - for (let idx = 0;idx < slashes.length; idx++) { - const n3 = prevIndex ? prevIndex + 1 : start; - const i = slashes[idx]; - const value = input.slice(n3, i); - if (opts.tokens) { - if (idx === 0 && start !== 0) { - tokens[idx].isPrefix = true; - tokens[idx].value = prefix; - } else { - tokens[idx].value = value; + static fromTemplate(template, additionalOptions) { + if (typeof template === "string") + return new this(PromptTemplate.fromTemplate(template, additionalOptions)); + const prompt = []; + for (const item of template) + if (typeof item === "string") + prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); + else if (item === null) {} else if (isTextTemplateParam(item)) { + let text = ""; + if (typeof item.text === "string") + text = item.text ?? ""; + const options = { + ...additionalOptions, + additionalContentFields: item + }; + prompt.push(PromptTemplate.fromTemplate(text, options)); + } else if (isImageTemplateParam(item)) { + let imgTemplate = item.image_url ?? ""; + let imgTemplateObject; + let inputVariables = []; + if (typeof imgTemplate === "string") { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") + parsedTemplate = parseMustache(imgTemplate); + else + parsedTemplate = parseFString(imgTemplate); + const variables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); + if ((variables?.length ?? 0) > 0) { + if (variables.length > 1) + throw new Error(`Only one format variable allowed per image template. +Got: ${variables} +From: ${imgTemplate}`); + inputVariables = [variables[0]]; + } else + inputVariables = []; + imgTemplate = { url: imgTemplate }; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else if (typeof imgTemplate === "object") { + if ("url" in imgTemplate) { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") + parsedTemplate = parseMustache(imgTemplate.url); + else + parsedTemplate = parseFString(imgTemplate.url); + inputVariables = parsedTemplate.flatMap((item2) => item2.type === "variable" ? [item2.name] : []); + } else + inputVariables = []; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else + throw new Error("Invalid image template"); + prompt.push(imgTemplateObject); + } else if (typeof item === "object") + prompt.push(new DictPromptTemplate({ + template: item, + templateFormat: additionalOptions?.templateFormat + })); + return new this({ + prompt, + additionalOptions + }); + } + async format(input) { + if (this.prompt instanceof BaseStringPromptTemplate) { + const text = await this.prompt.format(input); + return this.createMessage(text); + } else { + const content = []; + for (const prompt of this.prompt) { + let inputs = {}; + if (!("inputVariables" in prompt)) + throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); + for (const item of prompt.inputVariables) { + if (!inputs) + inputs = { [item]: input[item] }; + inputs = { + ...inputs, + [item]: input[item] + }; + } + if (prompt instanceof BaseStringPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) + additionalContentFields = prompt.additionalContentFields; + if (formatted !== "") + content.push({ + ...additionalContentFields, + type: "text", + text: formatted + }); + } else if (prompt instanceof ImagePromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) + additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + type: "image_url", + image_url: formatted + }); + } else if (prompt instanceof DictPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) + additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + ...formatted + }); } - depth(tokens[idx]); - state.maxDepth += tokens[idx].depth; - } - if (idx !== 0 || value !== "") { - parts.push(value); - } - prevIndex = i; - } - if (prevIndex && prevIndex + 1 < input.length) { - const value = input.slice(prevIndex + 1); - parts.push(value); - if (opts.tokens) { - tokens[tokens.length - 1].value = value; - depth(tokens[tokens.length - 1]); - state.maxDepth += tokens[tokens.length - 1].depth; } + return this.createMessage(content); } - state.slashes = slashes; - state.parts = parts; } - return state; + async formatMessages(values) { + return [await this.format(values)]; + } }; - module.exports = scan2; -}); - -// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/parse.js -var require_parse3 = __commonJS((exports, module) => { - var constants = require_constants2(); - var utils = require_utils2(); - var { - MAX_LENGTH, - POSIX_REGEX_SOURCE, - REGEX_NON_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_BACKREF, - REPLACEMENTS - } = constants; - var expandRange = (args, options) => { - if (typeof options.expandRange === "function") { - return options.expandRange(...args, options); + HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return HumanMessage; } - args.sort(); - const value = `[${args.join("-")}]`; - try { - new RegExp(value); - } catch (ex) { - return args.map((v) => utils.escapeRegex(v)).join(".."); + static lc_name() { + return "HumanMessagePromptTemplate"; } - return value; }; - var syntaxError = (type, char) => { - return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; - }; - var splitTopLevel = (input) => { - const parts = []; - let bracket = 0; - let paren = 0; - let quote = 0; - let value = ""; - let escaped = false; - for (const ch of input) { - if (escaped === true) { - value += ch; - escaped = false; - continue; - } - if (ch === "\\") { - value += ch; - escaped = true; - continue; - } - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - value += ch; - continue; - } - if (quote === 0) { - if (ch === "[") { - bracket++; - } else if (ch === "]" && bracket > 0) { - bracket--; - } else if (bracket === 0) { - if (ch === "(") { - paren++; - } else if (ch === ")" && paren > 0) { - paren--; - } else if (ch === "|" && paren === 0) { - parts.push(value); - value = ""; - continue; - } - } - } - value += ch; + AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return AIMessage; } - parts.push(value); - return parts; - }; - var isPlainBranch = (branch) => { - let escaped = false; - for (const ch of branch) { - if (escaped === true) { - escaped = false; - continue; - } - if (ch === "\\") { - escaped = true; - continue; - } - if (/[?*+@!()[\]{}]/.test(ch)) { - return false; - } + static lc_name() { + return "AIMessagePromptTemplate"; } - return true; }; - var normalizeSimpleBranch = (branch) => { - let value = branch.trim(); - let changed = true; - while (changed === true) { - changed = false; - if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { - value = value.slice(2, -1); - changed = true; - } + SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return SystemMessage; } - if (!isPlainBranch(value)) { - return; + static lc_name() { + return "SystemMessagePromptTemplate"; } - return value.replace(/\\(.)/g, "$1"); }; - var hasRepeatedCharPrefixOverlap = (branches) => { - const values = branches.map(normalizeSimpleBranch).filter(Boolean); - for (let i = 0;i < values.length; i++) { - for (let j = i + 1;j < values.length; j++) { - const a = values[i]; - const b = values[j]; - const char = a[0]; - if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { - continue; - } - if (a === b || a.startsWith(b) || b.startsWith(a)) { - return true; - } - } + ChatPromptTemplate = class ChatPromptTemplate2 extends BaseChatPromptTemplate { + static lc_name() { + return "ChatPromptTemplate"; } - return false; - }; - var parseRepeatedExtglob = (pattern, requireEnd = true) => { - if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") { - return; + get lc_aliases() { + return { promptMessages: "messages" }; } - let bracket = 0; - let paren = 0; - let quote = 0; - let escaped = false; - for (let i = 1;i < pattern.length; i++) { - const ch = pattern[i]; - if (escaped === true) { - escaped = false; - continue; - } - if (ch === "\\") { - escaped = true; - continue; - } - if (ch === '"') { - quote = quote === 1 ? 0 : 1; - continue; - } - if (quote === 1) { - continue; - } - if (ch === "[") { - bracket++; - continue; - } - if (ch === "]" && bracket > 0) { - bracket--; - continue; - } - if (bracket > 0) { - continue; - } - if (ch === "(") { - paren++; - continue; - } - if (ch === ")") { - paren--; - if (paren === 0) { - if (requireEnd === true && i !== pattern.length - 1) { - return; - } - return { - type: pattern[0], - body: pattern.slice(2, i), - end: i - }; + promptMessages; + validateTemplate = true; + templateFormat = "f-string"; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === undefined) + this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + const inputVariablesMessages = /* @__PURE__ */ new Set; + for (const promptMessage of this.promptMessages) { + if (promptMessage instanceof BaseMessage) + continue; + for (const inputVariable of promptMessage.inputVariables) + inputVariablesMessages.add(inputVariable); } + const totalInputVariables = this.inputVariables; + const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); + const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); + if (difference.size > 0) + throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); + const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); + if (otherDifference.size > 0) + throw new Error(`Input variables \`${[...otherDifference]}\` are used in prompt messages but not in the prompt template.`); } } - }; - var getStarExtglobSequenceOutput = (pattern) => { - let index2 = 0; - const chars = []; - while (index2 < pattern.length) { - const match2 = parseRepeatedExtglob(pattern.slice(index2), false); - if (!match2 || match2.type !== "*") { - return; - } - const branches = splitTopLevel(match2.body).map((branch2) => branch2.trim()); - if (branches.length !== 1) { - return; - } - const branch = normalizeSimpleBranch(branches[0]); - if (!branch || branch.length !== 1) { - return; - } - chars.push(branch); - index2 += match2.end + 1; + _getPromptType() { + return "chat"; } - if (chars.length < 1) { - return; + async _parseImagePrompts(message, inputValues) { + if (typeof message.content === "string") + return message; + message.content = await Promise.all(message.content.map(async (item) => { + if (item.type !== "image_url") + return item; + let imageUrl = ""; + if (typeof item.image_url === "string") + imageUrl = item.image_url; + else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") + imageUrl = item.image_url.url; + const formattedUrl = await PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }).format(inputValues); + if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) + item.image_url.url = formattedUrl; + else + item.image_url = formattedUrl; + return item; + })); + return message; } - const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`; - return `${source}*`; - }; - var repeatedExtglobRecursion = (pattern) => { - let depth = 0; - let value = pattern.trim(); - let match2 = parseRepeatedExtglob(value); - while (match2) { - depth++; - value = match2.body.trim(); - match2 = parseRepeatedExtglob(value); + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let resultMessages = []; + for (const promptMessage of this.promptMessages) + if (promptMessage instanceof BaseMessage) + resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); + else { + let inputValues; + if (this.templateFormat === "mustache") + inputValues = { ...allValues }; + else + inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { + if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) + throw addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); + acc[inputVariable] = allValues[inputVariable]; + return acc; + }, {}); + const message = await promptMessage.formatMessages(inputValues); + resultMessages = resultMessages.concat(message); + } + return resultMessages; } - return depth; - }; - var analyzeRepeatedExtglob = (body, options) => { - if (options.maxExtglobRecursion === false) { - return { risky: false }; + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new ChatPromptTemplate2({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); } - const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION; - const branches = splitTopLevel(body).map((branch) => branch.trim()); - if (branches.length > 1) { - if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) { - return { risky: true }; - } + static fromTemplate(template, options) { + const humanTemplate = new HumanMessagePromptTemplate({ prompt: PromptTemplate.fromTemplate(template, options) }); + return this.fromMessages([humanTemplate]); } - for (const branch of branches) { - const safeOutput = getStarExtglobSequenceOutput(branch); - if (safeOutput) { - return { risky: true, safeOutput }; - } - if (repeatedExtglobRecursion(branch) > max) { - return { risky: true }; + static fromMessages(promptMessages, extra) { + const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate2 ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); + const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate2 ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); + const inputVariables = /* @__PURE__ */ new Set; + for (const promptMessage of flattenedMessages) { + if (promptMessage instanceof BaseMessage) + continue; + for (const inputVariable of promptMessage.inputVariables) { + if (inputVariable in flattenedPartialVariables) + continue; + inputVariables.add(inputVariable); + } } + return new this({ + ...extra, + inputVariables: [...inputVariables], + promptMessages: flattenedMessages, + partialVariables: flattenedPartialVariables, + templateFormat: extra?.templateFormat + }); } - return { risky: false }; }; - var parse11 = (input, options) => { - if (typeof input !== "string") { - throw new TypeError("Expected a string"); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/few_shot.js +var FewShotPromptTemplate, FewShotChatMessagePromptTemplate; +var init_few_shot = __esm(() => { + init_string3(); + init_template(); + init_prompt(); + init_chat2(); + FewShotPromptTemplate = class FewShotPromptTemplate2 extends BaseStringPromptTemplate { + lc_serializable = false; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = ` + +`; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + constructor(input) { + super(input); + Object.assign(this, input); + if (this.examples !== undefined && this.exampleSelector !== undefined) + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + if (this.examples === undefined && this.exampleSelector === undefined) + throw new Error("One of 'examples' and 'example_selector' should be provided"); + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } } - input = REPLACEMENTS[input] || input; - const opts = { ...options }; - const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - let len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + _getPromptType() { + return "few_shot"; } - const bos = { type: "bos", value: "", output: opts.prepend || "" }; - const tokens = [bos]; - const capture = opts.capture ? "" : "?:"; - const win32 = utils.isWindows(options); - const PLATFORM_CHARS = constants.globChars(win32); - const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); - const { - DOT_LITERAL, - PLUS_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK, - QMARK_NO_DOT, - STAR, - START_ANCHOR - } = PLATFORM_CHARS; - const globstar = (opts2) => { - return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - const nodot = opts.dot ? "" : NO_DOT; - const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; - let star = opts.bash === true ? globstar(opts) : STAR; - if (opts.capture) { - star = `(${star})`; + static lc_name() { + return "FewShotPromptTemplate"; } - if (typeof opts.noext === "boolean") { - opts.noextglob = opts.noext; + async getExamples(inputVariables) { + if (this.examples !== undefined) + return this.examples; + if (this.exampleSelector !== undefined) + return this.exampleSelector.selectExamples(inputVariables); + throw new Error("One of 'examples' and 'example_selector' should be provided"); } - const state = { - input, - index: -1, - start: 0, - dot: opts.dot === true, - consumed: "", - output: "", - prefix: "", - backtrack: false, - negated: false, - brackets: 0, - braces: 0, - parens: 0, - quotes: 0, - globstar: false, - tokens - }; - input = utils.removePrefix(input, state); - len = input.length; - const extglobs = []; - const braces = []; - const stack = []; - let prev = bos; - let value; - const eos2 = () => state.index === len - 1; - const peek = state.peek = (n3 = 1) => input[state.index + n3]; - const advance = state.advance = () => input[++state.index] || ""; - const remaining = () => input.slice(state.index + 1); - const consume = (value2 = "", num = 0) => { - state.consumed += value2; - state.index += num; - }; - const append = (token) => { - state.output += token.output != null ? token.output : token.value; - consume(token.value); - }; - const negate = () => { - let count = 1; - while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { - advance(); - state.start++; - count++; - } - if (count % 2 === 0) { - return false; - } - state.negated = true; - state.start++; - return true; - }; - const increment2 = (type) => { - state[type]++; - stack.push(type); - }; - const decrement = (type) => { - state[type]--; - stack.pop(); - }; - const push2 = (tok) => { - if (prev.type === "globstar") { - const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); - const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); - if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { - state.output = state.output.slice(0, -prev.output.length); - prev.type = "star"; - prev.value = "*"; - prev.output = star; - state.output += prev.output; - } - } - if (extglobs.length && tok.type !== "paren") { - extglobs[extglobs.length - 1].inner += tok.value; - } - if (tok.value || tok.output) - append(tok); - if (prev && prev.type === "text" && tok.type === "text") { - prev.value += tok.value; - prev.output = (prev.output || "") + tok.value; - return; - } - tok.prev = prev; - tokens.push(tok); - prev = tok; - }; - const extglobOpen = (type, value2) => { - const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" }; - token.prev = prev; - token.parens = state.parens; - token.output = state.output; - token.startIndex = state.index; - token.tokensIndex = tokens.length; - const output = (opts.capture ? "(" : "") + token.open; - increment2("parens"); - push2({ type, value: value2, output: state.output ? "" : ONE_CHAR }); - push2({ type: "paren", extglob: true, value: advance(), output }); - extglobs.push(token); - }; - const extglobClose = (token) => { - const literal2 = input.slice(token.startIndex, state.index + 1); - const body = input.slice(token.startIndex + 2, state.index); - const analysis = analyzeRepeatedExtglob(body, opts); - if ((token.type === "plus" || token.type === "star") && analysis.risky) { - const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : undefined; - const open = tokens[token.tokensIndex]; - open.type = "text"; - open.value = literal2; - open.output = safeOutput || utils.escapeRegex(literal2); - for (let i = token.tokensIndex + 1;i < tokens.length; i++) { - tokens[i].value = ""; - tokens[i].output = ""; - delete tokens[i].suffix; - } - state.output = token.output + open.output; - state.backtrack = true; - push2({ type: "paren", extglob: true, value, output: "" }); - decrement("parens"); - return; - } - let output = token.close + (opts.capture ? ")" : ""); - let rest; - if (token.type === "negate") { - let extglobStar = star; - if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { - extglobStar = globstar(opts); - } - if (extglobStar !== star || eos2() || /^\)+$/.test(remaining())) { - output = token.close = `)$))${extglobStar}`; - } - if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { - const expression = parse11(rest, { ...options, fastpaths: false }).output; - output = token.close = `)${expression})${extglobStar})`; - } - if (token.prev.type === "bos") { - state.negatedExtglob = true; - } - } - push2({ type: "paren", extglob: true, value, output }); - decrement("parens"); - }; - if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { - let backslashes = false; - let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc2, chars, first, rest, index2) => { - if (first === "\\") { - backslashes = true; - return m; - } - if (first === "?") { - if (esc2) { - return esc2 + first + (rest ? QMARK.repeat(rest.length) : ""); - } - if (index2 === 0) { - return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); - } - return QMARK.repeat(chars.length); - } - if (first === ".") { - return DOT_LITERAL.repeat(chars.length); - } - if (first === "*") { - if (esc2) { - return esc2 + first + (rest ? star : ""); - } - return star; - } - return esc2 ? m : `\\${m}`; + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new FewShotPromptTemplate2({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables }); - if (backslashes === true) { - if (opts.unescape === true) { - output = output.replace(/\\/g, ""); - } else { - output = output.replace(/\\+/g, (m) => { - return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; - }); - } - } - if (output === input && opts.contains === true) { - state.output = input; - return state; - } - state.output = utils.wrapOutput(output, state, options); - return state; } - while (!eos2()) { - value = advance(); - if (value === "\x00") { - continue; - } - if (value === "\\") { - const next = peek(); - if (next === "/" && opts.bash !== true) { - continue; - } - if (next === "." || next === ";") { - continue; - } - if (!next) { - value += "\\"; - push2({ type: "text", value }); - continue; - } - const match2 = /^\\+/.exec(remaining()); - let slashes = 0; - if (match2 && match2[0].length > 2) { - slashes = match2[0].length; - state.index += slashes; - if (slashes % 2 !== 0) { - value += "\\"; - } - } - if (opts.unescape === true) { - value = advance(); - } else { - value += advance(); - } - if (state.brackets === 0) { - push2({ type: "text", value }); - continue; - } - } - if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { - if (opts.posix !== false && value === ":") { - const inner = prev.value.slice(1); - if (inner.includes("[")) { - prev.posix = true; - if (inner.includes(":")) { - const idx = prev.value.lastIndexOf("["); - const pre = prev.value.slice(0, idx); - const rest2 = prev.value.slice(idx + 2); - const posix = POSIX_REGEX_SOURCE[rest2]; - if (posix) { - prev.value = pre + posix; - state.backtrack = true; - advance(); - if (!bos.output && tokens.indexOf(prev) === 1) { - bos.output = ONE_CHAR; - } - continue; - } - } - } - } - if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") { - value = `\\${value}`; - } - if (value === "]" && (prev.value === "[" || prev.value === "[^")) { - value = `\\${value}`; - } - if (opts.posix === true && value === "!" && prev.value === "[") { - value = "^"; - } - prev.value += value; - append({ value }); - continue; - } - if (state.quotes === 1 && value !== '"') { - value = utils.escapeRegex(value); - prev.value += value; - append({ value }); - continue; - } - if (value === '"') { - state.quotes = state.quotes === 1 ? 0 : 1; - if (opts.keepQuotes === true) { - push2({ type: "text", value }); - } - continue; - } - if (value === "(") { - increment2("parens"); - push2({ type: "paren", value }); - continue; - } - if (value === ")") { - if (state.parens === 0 && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError("opening", "(")); - } - const extglob = extglobs[extglobs.length - 1]; - if (extglob && state.parens === extglob.parens + 1) { - extglobClose(extglobs.pop()); - continue; - } - push2({ type: "paren", value, output: state.parens ? ")" : "\\)" }); - decrement("parens"); - continue; - } - if (value === "[") { - if (opts.nobracket === true || !remaining().includes("]")) { - if (opts.nobracket !== true && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError("closing", "]")); - } - value = `\\${value}`; - } else { - increment2("brackets"); - } - push2({ type: "bracket", value }); - continue; - } - if (value === "]") { - if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { - push2({ type: "text", value, output: `\\${value}` }); - continue; - } - if (state.brackets === 0) { - if (opts.strictBrackets === true) { - throw new SyntaxError(syntaxError("opening", "[")); - } - push2({ type: "text", value, output: `\\${value}` }); - continue; - } - decrement("brackets"); - const prevValue = prev.value.slice(1); - if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { - value = `/${value}`; - } - prev.value += value; - append({ value }); - if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { - continue; - } - const escaped = utils.escapeRegex(prev.value); - state.output = state.output.slice(0, -prev.value.length); - if (opts.literalBrackets === true) { - state.output += escaped; - prev.value = escaped; - continue; - } - prev.value = `(${capture}${escaped}|${prev.value})`; - state.output += prev.value; - continue; - } - if (value === "{" && opts.nobrace !== true) { - increment2("braces"); - const open = { - type: "brace", - value, - output: "(", - outputIndex: state.output.length, - tokensIndex: state.tokens.length - }; - braces.push(open); - push2(open); - continue; - } - if (value === "}") { - const brace = braces[braces.length - 1]; - if (opts.nobrace === true || !brace) { - push2({ type: "text", value, output: value }); - continue; - } - let output = ")"; - if (brace.dots === true) { - const arr3 = tokens.slice(); - const range = []; - for (let i = arr3.length - 1;i >= 0; i--) { - tokens.pop(); - if (arr3[i].type === "brace") { - break; - } - if (arr3[i].type !== "dots") { - range.unshift(arr3[i].value); - } - } - output = expandRange(range, opts); - state.backtrack = true; - } - if (brace.comma !== true && brace.dots !== true) { - const out = state.output.slice(0, brace.outputIndex); - const toks = state.tokens.slice(brace.tokensIndex); - brace.value = brace.output = "\\{"; - value = output = "\\}"; - state.output = out; - for (const t of toks) { - state.output += t.output || t.value; - } - } - push2({ type: "brace", value, output }); - decrement("braces"); - braces.pop(); - continue; - } - if (value === "|") { - if (extglobs.length > 0) { - extglobs[extglobs.length - 1].conditions++; - } - push2({ type: "text", value }); - continue; - } - if (value === ",") { - let output = value; - const brace = braces[braces.length - 1]; - if (brace && stack[stack.length - 1] === "braces") { - brace.comma = true; - output = "|"; - } - push2({ type: "comma", value, output }); - continue; - } - if (value === "/") { - if (prev.type === "dot" && state.index === state.start + 1) { - state.start = state.index + 1; - state.consumed = ""; - state.output = ""; - tokens.pop(); - prev = bos; - continue; - } - push2({ type: "slash", value, output: SLASH_LITERAL }); - continue; - } - if (value === ".") { - if (state.braces > 0 && prev.type === "dot") { - if (prev.value === ".") - prev.output = DOT_LITERAL; - const brace = braces[braces.length - 1]; - prev.type = "dots"; - prev.output += value; - prev.value += value; - brace.dots = true; - continue; - } - if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { - push2({ type: "text", value, output: DOT_LITERAL }); - continue; - } - push2({ type: "dot", value, output: DOT_LITERAL }); - continue; - } - if (value === "?") { - const isGroup = prev && prev.value === "("; - if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { - extglobOpen("qmark", value); - continue; - } - if (prev && prev.type === "paren") { - const next = peek(); - let output = value; - if (next === "<" && !utils.supportsLookbehinds()) { - throw new Error("Node.js v10 or higher is required for regex lookbehinds"); - } - if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { - output = `\\${value}`; - } - push2({ type: "text", value, output }); - continue; - } - if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { - push2({ type: "qmark", value, output: QMARK_NO_DOT }); - continue; - } - push2({ type: "qmark", value, output: QMARK }); - continue; - } - if (value === "!") { - if (opts.noextglob !== true && peek() === "(") { - if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { - extglobOpen("negate", value); - continue; - } - } - if (opts.nonegate !== true && state.index === 0) { - negate(); - continue; - } - } - if (value === "+") { - if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { - extglobOpen("plus", value); - continue; - } - if (prev && prev.value === "(" || opts.regex === false) { - push2({ type: "plus", value, output: PLUS_LITERAL }); - continue; - } - if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { - push2({ type: "plus", value }); - continue; - } - push2({ type: "plus", value: PLUS_LITERAL }); - continue; - } - if (value === "@") { - if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { - push2({ type: "at", extglob: true, value, output: "" }); - continue; - } - push2({ type: "text", value }); - continue; - } - if (value !== "*") { - if (value === "$" || value === "^") { - value = `\\${value}`; - } - const match2 = REGEX_NON_SPECIAL_CHARS.exec(remaining()); - if (match2) { - value += match2[0]; - state.index += match2[0].length; - } - push2({ type: "text", value }); - continue; - } - if (prev && (prev.type === "globstar" || prev.star === true)) { - prev.type = "star"; - prev.star = true; - prev.value += value; - prev.output = star; - state.backtrack = true; - state.globstar = true; - consume(value); - continue; - } - let rest = remaining(); - if (opts.noextglob !== true && /^\([^?]/.test(rest)) { - extglobOpen("star", value); - continue; - } - if (prev.type === "star") { - if (opts.noglobstar === true) { - consume(value); - continue; - } - const prior = prev.prev; - const before = prior.prev; - const isStart = prior.type === "slash" || prior.type === "bos"; - const afterStar = before && (before.type === "star" || before.type === "globstar"); - if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { - push2({ type: "star", value, output: "" }); - continue; - } - const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); - const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); - if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { - push2({ type: "star", value, output: "" }); - continue; - } - while (rest.slice(0, 3) === "/**") { - const after = input[state.index + 4]; - if (after && after !== "/") { - break; - } - rest = rest.slice(3); - consume("/**", 3); - } - if (prior.type === "bos" && eos2()) { - prev.type = "globstar"; - prev.value += value; - prev.output = globstar(opts); - state.output = prev.output; - state.globstar = true; - consume(value); - continue; - } - if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos2()) { - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; - prev.type = "globstar"; - prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); - prev.value += value; - state.globstar = true; - state.output += prior.output + prev.output; - consume(value); - continue; - } - if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { - const end = rest[1] !== undefined ? "|$" : ""; - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; - prev.type = "globstar"; - prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; - prev.value += value; - state.output += prior.output + prev.output; - state.globstar = true; - consume(value + advance()); - push2({ type: "slash", value: "/", output: "" }); - continue; - } - if (prior.type === "bos" && rest[0] === "/") { - prev.type = "globstar"; - prev.value += value; - prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; - state.output = prev.output; - state.globstar = true; - consume(value + advance()); - push2({ type: "slash", value: "/", output: "" }); - continue; - } - state.output = state.output.slice(0, -prev.output.length); - prev.type = "globstar"; - prev.output = globstar(opts); - prev.value += value; - state.output += prev.output; - state.globstar = true; - consume(value); - continue; - } - const token = { type: "star", value, output: star }; - if (opts.bash === true) { - token.output = ".*?"; - if (prev.type === "bos" || prev.type === "slash") { - token.output = nodot + token.output; - } - push2(token); - continue; - } - if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { - token.output = value; - push2(token); - continue; - } - if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { - if (prev.type === "dot") { - state.output += NO_DOT_SLASH; - prev.output += NO_DOT_SLASH; - } else if (opts.dot === true) { - state.output += NO_DOTS_SLASH; - prev.output += NO_DOTS_SLASH; - } else { - state.output += nodot; - prev.output += nodot; - } - if (peek() !== "*") { - state.output += ONE_CHAR; - prev.output += ONE_CHAR; - } - } - push2(token); + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + return renderTemplate([ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator), this.templateFormat, allValues); } - while (state.brackets > 0) { - if (opts.strictBrackets === true) - throw new SyntaxError(syntaxError("closing", "]")); - state.output = utils.escapeLast(state.output, "["); - decrement("brackets"); + serialize() { + if (this.exampleSelector || !this.examples) + throw new Error("Serializing an example selector is not currently supported"); + if (this.outputParser !== undefined) + throw new Error("Serializing an output parser is not currently supported"); + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples + }; } - while (state.parens > 0) { - if (opts.strictBrackets === true) - throw new SyntaxError(syntaxError("closing", ")")); - state.output = utils.escapeLast(state.output, "("); - decrement("parens"); + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) + throw new Error("Missing example prompt"); + const examplePrompt = await PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) + examples = data.examples; + else + throw new Error("Invalid examples format. Only list or string are supported."); + return new FewShotPromptTemplate2({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format + }); } - while (state.braces > 0) { - if (opts.strictBrackets === true) - throw new SyntaxError(syntaxError("closing", "}")); - state.output = utils.escapeLast(state.output, "{"); - decrement("braces"); + }; + FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate2 extends BaseChatPromptTemplate { + lc_serializable = true; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = ` + +`; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + _getPromptType() { + return "few_shot_chat"; } - if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { - push2({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` }); + static lc_name() { + return "FewShotChatMessagePromptTemplate"; } - if (state.backtrack === true) { - state.output = ""; - for (const token of state.tokens) { - state.output += token.output != null ? token.output : token.value; - if (token.suffix) { - state.output += token.suffix; - } + constructor(fields) { + super(fields); + this.examples = fields.examples; + this.examplePrompt = fields.examplePrompt; + this.exampleSeparator = fields.exampleSeparator ?? ` + +`; + this.exampleSelector = fields.exampleSelector; + this.prefix = fields.prefix ?? ""; + this.suffix = fields.suffix ?? ""; + this.templateFormat = fields.templateFormat ?? "f-string"; + this.validateTemplate = fields.validateTemplate ?? true; + if (this.examples !== undefined && this.exampleSelector !== undefined) + throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + if (this.examples === undefined && this.exampleSelector === undefined) + throw new Error("One of 'examples' and 'example_selector' should be provided"); + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) + totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); } } - return state; - }; - parse11.fastpaths = (input, options) => { - const opts = { ...options }; - const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - const len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); - } - input = REPLACEMENTS[input] || input; - const win32 = utils.isWindows(options); - const { - DOT_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOTS_SLASH, - STAR, - START_ANCHOR - } = constants.globChars(win32); - const nodot = opts.dot ? NO_DOTS : NO_DOT; - const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; - const capture = opts.capture ? "" : "?:"; - const state = { negated: false, prefix: "" }; - let star = opts.bash === true ? ".*?" : STAR; - if (opts.capture) { - star = `(${star})`; + async getExamples(inputVariables) { + if (this.examples !== undefined) + return this.examples; + if (this.exampleSelector !== undefined) + return this.exampleSelector.selectExamples(inputVariables); + throw new Error("One of 'examples' and 'example_selector' should be provided"); } - const globstar = (opts2) => { - if (opts2.noglobstar === true) - return star; - return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - const create = (str) => { - switch (str) { - case "*": - return `${nodot}${ONE_CHAR}${star}`; - case ".*": - return `${DOT_LITERAL}${ONE_CHAR}${star}`; - case "*.*": - return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - case "*/*": - return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; - case "**": - return nodot + globstar(opts); - case "**/*": - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - case "**/*.*": - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - case "**/.*": - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - default: { - const match2 = /^(.*?)\.(\w+)$/.exec(str); - if (!match2) - return; - const source2 = create(match2[1]); - if (!source2) - return; - return source2 + DOT_LITERAL + match2[2]; - } + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let examples = await this.getExamples(allValues); + examples = examples.map((example) => { + const result = {}; + this.examplePrompt.inputVariables.forEach((inputVariable) => { + result[inputVariable] = example[inputVariable]; + }); + return result; + }); + const messages = []; + for (const example of examples) { + const exampleMessages = await this.examplePrompt.formatMessages(example); + messages.push(...exampleMessages); } - }; - const output = utils.removePrefix(input, state); - let source = create(output); - if (source && opts.strictSlashes !== true) { - source += `${SLASH_LITERAL}?`; + return messages; + } + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = (await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example)))).flat().map((message) => message.content); + return renderTemplate([ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator), this.templateFormat, allValues); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new FewShotChatMessagePromptTemplate2({ + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }); } - return source; }; - module.exports = parse11; }); -// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/picomatch.js -var require_picomatch = __commonJS((exports, module) => { - var path2 = __require("path"); - var scan2 = require_scan(); - var parse11 = require_parse3(); - var utils = require_utils2(); - var constants = require_constants2(); - var isObject3 = (val) => val && typeof val === "object" && !Array.isArray(val); - var picomatch = (glob, options, returnState = false) => { - if (Array.isArray(glob)) { - const fns = glob.map((input) => picomatch(input, options, returnState)); - const arrayMatcher = (str) => { - for (const isMatch of fns) { - const state2 = isMatch(str); - if (state2) - return state2; - } - return false; - }; - return arrayMatcher; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/pipeline.js +var PipelinePromptTemplate; +var init_pipeline2 = __esm(() => { + init_base10(); + init_chat2(); + PipelinePromptTemplate = class PipelinePromptTemplate2 extends BasePromptTemplate { + static lc_name() { + return "PipelinePromptTemplate"; } - const isState = isObject3(glob) && glob.tokens && glob.input; - if (glob === "" || typeof glob !== "string" && !isState) { - throw new TypeError("Expected pattern to be a non-empty string"); + pipelinePrompts; + finalPrompt; + constructor(input) { + super({ + ...input, + inputVariables: [] + }); + this.pipelinePrompts = input.pipelinePrompts; + this.finalPrompt = input.finalPrompt; + this.inputVariables = this.computeInputValues(); } - const opts = options || {}; - const posix = utils.isWindows(options); - const regex2 = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); - const state = regex2.state; - delete regex2.state; - let isIgnored = () => false; - if (opts.ignore) { - const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; - isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + computeInputValues() { + const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); + const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); + return [...new Set(inputValues)]; } - const matcher = (input, returnObject = false) => { - const { isMatch, match: match2, output } = picomatch.test(input, regex2, options, { glob, posix }); - const result = { glob, state, regex: regex2, posix, input, output, match: match2, isMatch }; - if (typeof opts.onResult === "function") { - opts.onResult(result); - } - if (isMatch === false) { - result.isMatch = false; - return returnObject ? result : false; - } - if (isIgnored(input)) { - if (typeof opts.onIgnore === "function") { - opts.onIgnore(result); - } - result.isMatch = false; - return returnObject ? result : false; - } - if (typeof opts.onMatch === "function") { - opts.onMatch(result); - } - return returnObject ? result : true; - }; - if (returnState) { - matcher.state = state; - } - return matcher; - }; - picomatch.test = (input, regex2, options, { glob, posix } = {}) => { - if (typeof input !== "string") { - throw new TypeError("Expected input to be a string"); + static extractRequiredInputValues(allValues, requiredValueNames) { + return requiredValueNames.reduce((requiredValues, valueName) => { + requiredValues[valueName] = allValues[valueName]; + return requiredValues; + }, {}); } - if (input === "") { - return { isMatch: false, output: "" }; + async formatPipelinePrompts(values) { + const allValues = await this.mergePartialAndUserVariables(values); + for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { + const pipelinePromptInputValues = PipelinePromptTemplate2.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); + if (pipelinePrompt instanceof ChatPromptTemplate) + allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); + else + allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); + } + return PipelinePromptTemplate2.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); } - const opts = options || {}; - const format3 = opts.format || (posix ? utils.toPosixSlashes : null); - let match2 = input === glob; - let output = match2 && format3 ? format3(input) : input; - if (match2 === false) { - output = format3 ? format3(input) : input; - match2 = output === glob; + async formatPromptValue(values) { + return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); } - if (match2 === false || opts.capture === true) { - if (opts.matchBase === true || opts.basename === true) { - match2 = picomatch.matchBase(input, regex2, options, posix); - } else { - match2 = regex2.exec(output); - } + async format(values) { + return this.finalPrompt.format(await this.formatPipelinePrompts(values)); } - return { isMatch: Boolean(match2), match: match2, output }; - }; - picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { - const regex2 = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); - return regex2.test(path2.basename(input)); - }; - picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); - picomatch.parse = (pattern, options) => { - if (Array.isArray(pattern)) - return pattern.map((p) => picomatch.parse(p, options)); - return parse11(pattern, { ...options, fastpaths: false }); - }; - picomatch.scan = (input, options) => scan2(input, options); - picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { - if (returnOutput === true) { - return state.output; + async partial(values) { + const promptDict = { ...this }; + promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); + promptDict.partialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new PipelinePromptTemplate2(promptDict); } - const opts = options || {}; - const prepend = opts.contains ? "" : "^"; - const append = opts.contains ? "" : "$"; - let source = `${prepend}(?:${state.output})${append}`; - if (state && state.negated === true) { - source = `^(?!${source}).*$`; + serialize() { + throw new Error("Not implemented."); } - const regex2 = picomatch.toRegex(source, options); - if (returnState === true) { - regex2.state = state; + _getPromptType() { + return "pipeline"; } - return regex2; }; - picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { - if (!input || typeof input !== "string") { - throw new TypeError("Expected a non-empty string"); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/structured.js +function isWithStructuredOutput(x) { + return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; +} +function isRunnableBinding(x) { + return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; +} +var StructuredPrompt; +var init_structured2 = __esm(() => { + init_base4(); + init_chat2(); + StructuredPrompt = class StructuredPrompt2 extends ChatPromptTemplate { + schema; + method; + lc_namespace = [ + "langchain_core", + "prompts", + "structured" + ]; + get lc_aliases() { + return { + ...super.lc_aliases, + schema: "schema_" + }; } - let parsed = { negated: false, fastpaths: true }; - if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) { - parsed.output = parse11.fastpaths(input, options); + constructor(input) { + super(input); + this.schema = input.schema; + this.method = input.method; } - if (!parsed.output) { - parsed = parse11(input, options); + pipe(coerceable) { + if (isWithStructuredOutput(coerceable)) + return super.pipe(coerceable.withStructuredOutput(this.schema)); + if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) + return super.pipe(new RunnableBinding({ + bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), + kwargs: coerceable.kwargs ?? {}, + config: coerceable.config, + configFactories: coerceable.configFactories + })); + throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); } - return picomatch.compileRe(parsed, options, returnOutput, returnState); - }; - picomatch.toRegex = (source, options) => { - try { - const opts = options || {}; - return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); - } catch (err) { - if (options && options.debug === true) - throw err; - return /$^/; + static fromMessagesAndSchema(promptMessages, schema, method) { + return StructuredPrompt2.fromMessages(promptMessages, { + schema, + method + }); } }; - picomatch.constants = constants; - module.exports = picomatch; }); -// ../../node_modules/.pnpm/micromatch@4.0.8/node_modules/micromatch/index.js -var require_micromatch = __commonJS((exports, module) => { - var util3 = __require("util"); - var braces = require_braces(); - var picomatch = require_picomatch(); - var utils = require_utils2(); - var isEmptyString = (v) => v === "" || v === "./"; - var hasBraces = (v) => { - const index2 = v.indexOf("{"); - return index2 > -1 && v.indexOf("}", index2) > -1; - }; - var micromatch = (list, patterns, options) => { - patterns = [].concat(patterns); - list = [].concat(list); - let omit2 = new Set; - let keep = new Set; - let items = new Set; - let negatives = 0; - let onResult = (state) => { - items.add(state.output); - if (options && options.onResult) { - options.onResult(state); - } - }; - for (let i = 0;i < patterns.length; i++) { - let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); - let negated = isMatch.state.negated || isMatch.state.negatedExtglob; - if (negated) - negatives++; - for (let item of list) { - let matched = isMatch(item, true); - let match2 = negated ? !matched.isMatch : matched.isMatch; - if (!match2) - continue; - if (negated) { - omit2.add(matched.output); - } else { - omit2.delete(matched.output); - keep.add(matched.output); - } - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/prompts/index.js +var prompts_exports; +var init_prompts2 = __esm(() => { + init_runtime2(); + init_base10(); + init_string3(); + init_template(); + init_prompt(); + init_image(); + init_dict(); + init_chat2(); + init_few_shot(); + init_pipeline2(); + init_structured2(); + prompts_exports = /* @__PURE__ */ __exportAll({ + AIMessagePromptTemplate: () => AIMessagePromptTemplate, + BaseChatPromptTemplate: () => BaseChatPromptTemplate, + BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, + BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, + BasePromptTemplate: () => BasePromptTemplate, + BaseStringPromptTemplate: () => BaseStringPromptTemplate, + ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, + ChatPromptTemplate: () => ChatPromptTemplate, + DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, + DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, + DictPromptTemplate: () => DictPromptTemplate, + FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, + FewShotPromptTemplate: () => FewShotPromptTemplate, + HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, + ImagePromptTemplate: () => ImagePromptTemplate, + MessagesPlaceholder: () => MessagesPlaceholder, + PipelinePromptTemplate: () => PipelinePromptTemplate, + PromptTemplate: () => PromptTemplate, + StructuredPrompt: () => StructuredPrompt, + SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, + checkValidTemplate: () => checkValidTemplate, + interpolateFString: () => interpolateFString, + interpolateMustache: () => interpolateMustache, + parseFString: () => parseFString, + parseMustache: () => parseMustache, + parseTemplate: () => parseTemplate2, + renderTemplate: () => renderTemplate + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/retrievers/document_compressors/index.js +var document_compressors_exports, BaseDocumentCompressor = class { + static isBaseDocumentCompressor(x) { + return x?.compressDocuments !== undefined; + } +}; +var init_document_compressors = __esm(() => { + init_runtime2(); + document_compressors_exports = /* @__PURE__ */ __exportAll({ BaseDocumentCompressor: () => BaseDocumentCompressor }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/retrievers/index.js +var retrievers_exports, BaseRetriever; +var init_retrievers = __esm(() => { + init_runtime2(); + init_manager(); + init_config(); + init_base4(); + retrievers_exports = /* @__PURE__ */ __exportAll({ BaseRetriever: () => BaseRetriever }); + BaseRetriever = class extends Runnable { + callbacks; + tags; + metadata; + verbose; + constructor(fields) { + super(fields); + this.callbacks = fields?.callbacks; + this.tags = fields?.tags ?? []; + this.metadata = fields?.metadata ?? {}; + this.verbose = fields?.verbose ?? false; } - let result = negatives === patterns.length ? [...items] : [...keep]; - let matches = result.filter((item) => !omit2.has(item)); - if (options && matches.length === 0) { - if (options.failglob === true) { - throw new Error(`No matches found for "${patterns.join(", ")}"`); - } - if (options.nonull === true || options.nullglob === true) { - return options.unescape ? patterns.map((p) => p.replace(/\\/g, "")) : patterns; - } + _getRelevantDocuments(_query, _callbacks) { + throw new Error("Not implemented!"); } - return matches; - }; - micromatch.match = micromatch; - micromatch.matcher = (pattern, options) => picomatch(pattern, options); - micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); - micromatch.any = micromatch.isMatch; - micromatch.not = (list, patterns, options = {}) => { - patterns = [].concat(patterns).map(String); - let result = new Set; - let items = []; - let onResult = (state) => { - if (options.onResult) - options.onResult(state); - items.push(state.output); - }; - let matches = new Set(micromatch(list, patterns, { ...options, onResult })); - for (let item of items) { - if (!matches.has(item)) { - result.add(item); + async invoke(input, options) { + const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); + const runManager = await (await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }))?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, undefined, undefined, undefined, parsedConfig.runName); + try { + const results = await this._getRelevantDocuments(input, runManager); + await runManager?.handleRetrieverEnd(results); + return results; + } catch (error90) { + await runManager?.handleRetrieverError(error90); + throw error90; } } - return [...result]; }; - micromatch.contains = (str, pattern, options) => { - if (typeof str !== "string") { - throw new TypeError(`Expected a string: "${util3.inspect(str)}"`); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/stores.js +var stores_exports, BaseStore, InMemoryStore; +var init_stores = __esm(() => { + init_runtime2(); + init_serializable(); + stores_exports = /* @__PURE__ */ __exportAll({ + BaseStore: () => BaseStore, + InMemoryStore: () => InMemoryStore + }); + BaseStore = class extends Serializable { + }; + InMemoryStore = class extends BaseStore { + lc_namespace = ["langchain", "storage"]; + store = {}; + async mget(keys) { + return keys.map((key) => this.store[key]); } - if (Array.isArray(pattern)) { - return pattern.some((p) => micromatch.contains(str, p, options)); + async mset(keyValuePairs) { + for (const [key, value] of keyValuePairs) + this.store[key] = value; } - if (typeof pattern === "string") { - if (isEmptyString(str) || isEmptyString(pattern)) { - return false; - } - if (str.includes(pattern) || str.startsWith("./") && str.slice(2).includes(pattern)) { - return true; - } + async mdelete(keys) { + for (const key of keys) + delete this.store[key]; } - return micromatch.isMatch(str, pattern, { ...options, contains: true }); - }; - micromatch.matchKeys = (obj, patterns, options) => { - if (!utils.isObject(obj)) { - throw new TypeError("Expected the first argument to be an object"); + async* yieldKeys(prefix) { + const keys = Object.keys(this.store); + for (const key of keys) + if (prefix === undefined || key.startsWith(prefix)) + yield key; } - let keys = micromatch(Object.keys(obj), patterns, options); - let res = {}; - for (let key of keys) - res[key] = obj[key]; - return res; }; - micromatch.some = (list, patterns, options) => { - let items = [].concat(list); - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch(String(pattern), options); - if (items.some((item) => isMatch(item))) { - return true; - } - } - return false; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/structured_query/ir.js +var Operators, Comparators, Visitor = class { +}, Expression = class { + accept(visitor) { + if (this.exprName === "Operation") + return visitor.visitOperation(this); + else if (this.exprName === "Comparison") + return visitor.visitComparison(this); + else if (this.exprName === "StructuredQuery") + return visitor.visitStructuredQuery(this); + else + throw new Error("Unknown Expression type"); + } +}, FilterDirective, Comparison, Operation, StructuredQuery; +var init_ir = __esm(() => { + Operators = { + and: "and", + or: "or", + not: "not" }; - micromatch.every = (list, patterns, options) => { - let items = [].concat(list); - for (let pattern of [].concat(patterns)) { - let isMatch = picomatch(String(pattern), options); - if (!items.every((item) => isMatch(item))) { - return false; - } - } - return true; + Comparators = { + eq: "eq", + ne: "ne", + lt: "lt", + gt: "gt", + lte: "lte", + gte: "gte" }; - micromatch.all = (str, patterns, options) => { - if (typeof str !== "string") { - throw new TypeError(`Expected a string: "${util3.inspect(str)}"`); - } - return [].concat(patterns).every((p) => picomatch(p, options)(str)); + FilterDirective = class extends Expression { }; - micromatch.capture = (glob, input, options) => { - let posix = utils.isWindows(options); - let regex2 = picomatch.makeRe(String(glob), { ...options, capture: true }); - let match2 = regex2.exec(posix ? utils.toPosixSlashes(input) : input); - if (match2) { - return match2.slice(1).map((v) => v === undefined ? "" : v); + Comparison = class extends FilterDirective { + exprName = "Comparison"; + constructor(comparator, attribute, value) { + super(); + this.comparator = comparator; + this.attribute = attribute; + this.value = value; } }; - micromatch.makeRe = (...args) => picomatch.makeRe(...args); - micromatch.scan = (...args) => picomatch.scan(...args); - micromatch.parse = (patterns, options) => { - let res = []; - for (let pattern of [].concat(patterns || [])) { - for (let str of braces(String(pattern), options)) { - res.push(picomatch.parse(str, options)); - } + Operation = class extends FilterDirective { + exprName = "Operation"; + constructor(operator, args) { + super(); + this.operator = operator; + this.args = args; } - return res; }; - micromatch.braces = (pattern, options) => { - if (typeof pattern !== "string") - throw new TypeError("Expected a string"); - if (options && options.nobrace === true || !hasBraces(pattern)) { - return [pattern]; + StructuredQuery = class extends Expression { + exprName = "StructuredQuery"; + constructor(query3, filter) { + super(); + this.query = query3; + this.filter = filter; } - return braces(pattern, options); - }; - micromatch.braceExpand = (pattern, options) => { - if (typeof pattern !== "string") - throw new TypeError("Expected a string"); - return micromatch.braces(pattern, { ...options, expand: true }); }; - micromatch.hasBraces = hasBraces; - module.exports = micromatch; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/identity.js -var require_identity = __commonJS((exports) => { - var ALIAS = Symbol.for("yaml.alias"); - var DOC = Symbol.for("yaml.document"); - var MAP = Symbol.for("yaml.map"); - var PAIR = Symbol.for("yaml.pair"); - var SCALAR = Symbol.for("yaml.scalar"); - var SEQ = Symbol.for("yaml.seq"); - var NODE_TYPE = Symbol.for("yaml.node.type"); - var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; - var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; - var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; - var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; - var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; - var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; - function isCollection(node) { - if (node && typeof node === "object") - switch (node[NODE_TYPE]) { - case MAP: - case SEQ: - return true; - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/structured_query/utils.js +function isObject3(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj); +} +function isFilterEmpty(filter) { + if (!filter) + return true; + if (typeof filter === "string" && filter.length > 0) return false; - } - function isNode3(node) { - if (node && typeof node === "object") - switch (node[NODE_TYPE]) { - case ALIAS: - case MAP: - case SCALAR: - case SEQ: - return true; - } + if (typeof filter === "function") return false; + return isObject3(filter) && Object.keys(filter).length === 0; +} +function isInt(value) { + if (typeof value === "number") + return value % 1 === 0; + else if (typeof value === "string") { + const numberValue = parseInt(value, 10); + return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; } - var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; - exports.ALIAS = ALIAS; - exports.DOC = DOC; - exports.MAP = MAP; - exports.NODE_TYPE = NODE_TYPE; - exports.PAIR = PAIR; - exports.SCALAR = SCALAR; - exports.SEQ = SEQ; - exports.hasAnchor = hasAnchor; - exports.isAlias = isAlias; - exports.isCollection = isCollection; - exports.isDocument = isDocument; - exports.isMap = isMap; - exports.isNode = isNode3; - exports.isPair = isPair; - exports.isScalar = isScalar; - exports.isSeq = isSeq; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/visit.js -var require_visit = __commonJS((exports) => { - var identity = require_identity(); - var BREAK = Symbol("break visit"); - var SKIP = Symbol("skip children"); - var REMOVE = Symbol("remove node"); - function visit(node, visitor) { - const visitor_ = initVisitor(visitor); - if (identity.isDocument(node)) { - const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); - if (cd === REMOVE) - node.contents = null; - } else - visit_(null, node, visitor_, Object.freeze([])); + return false; +} +function isFloat(value) { + if (typeof value === "number") + return value % 1 !== 0; + else if (typeof value === "string") { + const numberValue = parseFloat(value); + return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; } - visit.BREAK = BREAK; - visit.SKIP = SKIP; - visit.REMOVE = REMOVE; - function visit_(key, node, visitor, path2) { - const ctrl = callVisitor(key, node, visitor, path2); - if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path2, ctrl); - return visit_(key, ctrl, visitor, path2); + return false; +} +function isString(value) { + return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); +} +function isBoolean(value) { + return typeof value === "boolean"; +} +function castValue(input) { + let value; + if (isString(input)) + value = input; + else if (isInt(input)) + value = parseInt(input, 10); + else if (isFloat(input)) + value = parseFloat(input); + else if (isBoolean(input)) + value = Boolean(input); + else + throw new Error("Unsupported value type"); + return value; +} +var init_utils6 = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/structured_query/base.js +var BaseTranslator, BasicTranslator; +var init_base11 = __esm(() => { + init_ir(); + init_utils6(); + BaseTranslator = class extends Visitor { + }; + BasicTranslator = class extends BaseTranslator { + allowedOperators; + allowedComparators; + constructor(opts) { + super(); + this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; + this.allowedComparators = opts?.allowedComparators ?? [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; } - if (typeof ctrl !== "symbol") { - if (identity.isCollection(node)) { - path2 = Object.freeze(path2.concat(node)); - for (let i = 0;i < node.items.length; ++i) { - const ci = visit_(i, node.items[i], visitor, path2); - if (typeof ci === "number") - i = ci - 1; - else if (ci === BREAK) - return BREAK; - else if (ci === REMOVE) { - node.items.splice(i, 1); - i -= 1; - } - } - } else if (identity.isPair(node)) { - path2 = Object.freeze(path2.concat(node)); - const ck = visit_("key", node.key, visitor, path2); - if (ck === BREAK) - return BREAK; - else if (ck === REMOVE) - node.key = null; - const cv = visit_("value", node.value, visitor, path2); - if (cv === BREAK) - return BREAK; - else if (cv === REMOVE) - node.value = null; - } + formatFunction(func) { + if (func in Comparators) { + if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) + throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); + } else if (func in Operators) { + if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) + throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); + } else + throw new Error("Unknown comparator or operator"); + return `$${func}`; } - return ctrl; - } - async function visitAsync(node, visitor) { - const visitor_ = initVisitor(visitor); - if (identity.isDocument(node)) { - const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); - if (cd === REMOVE) - node.contents = null; - } else - await visitAsync_(null, node, visitor_, Object.freeze([])); - } - visitAsync.BREAK = BREAK; - visitAsync.SKIP = SKIP; - visitAsync.REMOVE = REMOVE; - async function visitAsync_(key, node, visitor, path2) { - const ctrl = await callVisitor(key, node, visitor, path2); - if (identity.isNode(ctrl) || identity.isPair(ctrl)) { - replaceNode(key, path2, ctrl); - return visitAsync_(key, ctrl, visitor, path2); + visitOperation(operation) { + const args = operation.args?.map((arg) => arg.accept(this)); + return { [this.formatFunction(operation.operator)]: args }; } - if (typeof ctrl !== "symbol") { - if (identity.isCollection(node)) { - path2 = Object.freeze(path2.concat(node)); - for (let i = 0;i < node.items.length; ++i) { - const ci = await visitAsync_(i, node.items[i], visitor, path2); - if (typeof ci === "number") - i = ci - 1; - else if (ci === BREAK) - return BREAK; - else if (ci === REMOVE) { - node.items.splice(i, 1); - i -= 1; - } - } - } else if (identity.isPair(node)) { - path2 = Object.freeze(path2.concat(node)); - const ck = await visitAsync_("key", node.key, visitor, path2); - if (ck === BREAK) - return BREAK; - else if (ck === REMOVE) - node.key = null; - const cv = await visitAsync_("value", node.value, visitor, path2); - if (cv === BREAK) - return BREAK; - else if (cv === REMOVE) - node.value = null; - } + visitComparison(comparison) { + return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; } - return ctrl; - } - function initVisitor(visitor) { - if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { - return Object.assign({ - Alias: visitor.Node, - Map: visitor.Node, - Scalar: visitor.Node, - Seq: visitor.Node - }, visitor.Value && { - Map: visitor.Value, - Scalar: visitor.Value, - Seq: visitor.Value - }, visitor.Collection && { - Map: visitor.Collection, - Seq: visitor.Collection - }, visitor); + visitStructuredQuery(query3) { + let nextArg = {}; + if (query3.filter) + nextArg = { filter: query3.filter.accept(this) }; + return nextArg; } - return visitor; - } - function callVisitor(key, node, visitor, path2) { - if (typeof visitor === "function") - return visitor(key, node, path2); - if (identity.isMap(node)) - return visitor.Map?.(key, node, path2); - if (identity.isSeq(node)) - return visitor.Seq?.(key, node, path2); - if (identity.isPair(node)) - return visitor.Pair?.(key, node, path2); - if (identity.isScalar(node)) - return visitor.Scalar?.(key, node, path2); - if (identity.isAlias(node)) - return visitor.Alias?.(key, node, path2); - return; - } - function replaceNode(key, path2, node) { - const parent = path2[path2.length - 1]; - if (identity.isCollection(parent)) { - parent.items[key] = node; - } else if (identity.isPair(parent)) { - if (key === "key") - parent.key = node; + mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) + return; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) + return; + return generatedFilter; + } + if (isFilterEmpty(generatedFilter)) { + if (forceDefaultFilter) + return defaultFilter; + if (mergeType === "and") + return; + return defaultFilter; + } + if (mergeType === "and") + return { $and: [defaultFilter, generatedFilter] }; + else if (mergeType === "or") + return { $or: [defaultFilter, generatedFilter] }; else - parent.value = node; - } else if (identity.isDocument(parent)) { - parent.contents = node; - } else { - const pt = identity.isAlias(parent) ? "alias" : "scalar"; - throw new Error(`Cannot replace node with ${pt} parent`); + throw new Error("Unknown merge type"); } - } - exports.visit = visit; - exports.visitAsync = visitAsync; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/doc/directives.js -var require_directives = __commonJS((exports) => { - var identity = require_identity(); - var visit = require_visit(); - var escapeChars = { - "!": "%21", - ",": "%2C", - "[": "%5B", - "]": "%5D", - "{": "%7B", - "}": "%7D" }; - var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); +}); - class Directives { - constructor(yaml, tags) { - this.docStart = null; - this.docEnd = false; - this.yaml = Object.assign({}, Directives.defaultYaml, yaml); - this.tags = Object.assign({}, Directives.defaultTags, tags); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/structured_query/functional.js +var FunctionalTranslator; +var init_functional = __esm(() => { + init_ir(); + init_utils6(); + init_base11(); + FunctionalTranslator = class extends BaseTranslator { + allowedOperators = [Operators.and, Operators.or]; + allowedComparators = [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + formatFunction() { + throw new Error("Not implemented"); } - clone() { - const copy = new Directives(this.yaml, this.tags); - copy.docStart = this.docStart; - return copy; + getAllowedComparatorsForType(inputType) { + switch (inputType) { + case "string": + return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "number": + return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "boolean": + return [Comparators.eq, Comparators.ne]; + default: + throw new Error(`Unsupported data type: ${inputType}`); + } } - atDocument() { - const res = new Directives(this.yaml, this.tags); - switch (this.yaml.version) { - case "1.1": - this.atNextDocument = true; - break; - case "1.2": - this.atNextDocument = false; - this.yaml = { - explicit: Directives.defaultYaml.explicit, - version: "1.2" - }; - this.tags = Object.assign({}, Directives.defaultTags); - break; + getComparatorFunction(comparator) { + switch (comparator) { + case Comparators.eq: + return (a, b) => a === b; + case Comparators.ne: + return (a, b) => a !== b; + case Comparators.gt: + return (a, b) => a > b; + case Comparators.gte: + return (a, b) => a >= b; + case Comparators.lt: + return (a, b) => a < b; + case Comparators.lte: + return (a, b) => a <= b; + default: + throw new Error("Unknown comparator"); } - return res; } - add(line, onError2) { - if (this.atNextDocument) { - this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; - this.tags = Object.assign({}, Directives.defaultTags); - this.atNextDocument = false; + getOperatorFunction(operator) { + switch (operator) { + case Operators.and: + return (a, b) => a && b; + case Operators.or: + return (a, b) => a || b; + default: + throw new Error("Unknown operator"); } - const parts = line.trim().split(/[ \t]+/); - const name = parts.shift(); - switch (name) { - case "%TAG": { - if (parts.length !== 2) { - onError2(0, "%TAG directive should contain exactly two parts"); - if (parts.length < 2) - return false; - } - const [handle, prefix] = parts; - this.tags[handle] = prefix; - return true; - } - case "%YAML": { - this.yaml.explicit = true; - if (parts.length !== 1) { - onError2(0, "%YAML directive should contain exactly one part"); - return false; - } - const [version4] = parts; - if (version4 === "1.1" || version4 === "1.2") { - this.yaml.version = version4; + } + visitOperation(operation) { + const { operator, args } = operation; + if (this.allowedOperators.includes(operator)) { + const operatorFunction = this.getOperatorFunction(operator); + return (document2) => { + if (!args) return true; - } else { - const isValid2 = /^\d+\.\d+$/.test(version4); - onError2(6, `Unsupported YAML version ${version4}`, isValid2); + return args.reduce((acc, arg) => { + const result = arg.accept(this); + if (typeof result === "function") + return operatorFunction(acc, result(document2)); + else + throw new Error("Filter is not a function"); + }, true); + }; + } else + throw new Error("Operator not allowed"); + } + visitComparison(comparison) { + const { comparator, attribute, value } = comparison; + const undefinedTrue = [Comparators.ne]; + if (this.allowedComparators.includes(comparator)) { + if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) + throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); + const comparatorFunction = this.getComparatorFunction(comparator); + return (document2) => { + const documentValue = document2.metadata[attribute]; + if (documentValue === undefined) { + if (undefinedTrue.includes(comparator)) + return true; return false; } - } - default: - onError2(0, `Unknown directive ${name}`, true); - return false; - } + return comparatorFunction(documentValue, castValue(value)); + }; + } else + throw new Error("Comparator not allowed"); } - tagName(source, onError2) { - if (source === "!") - return "!"; - if (source[0] !== "!") { - onError2(`Not a valid tag: ${source}`); - return null; - } - if (source[1] === "<") { - const verbatim = source.slice(2, -1); - if (verbatim === "!" || verbatim === "!!") { - onError2(`Verbatim tags aren't resolved, so ${source} is invalid.`); - return null; - } - if (source[source.length - 1] !== ">") - onError2("Verbatim tags must end with a >"); - return verbatim; - } - const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); - if (!suffix) - onError2(`The ${source} tag has no suffix`); - const prefix = this.tags[handle]; - if (prefix) { - try { - return prefix + decodeURIComponent(suffix); - } catch (error51) { - onError2(String(error51)); - return null; - } - } - if (handle === "!") - return source; - onError2(`Could not resolve tag: ${source}`); - return null; + visitStructuredQuery(query3) { + if (!query3.filter) + return {}; + const filterFunction = query3.filter?.accept(this); + if (typeof filterFunction !== "function") + throw new Error("Structured query filter is not a function"); + return { filter: filterFunction }; } - tagString(tag) { - for (const [handle, prefix] of Object.entries(this.tags)) { - if (tag.startsWith(prefix)) - return handle + escapeTagName(tag.substring(prefix.length)); + mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) + return; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) + return; + return generatedFilter; } - return tag[0] === "!" ? tag : `!<${tag}>`; - } - toString(doc2) { - const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; - const tagEntries = Object.entries(this.tags); - let tagNames; - if (doc2 && tagEntries.length > 0 && identity.isNode(doc2.contents)) { - const tags = {}; - visit.visit(doc2.contents, (_key, node) => { - if (identity.isNode(node) && node.tag) - tags[node.tag] = true; - }); - tagNames = Object.keys(tags); - } else - tagNames = []; - for (const [handle, prefix] of tagEntries) { - if (handle === "!!" && prefix === "tag:yaml.org,2002:") - continue; - if (!doc2 || tagNames.some((tn) => tn.startsWith(prefix))) - lines.push(`%TAG ${handle} ${prefix}`); + if (isFilterEmpty(generatedFilter)) { + if (mergeType === "and") + return; + return defaultFilter; } - return lines.join(` -`); + if (mergeType === "and") + return (document2) => defaultFilter(document2) && generatedFilter(document2); + else if (mergeType === "or") + return (document2) => defaultFilter(document2) || generatedFilter(document2); + else + throw new Error("Unknown merge type"); } - } - Directives.defaultYaml = { explicit: false, version: "1.2" }; - Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; - exports.Directives = Directives; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/doc/anchors.js -var require_anchors = __commonJS((exports) => { - var identity = require_identity(); - var visit = require_visit(); - function anchorIsValid(anchor) { - if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { - const sa = JSON.stringify(anchor); - const msg = `Anchor must not contain whitespace or control characters: ${sa}`; - throw new Error(msg); - } - return true; - } - function anchorNames(root) { - const anchors = new Set; - visit.visit(root, { - Value(_key, node) { - if (node.anchor) - anchors.add(node.anchor); - } - }); - return anchors; - } - function findNewAnchor(prefix, exclude) { - for (let i = 1;; ++i) { - const name = `${prefix}${i}`; - if (!exclude.has(name)) - return name; - } - } - function createNodeAnchors(doc2, prefix) { - const aliasObjects = []; - const sourceObjects = new Map; - let prevAnchors = null; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/structured_query/index.js +var structured_query_exports; +var init_structured_query = __esm(() => { + init_runtime2(); + init_ir(); + init_utils6(); + init_base11(); + init_functional(); + structured_query_exports = /* @__PURE__ */ __exportAll({ + BaseTranslator: () => BaseTranslator, + BasicTranslator: () => BasicTranslator, + Comparators: () => Comparators, + Comparison: () => Comparison, + Expression: () => Expression, + FilterDirective: () => FilterDirective, + FunctionalTranslator: () => FunctionalTranslator, + Operation: () => Operation, + Operators: () => Operators, + StructuredQuery: () => StructuredQuery, + Visitor: () => Visitor, + castValue: () => castValue, + isBoolean: () => isBoolean, + isFilterEmpty: () => isFilterEmpty, + isFloat: () => isFloat, + isInt: () => isInt, + isObject: () => isObject3, + isString: () => isString + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/testing/matchers.js +function getMessageTypeName(msg) { + if (!BaseMessage.isInstance(msg)) + return typeof msg; + return msg.constructor.name || msg.type; +} +function makeMessageTypeMatcher(typeName, isInstance) { + return function(received, expected) { + const { isNot, utils } = this; + if (!isInstance(received)) + return { + pass: false, + message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} + +Expected: ${isNot ? "not " : ""}${typeName} +Received: ${getMessageTypeName(received)}`, + actual: getMessageTypeName(received), + expected: typeName + }; + if (expected === undefined) + return { + pass: true, + message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} + +Expected: not ${typeName} +Received: ${typeName}` + }; + const msg = received; + if (typeof expected === "string") + return { + pass: msg.content === expected, + message: () => `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} + +Expected: ${typeName} with content ${utils.printExpected(expected)} +Received: ${typeName} with content ${utils.printReceived(msg.content)}`, + actual: msg.content, + expected + }; return { - onAnchor: (source) => { - aliasObjects.push(source); - prevAnchors ?? (prevAnchors = anchorNames(doc2)); - const anchor = findNewAnchor(prefix, prevAnchors); - prevAnchors.add(anchor); - return anchor; - }, - setAnchors: () => { - for (const source of aliasObjects) { - const ref = sourceObjects.get(source); - if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { - ref.node.anchor = ref.anchor; - } else { - const error51 = new Error("Failed to resolve repeated object (this should not happen)"); - error51.source = source; - throw error51; - } - } + pass: Object.entries(expected).every(([key, value]) => this.equals(msg[key], value)), + message: () => { + const receivedFields = {}; + for (const key of Object.keys(expected)) + receivedFields[key] = msg[key]; + return `${utils.matcherHint(`toBe${typeName}`, undefined, undefined)} + +Expected: ${typeName} matching ${utils.printExpected(expected)} +Received: ${typeName} with ${utils.printReceived(receivedFields)}`; }, - sourceObjects + actual: (() => { + const receivedFields = {}; + for (const key of Object.keys(expected)) + receivedFields[key] = msg[key]; + return receivedFields; + })(), + expected }; - } - exports.anchorIsValid = anchorIsValid; - exports.anchorNames = anchorNames; - exports.createNodeAnchors = createNodeAnchors; - exports.findNewAnchor = findNewAnchor; -}); + }; +} +function toHaveToolCalls(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")} -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/doc/applyReviver.js -var require_applyReviver = __commonJS((exports) => { - function applyReviver(reviver2, obj, key, val) { - if (val && typeof val === "object") { - if (Array.isArray(val)) { - for (let i = 0, len = val.length;i < len; ++i) { - const v0 = val[i]; - const v13 = applyReviver(reviver2, val, String(i), v0); - if (v13 === undefined) - delete val[i]; - else if (v13 !== v0) - val[i] = v13; - } - } else if (val instanceof Map) { - for (const k of Array.from(val.keys())) { - const v0 = val.get(k); - const v13 = applyReviver(reviver2, val, k, v0); - if (v13 === undefined) - val.delete(k); - else if (v13 !== v0) - val.set(k, v13); - } - } else if (val instanceof Set) { - for (const v0 of Array.from(val)) { - const v13 = applyReviver(reviver2, val, v0, v0); - if (v13 === undefined) - val.delete(v0); - else if (v13 !== v0) { - val.delete(v0); - val.add(v13); - } - } - } else { - for (const [k, v0] of Object.entries(val)) { - const v13 = applyReviver(reviver2, val, k, v0); - if (v13 === undefined) - delete val[k]; - else if (v13 !== v0) - val[k] = v13; - } - } - } - return reviver2.call(obj, key, val); - } - exports.applyReviver = applyReviver; -}); +Expected: AIMessage +Received: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls ?? []; + if (actual.length !== expected.length) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")} -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/toJS.js -var require_toJS = __commonJS((exports) => { - var identity = require_identity(); - function toJS(value, arg, ctx) { - if (Array.isArray(value)) - return value.map((v, i) => toJS(v, String(i), ctx)); - if (value && typeof value.toJSON === "function") { - if (!ctx || !identity.hasAnchor(value)) - return value.toJSON(arg, ctx); - const data = { aliasCount: 0, count: 1, res: undefined }; - ctx.anchors.set(value, data); - ctx.onCreate = (res2) => { - data.res = res2; - delete ctx.onCreate; +Expected ${isNot ? "not " : ""}${expected.length} tool call(s), received ${actual.length}`, + actual: actual.length, + expected: expected.length + }; + const unmatched = expected.filter((exp) => !actual.some((tc) => Object.entries(exp).every(([key, value]) => this.equals(tc[key], value)))); + if (unmatched.length > 0) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCalls")} + +Could not find matching tool call(s) for: +${utils.printExpected(unmatched)} +Received tool calls: ${utils.printReceived(actual.map((tc) => ({ + name: tc.name, + id: tc.id, + args: tc.args + })))}`, + actual: actual.map((tc) => ({ + name: tc.name, + id: tc.id, + args: tc.args + })), + expected + }; + return { + pass: true, + message: () => `${utils.matcherHint("toHaveToolCalls")} + +Expected AIMessage not to have matching tool calls` + }; +} +function toHaveToolCallCount(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolCallCount")} + +Expected: AIMessage +Received: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls?.length ?? 0; + return { + pass: actual === expected, + message: () => `${utils.matcherHint("toHaveToolCallCount")} + +Expected ${isNot ? "not " : ""}${expected} tool call(s) +Received: ${actual}`, + actual, + expected + }; +} +function toContainToolCall(received, expected) { + const { isNot, utils } = this; + if (!AIMessage.isInstance(received)) + return { + pass: false, + message: () => `${utils.matcherHint("toContainToolCall")} + +Expected: AIMessage +Received: ${getMessageTypeName(received)}` + }; + const actual = received.tool_calls ?? []; + return { + pass: actual.some((tc) => Object.entries(expected).every(([key, value]) => this.equals(tc[key], value))), + message: () => `${utils.matcherHint("toContainToolCall")} + +Expected AIMessage ${isNot ? "not " : ""}to contain a tool call matching ${utils.printExpected(expected)} +Received tool calls: ${utils.printReceived(actual.map((tc) => ({ + name: tc.name, + id: tc.id + })))}`, + actual: actual.map((tc) => ({ + name: tc.name, + id: tc.id + })), + expected + }; +} +function toHaveToolMessages(received, expected) { + const { isNot, utils } = this; + if (!Array.isArray(received)) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolMessages")} + +Expected an array of messages +Received: ${typeof received}` + }; + const toolMessages = received.filter(ToolMessage.isInstance); + if (toolMessages.length !== expected.length) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveToolMessages")} + +Expected ${isNot ? "not " : ""}${expected.length} tool message(s), found ${toolMessages.length}`, + actual: toolMessages.length, + expected: expected.length + }; + for (let i = 0;i < expected.length; i++) + if (!Object.entries(expected[i]).every(([key, value]) => this.equals(toolMessages[i][key], value))) + return { + pass: false, + message: () => { + const receivedFields = {}; + for (const key of Object.keys(expected[i])) + receivedFields[key] = toolMessages[i][key]; + return `${utils.matcherHint("toHaveToolMessages")} + +Tool message at index ${i} did not match: +Expected: ${utils.printExpected(expected[i])} +Received: ${utils.printReceived(receivedFields)}`; + }, + actual: toolMessages[i], + expected: expected[i] }; - const res = value.toJSON(arg, ctx); - if (ctx.onCreate) - ctx.onCreate(res); - return res; - } - if (typeof value === "bigint" && !ctx?.keep) - return Number(value); - return value; - } - exports.toJS = toJS; -}); + return { + pass: true, + message: () => `${utils.matcherHint("toHaveToolMessages")} -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/Node.js -var require_Node = __commonJS((exports) => { - var applyReviver = require_applyReviver(); - var identity = require_identity(); - var toJS = require_toJS(); +Expected messages not to contain matching tool messages` + }; +} +function toHaveBeenInterrupted(received, expectedValue) { + const { isNot, utils } = this; + const interrupts = received?.__interrupt__; + if (!(Array.isArray(interrupts) && interrupts.length > 0)) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveBeenInterrupted")} - class NodeBase { - constructor(type) { - Object.defineProperty(this, identity.NODE_TYPE, { value: type }); +Expected result ${isNot ? "not " : ""}to have been interrupted +Received __interrupt__: ${utils.printReceived(interrupts)}` + }; + if (expectedValue === undefined) + return { + pass: true, + message: () => `${utils.matcherHint("toHaveBeenInterrupted")} + +Expected result not to have been interrupted +Received ${interrupts.length} interrupt(s)` + }; + const actualValue = interrupts[0]?.value; + return { + pass: this.equals(actualValue, expectedValue), + message: () => `${utils.matcherHint("toHaveBeenInterrupted")} + +Expected interrupt value: ${utils.printExpected(expectedValue)} +Received interrupt value: ${utils.printReceived(actualValue)}`, + actual: actualValue, + expected: expectedValue + }; +} +function toHaveStructuredResponse(received, expected) { + const { isNot, utils } = this; + const structuredResponse = received?.structuredResponse; + if (!(structuredResponse !== undefined)) + return { + pass: false, + message: () => `${utils.matcherHint("toHaveStructuredResponse")} + +Expected result ${isNot ? "not " : ""}to have a structured response +Received structuredResponse: undefined` + }; + if (expected === undefined) + return { + pass: true, + message: () => `${utils.matcherHint("toHaveStructuredResponse")} + +Expected result not to have a structured response` + }; + return { + pass: Object.entries(expected).every(([key, value]) => this.equals(structuredResponse[key], value)), + message: () => `${utils.matcherHint("toHaveStructuredResponse")} + +Expected structured response: ${utils.printExpected(expected)} +Received structured response: ${utils.printReceived(structuredResponse)}`, + actual: structuredResponse, + expected + }; +} +var toBeHumanMessage, toBeAIMessage, toBeSystemMessage, toBeToolMessage, langchainMatchers; +var init_matchers = __esm(() => { + init_base(); + init_tool(); + init_ai(); + init_human(); + init_system(); + init_messages(); + toBeHumanMessage = makeMessageTypeMatcher("HumanMessage", HumanMessage.isInstance); + toBeAIMessage = makeMessageTypeMatcher("AIMessage", AIMessage.isInstance); + toBeSystemMessage = makeMessageTypeMatcher("SystemMessage", SystemMessage.isInstance); + toBeToolMessage = makeMessageTypeMatcher("ToolMessage", ToolMessage.isInstance); + langchainMatchers = { + toBeHumanMessage, + toBeAIMessage, + toBeSystemMessage, + toBeToolMessage, + toHaveToolCalls, + toHaveToolCallCount, + toContainToolCall, + toHaveToolMessages, + toHaveBeenInterrupted, + toHaveStructuredResponse + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/testing/fake_model_builder.js +function deriveContent(messages) { + return messages.map((m) => m.text).filter(Boolean).join("-"); +} +function nextToolCallId() { + idCounter += 1; + return `fake_tc_${idCounter}`; +} +function fakeModel() { + return new FakeBuiltModel; +} +var idCounter = 0, FakeBuiltModel; +var init_fake_model_builder = __esm(() => { + init_base(); + init_ai(); + init_base4(); + init_messages(); + init_chat_models(); + FakeBuiltModel = class FakeBuiltModel2 extends BaseChatModel { + queue = []; + _alwaysThrowError; + _structuredResponseValue; + _tools = []; + _state = { + callIndex: 0, + calls: [] + }; + get calls() { + return this._state.calls; } - clone() { - const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); - if (this.range) - copy.range = this.range.slice(); - return copy; + get callCount() { + return this._state.calls.length; } - toJS(doc2, { mapAsMap, maxAliasCount, onAnchor, reviver: reviver2 } = {}) { - if (!identity.isDocument(doc2)) - throw new TypeError("A document argument is required"); - const ctx = { - anchors: new Map, - doc: doc2, - keep: true, - mapAsMap: mapAsMap === true, - mapKeyWarned: false, - maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 - }; - const res = toJS.toJS(this, "", ctx); - if (typeof onAnchor === "function") - for (const { count, res: res2 } of ctx.anchors.values()) - onAnchor(res2, count); - return typeof reviver2 === "function" ? applyReviver.applyReviver(reviver2, { "": res }, "", res) : res; + constructor() { + super({}); } - } - exports.NodeBase = NodeBase; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/Alias.js -var require_Alias = __commonJS((exports) => { - var anchors = require_anchors(); - var visit = require_visit(); - var identity = require_identity(); - var Node3 = require_Node(); - var toJS = require_toJS(); - - class Alias extends Node3.NodeBase { - constructor(source) { - super(identity.ALIAS); - this.source = source; - Object.defineProperty(this, "tag", { - set() { - throw new Error("Alias nodes cannot have tags"); - } - }); + _llmType() { + return "fake-model-builder"; } - resolve(doc2, ctx) { - if (ctx?.maxAliasCount === 0) - throw new ReferenceError("Alias resolution is disabled"); - let nodes; - if (ctx?.aliasResolveCache) { - nodes = ctx.aliasResolveCache; - } else { - nodes = []; - visit.visit(doc2, { - Node: (_key, node) => { - if (identity.isAlias(node) || identity.hasAnchor(node)) - nodes.push(node); - } + _combineLLMOutput() { + return []; + } + respond(entry) { + if (typeof entry === "function") + this.queue.push({ + kind: "factory", + factory: entry }); - if (ctx) - ctx.aliasResolveCache = nodes; - } - let found = undefined; - for (const node of nodes) { - if (node === this) - break; - if (node.anchor === this.source) - found = node; - } - return found; + else if (BaseMessage.isInstance(entry)) + this.queue.push({ + kind: "message", + message: entry + }); + else + this.queue.push({ + kind: "error", + error: entry + }); + return this; } - toJSON(_arg, ctx) { - if (!ctx) - return { source: this.source }; - const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx; - const source = this.resolve(doc2, ctx); - if (!source) { - const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; - throw new ReferenceError(msg); - } - let data = anchors2.get(source); - if (!data) { - toJS.toJS(source, null, ctx); - data = anchors2.get(source); - } - if (data?.res === undefined) { - const msg = "This should not happen: Alias anchor was not resolved?"; - throw new ReferenceError(msg); - } - if (maxAliasCount >= 0) { - data.count += 1; - if (data.aliasCount === 0) - data.aliasCount = getAliasCount(doc2, source, anchors2); - if (data.count * data.aliasCount > maxAliasCount) { - const msg = "Excessive alias count indicates a resource exhaustion attack"; - throw new ReferenceError(msg); - } - } - return data.res; + respondWithTools(toolCalls) { + this.queue.push({ + kind: "toolCalls", + toolCalls: toolCalls.map((tc) => ({ + name: tc.name, + args: tc.args, + id: tc.id ?? nextToolCallId(), + type: "tool_call" + })) + }); + return this; } - toString(ctx, _onComment, _onChompKeep) { - const src = `*${this.source}`; - if (ctx) { - anchors.anchorIsValid(this.source); - if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { - const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; - throw new Error(msg); - } - if (ctx.implicitKey) - return `${src} `; - } - return src; + alwaysThrow(error90) { + this._alwaysThrowError = error90; + return this; } - } - function getAliasCount(doc2, node, anchors2) { - if (identity.isAlias(node)) { - const source = node.resolve(doc2); - const anchor = anchors2 && source && anchors2.get(source); - return anchor ? anchor.count * anchor.aliasCount : 0; - } else if (identity.isCollection(node)) { - let count = 0; - for (const item of node.items) { - const c = getAliasCount(doc2, item, anchors2); - if (c > count) - count = c; + structuredResponse(value) { + this._structuredResponseValue = value; + return this; + } + bindTools(tools) { + const merged = [...this._tools, ...tools]; + const next = new FakeBuiltModel2; + next.queue = this.queue; + next._alwaysThrowError = this._alwaysThrowError; + next._structuredResponseValue = this._structuredResponseValue; + next._tools = merged; + next._state = this._state; + return next.withConfig({}); + } + withStructuredOutput(_params, _config) { + const { _structuredResponseValue } = this; + return RunnableLambda.from(async () => { + return _structuredResponseValue; + }); + } + async _generate(messages, options, _runManager) { + this._state.calls.push({ + messages: [...messages], + options + }); + const currentCallIndex = this._state.callIndex; + this._state.callIndex += 1; + if (this._alwaysThrowError) + throw this._alwaysThrowError; + const entry = this.queue[currentCallIndex]; + if (!entry) + throw new Error(`FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`); + if (entry.kind === "error") + throw entry.error; + if (entry.kind === "factory") { + const result = entry.factory(messages); + if (!BaseMessage.isInstance(result)) + throw result; + return { generations: [{ + text: "", + message: result + }] }; } - return count; - } else if (identity.isPair(node)) { - const kc = getAliasCount(doc2, node.key, anchors2); - const vc = getAliasCount(doc2, node.value, anchors2); - return Math.max(kc, vc); + if (entry.kind === "message") + return { generations: [{ + text: "", + message: entry.message + }] }; + const content = deriveContent(messages); + return { + generations: [{ + text: content, + message: new AIMessage({ + content, + id: currentCallIndex.toString(), + tool_calls: entry.toolCalls.length > 0 ? entry.toolCalls.map((tc) => ({ + ...tc, + type: "tool_call" + })) : undefined + }) + }], + llmOutput: {} + }; } - return 1; - } - exports.Alias = Alias; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/Scalar.js -var require_Scalar = __commonJS((exports) => { - var identity = require_identity(); - var Node3 = require_Node(); - var toJS = require_toJS(); - var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/testing/index.js +var testing_exports; +var init_testing = __esm(() => { + init_runtime2(); + init_matchers(); + init_fake_model_builder(); + testing_exports = /* @__PURE__ */ __exportAll({ + FakeBuiltModel: () => FakeBuiltModel, + fakeModel: () => fakeModel, + langchainMatchers: () => langchainMatchers, + toBeAIMessage: () => toBeAIMessage, + toBeHumanMessage: () => toBeHumanMessage, + toBeSystemMessage: () => toBeSystemMessage, + toBeToolMessage: () => toBeToolMessage, + toContainToolCall: () => toContainToolCall, + toHaveBeenInterrupted: () => toHaveBeenInterrupted, + toHaveStructuredResponse: () => toHaveStructuredResponse, + toHaveToolCallCount: () => toHaveToolCallCount, + toHaveToolCalls: () => toHaveToolCalls, + toHaveToolMessages: () => toHaveToolMessages + }); +}); - class Scalar extends Node3.NodeBase { - constructor(value) { - super(identity.SCALAR); - this.value = value; - } - toJSON(arg, ctx) { - return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/tracers/run_collector.js +var run_collector_exports, RunCollectorCallbackHandler; +var init_run_collector = __esm(() => { + init_runtime2(); + init_base3(); + run_collector_exports = /* @__PURE__ */ __exportAll({ RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); + RunCollectorCallbackHandler = class extends BaseTracer { + name = "run_collector"; + exampleId; + tracedRuns; + constructor({ exampleId } = {}) { + super({ _awaitHandler: true }); + this.exampleId = exampleId; + this.tracedRuns = []; } - toString() { - return String(this.value); + async persistRun(run2) { + const run_ = { ...run2 }; + run_.reference_example_id = this.exampleId; + this.tracedRuns.push(run_); } - } - Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; - Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; - Scalar.PLAIN = "PLAIN"; - Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; - Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; - exports.Scalar = Scalar; - exports.isScalarValue = isScalarValue; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/doc/createNode.js -var require_createNode = __commonJS((exports) => { - var Alias = require_Alias(); - var identity = require_identity(); - var Scalar = require_Scalar(); - var defaultTagPrefix = "tag:yaml.org,2002:"; - function findTagObject(value, tagName, tags) { - if (tagName) { - const match2 = tags.filter((t) => t.tag === tagName); - const tagObj = match2.find((t) => !t.format) ?? match2[0]; - if (!tagObj) - throw new Error(`Tag ${tagName} not found`); - return tagObj; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/types/stream.js +var stream_exports3; +var init_stream3 = __esm(() => { + init_runtime2(); + stream_exports3 = /* @__PURE__ */ __exportAll({}); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/chunk_array.js +var chunk_array_exports, chunkArray = (arr3, chunkSize) => arr3.reduce((chunks, elem, index2) => { + const chunkIndex = Math.floor(index2 / chunkSize); + chunks[chunkIndex] = (chunks[chunkIndex] || []).concat([elem]); + return chunks; +}, []); +var init_chunk_array = __esm(() => { + init_runtime2(); + chunk_array_exports = /* @__PURE__ */ __exportAll({ chunkArray: () => chunkArray }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/context.js +function context(strings, ...values) { + const raw2 = strings.raw; + let result = ""; + for (let i = 0;i < raw2.length; i++) { + const next = raw2[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{"); + result += next; + if (i < values.length) { + const value = alignValue(values[i], result); + result += typeof value === "string" ? value : JSON.stringify(value); } - return tags.find((t) => t.identify?.(value) && !t.format); } - function createNode(value, tagName, ctx) { - if (identity.isDocument(value)) - value = value.contents; - if (identity.isNode(value)) - return value; - if (identity.isPair(value)) { - const map2 = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); - map2.items.push(value); - return map2; - } - if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { - value = value.valueOf(); - } - const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; - let ref = undefined; - if (aliasDuplicateObjects && value && typeof value === "object") { - ref = sourceObjects.get(value); - if (ref) { - ref.anchor ?? (ref.anchor = onAnchor(value)); - return new Alias.Alias(ref.anchor); - } else { - ref = { anchor: null, node: null }; - sourceObjects.set(value, ref); - } - } - if (tagName?.startsWith("!!")) - tagName = defaultTagPrefix + tagName.slice(2); - let tagObj = findTagObject(value, tagName, schema.tags); - if (!tagObj) { - if (value && typeof value.toJSON === "function") { - value = value.toJSON(); - } - if (!value || typeof value !== "object") { - const node2 = new Scalar.Scalar(value); - if (ref) - ref.node = node2; - return node2; - } - tagObj = value instanceof Map ? schema[identity.MAP] : (Symbol.iterator in Object(value)) ? schema[identity.SEQ] : schema[identity.MAP]; - } - if (onTagObj) { - onTagObj(tagObj); - delete ctx.onTagObj; + result = stripIndent(result); + result = result.trim(); + result = result.replace(/\\n/g, ` +`); + return result; +} +function alignValue(value, precedingText) { + if (typeof value !== "string" || !value.includes(` +`)) + return value; + const indentMatch = precedingText.slice(precedingText.lastIndexOf(` +`) + 1).match(/^(\s+)/); + if (indentMatch) { + const indent = indentMatch[1]; + return value.replace(/\n/g, ` +${indent}`); + } + return value; +} +function stripIndent(text) { + const lines = text.split(` +`); + let minIndent = null; + for (const line of lines) { + const match2 = line.match(/^(\s+)\S+/); + if (match2) { + const indent = match2[1].length; + if (minIndent === null) + minIndent = indent; + else + minIndent = Math.min(minIndent, indent); } - const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); - if (tagName) - node.tag = tagName; - else if (!tagObj.default) - node.tag = tagObj.tag; - if (ref) - ref.node = node; - return node; } - exports.createNode = createNode; + if (minIndent === null) + return text; + return lines.map((line) => line[0] === " " || line[0] === "\t" ? line.slice(minIndent) : line).join(` +`); +} +var context_exports; +var init_context2 = __esm(() => { + init_runtime2(); + context_exports = /* @__PURE__ */ __exportAll({ context: () => context }); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/Collection.js -var require_Collection = __commonJS((exports) => { - var createNode = require_createNode(); - var identity = require_identity(); - var Node3 = require_Node(); - function collectionFromPath(schema, path2, value) { - let v = value; - for (let i = path2.length - 1;i >= 0; --i) { - const k = path2[i]; - if (typeof k === "number" && Number.isInteger(k) && k >= 0) { - const a = []; - a[k] = v; - v = a; - } else { - v = new Map([[k, v]]); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/event_source_parse.js +async function getBytes(stream2, onChunk) { + if (stream2 instanceof ReadableStream) { + const reader = stream2.getReader(); + while (true) { + const result = await reader.read(); + if (result.done) { + onChunk(new Uint8Array, true); + break; } + onChunk(result.value); } - return createNode.createNode(v, undefined, { - aliasDuplicateObjects: false, - keepUndefined: false, - onAnchor: () => { - throw new Error("This should not happen, please report a bug."); - }, - schema, - sourceObjects: new Map - }); - } - var isEmptyPath = (path2) => path2 == null || typeof path2 === "object" && !!path2[Symbol.iterator]().next().done; - - class Collection extends Node3.NodeBase { - constructor(type, schema) { - super(type); - Object.defineProperty(this, "schema", { - value: schema, - configurable: true, - enumerable: false, - writable: true - }); + } else + try { + for await (const chunk of stream2) + onChunk(new Uint8Array(chunk)); + onChunk(new Uint8Array, true); + } catch (e) { + throw new Error([ + "Parsing event source stream failed.", + "Ensure your implementation of fetch returns a web or Node readable stream.", + `Error: ${e.message}` + ].join(` +`)); } - clone(schema) { - const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); - if (schema) - copy.schema = schema; - copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); - if (this.range) - copy.range = this.range.slice(); - return copy; +} +function getLines(onLine) { + let buffer; + let position; + let fieldLength; + let discardTrailingNewline = false; + return function onChunk(arr3, flush) { + if (flush) { + onLine(arr3, 0, true); + return; } - addIn(path2, value) { - if (isEmptyPath(path2)) - this.add(value); - else { - const [key, ...rest] = path2; - const node = this.get(key, true); - if (identity.isCollection(node)) - node.addIn(rest, value); - else if (node === undefined && this.schema) - this.set(key, collectionFromPath(this.schema, rest, value)); - else - throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + if (buffer === undefined) { + buffer = arr3; + position = 0; + fieldLength = -1; + } else + buffer = concat2(buffer, arr3); + const bufLength = buffer.length; + let lineStart = 0; + while (position < bufLength) { + if (discardTrailingNewline) { + if (buffer[position] === 10) + lineStart = ++position; + discardTrailingNewline = false; } + let lineEnd = -1; + for (;position < bufLength && lineEnd === -1; ++position) + switch (buffer[position]) { + case 58: + if (fieldLength === -1) + fieldLength = position - lineStart; + break; + case 13: + discardTrailingNewline = true; + case 10: + lineEnd = position; + break; + } + if (lineEnd === -1) + break; + onLine(buffer.subarray(lineStart, lineEnd), fieldLength); + lineStart = position; + fieldLength = -1; } - deleteIn(path2) { - const [key, ...rest] = path2; - if (rest.length === 0) - return this.delete(key); - const node = this.get(key, true); - if (identity.isCollection(node)) - return node.deleteIn(rest); - else - throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); - } - getIn(path2, keepScalar) { - const [key, ...rest] = path2; - const node = this.get(key, true); - if (rest.length === 0) - return !keepScalar && identity.isScalar(node) ? node.value : node; - else - return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined; - } - hasAllNullValues(allowScalar) { - return this.items.every((node) => { - if (!identity.isPair(node)) - return false; - const n3 = node.value; - return n3 == null || allowScalar && identity.isScalar(n3) && n3.value == null && !n3.commentBefore && !n3.comment && !n3.tag; - }); + if (lineStart === bufLength) + buffer = undefined; + else if (lineStart !== 0) { + buffer = buffer.subarray(lineStart); + position -= lineStart; } - hasIn(path2) { - const [key, ...rest] = path2; - if (rest.length === 0) - return this.has(key); - const node = this.get(key, true); - return identity.isCollection(node) ? node.hasIn(rest) : false; + }; +} +function getMessages(onMessage, onId, onRetry) { + let message = newMessage(); + const decoder = new TextDecoder; + return function onLine(line, fieldLength, flush) { + if (flush) { + if (!isEmpty(message)) { + onMessage?.(message); + message = newMessage(); + } + return; } - setIn(path2, value) { - const [key, ...rest] = path2; - if (rest.length === 0) { - this.set(key, value); - } else { - const node = this.get(key, true); - if (identity.isCollection(node)) - node.setIn(rest, value); - else if (node === undefined && this.schema) - this.set(key, collectionFromPath(this.schema, rest, value)); - else - throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + if (line.length === 0) { + onMessage?.(message); + message = newMessage(); + } else if (fieldLength > 0) { + const field = decoder.decode(line.subarray(0, fieldLength)); + const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1); + const value = decoder.decode(line.subarray(valueOffset)); + switch (field) { + case "data": + message.data = message.data ? message.data + ` +` + value : value; + break; + case "event": + message.event = value; + break; + case "id": + onId?.(message.id = value); + break; + case "retry": { + const retry = parseInt(value, 10); + if (!Number.isNaN(retry)) + onRetry?.(message.retry = retry); + break; + } } } - } - exports.Collection = Collection; - exports.collectionFromPath = collectionFromPath; - exports.isEmptyPath = isEmptyPath; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyComment.js -var require_stringifyComment = __commonJS((exports) => { - var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); - function indentComment(comment, indent) { - if (/^\n+$/.test(comment)) - return comment.substring(1); - return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; - } - var lineComment = (str, indent, comment) => str.endsWith(` -`) ? indentComment(comment, indent) : comment.includes(` -`) ? ` -` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; - exports.indentComment = indentComment; - exports.lineComment = lineComment; - exports.stringifyComment = stringifyComment; + }; +} +function concat2(a, b) { + const res = new Uint8Array(a.length + b.length); + res.set(a); + res.set(b, a.length); + return res; +} +function newMessage() { + return { + data: "", + event: "", + id: "", + retry: undefined + }; +} +function convertEventStreamToIterableReadableDataStream(stream2, onMetadataEvent) { + const dataStream = new ReadableStream({ async start(controller) { + const enqueueLine = getMessages((msg) => { + if (msg.event === "error") + throw new Error(msg.data ?? "Unspecified event streaming error."); + else if (msg.event === "metadata") + onMetadataEvent?.(msg); + else if (msg.data) + controller.enqueue(msg.data); + }); + const onLine = (line, fieldLength, flush) => { + enqueueLine(line, fieldLength, flush); + if (flush) + controller.close(); + }; + await getBytes(stream2, getLines(onLine)); + } }); + return IterableReadableStream.fromReadableStream(dataStream); +} +function isEmpty(message) { + return message.data === "" && message.event === "" && message.id === "" && message.retry === undefined; +} +var event_source_parse_exports, EventStreamContentType = "text/event-stream"; +var init_event_source_parse = __esm(() => { + init_runtime2(); + init_stream(); + event_source_parse_exports = /* @__PURE__ */ __exportAll({ + EventStreamContentType: () => EventStreamContentType, + convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, + getBytes: () => getBytes, + getLines: () => getLines, + getMessages: () => getMessages + }); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/foldFlowLines.js -var require_foldFlowLines = __commonJS((exports) => { - var FOLD_FLOW = "flow"; - var FOLD_BLOCK = "block"; - var FOLD_QUOTED = "quoted"; - function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { - if (!lineWidth || lineWidth < 0) - return text; - if (lineWidth < minContentWidth) - minContentWidth = 0; - const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); - if (text.length <= endStep) - return text; - const folds = []; - const escapedFolds = {}; - let end = lineWidth - indent.length; - if (typeof indentAtStart === "number") { - if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) - folds.push(0); - else - end = lineWidth - indentAtStart; - } - let split = undefined; - let prev = undefined; - let overflow = false; - let i = -1; - let escStart = -1; - let escEnd = -1; - if (mode === FOLD_BLOCK) { - i = consumeMoreIndentedLines(text, i, indent.length); - if (i !== -1) - end = i + endStep; - } - for (let ch;ch = text[i += 1]; ) { - if (mode === FOLD_QUOTED && ch === "\\") { - escStart = i; - switch (text[i + 1]) { - case "x": - i += 3; - break; - case "u": - i += 5; - break; - case "U": - i += 9; - break; - default: - i += 1; - } - escEnd = i; - } - if (ch === ` -`) { - if (mode === FOLD_BLOCK) - i = consumeMoreIndentedLines(text, i, indent.length); - end = i + indent.length + endStep; - split = undefined; - } else { - if (ch === " " && prev && prev !== " " && prev !== ` -` && prev !== "\t") { - const next = text[i + 1]; - if (next && next !== " " && next !== ` -` && next !== "\t") - split = i; - } - if (i >= end) { - if (split) { - folds.push(split); - end = split + endStep; - split = undefined; - } else if (mode === FOLD_QUOTED) { - while (prev === " " || prev === "\t") { - prev = ch; - ch = text[i += 1]; - overflow = true; - } - const j = i > escEnd + 1 ? i - 2 : escStart - 1; - if (escapedFolds[j]) - return text; - folds.push(j); - escapedFolds[j] = true; - end = j + endStep; - split = undefined; - } else { - overflow = true; - } - } - } - prev = ch; - } - if (overflow && onOverflow) - onOverflow(); - if (folds.length === 0) - return text; - if (onFold) - onFold(); - let res = text.slice(0, folds[0]); - for (let i2 = 0;i2 < folds.length; ++i2) { - const fold = folds[i2]; - const end2 = folds[i2 + 1] || text.length; - if (fold === 0) - res = ` -${indent}${text.slice(0, end2)}`; - else { - if (mode === FOLD_QUOTED && escapedFolds[fold]) - res += `${text[fold]}\\`; - res += ` -${indent}${text.slice(fold + 1, end2)}`; - } - } - return res; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/format.js +var format_exports; +var init_format3 = __esm(() => { + init_runtime2(); + format_exports = /* @__PURE__ */ __exportAll({}); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/function_calling.js +function convertToOpenAIFunction(tool2, fields) { + const fieldsCopy = typeof fields === "number" ? undefined : fields; + return { + name: tool2.name, + description: tool2.description, + parameters: toJsonSchema(tool2.schema), + ...fieldsCopy?.strict !== undefined ? { strict: fieldsCopy.strict } : {} + }; +} +function convertToOpenAITool(tool2, fields) { + const fieldsCopy = typeof fields === "number" ? undefined : fields; + let toolDef; + if (isLangChainTool(tool2)) + toolDef = { + type: "function", + function: convertToOpenAIFunction(tool2) + }; + else + toolDef = tool2; + if (fieldsCopy?.strict !== undefined) + toolDef.function.strict = fieldsCopy.strict; + return toolDef; +} +var function_calling_exports; +var init_function_calling = __esm(() => { + init_runtime2(); + init_json_schema3(); + init_types4(); + function_calling_exports = /* @__PURE__ */ __exportAll({ + convertToOpenAIFunction: () => convertToOpenAIFunction, + convertToOpenAITool: () => convertToOpenAITool, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams + }); +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/ml-distance/similarities.js +function cosine(a, b) { + let p = 0; + let p2 = 0; + let q2 = 0; + for (let i = 0;i < a.length; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; } - function consumeMoreIndentedLines(text, i, indent) { - let end = i; - let start = i + 1; - let ch = text[start]; - while (ch === " " || ch === "\t") { - if (i < start + indent) { - ch = text[++i]; - } else { - do { - ch = text[++i]; - } while (ch && ch !== ` -`); - end = i; - start = i + 1; - ch = text[start]; + return p / (Math.sqrt(p2) * Math.sqrt(q2)); +} +var init_similarities = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/ml-distance/distances.js +function innerProduct(a, b) { + let ans = 0; + for (let i = 0;i < a.length; i++) + ans += a[i] * b[i]; + return ans; +} +var init_distances = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js +function squaredEuclidean(p, q) { + let d = 0; + for (let i = 0;i < p.length; i++) + d += (p[i] - q[i]) * (p[i] - q[i]); + return d; +} +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} +var init_euclidean = () => {}; + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/math.js +function matrixFunc(X, Y, func) { + if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) + return [[]]; + if (X[0].length !== Y[0].length) + throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); + return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); +} +function normalize2(M, similarity = false) { + const max = matrixMaxVal(M); + return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); +} +function cosineSimilarity(X, Y) { + return matrixFunc(X, Y, cosine); +} +function innerProduct2(X, Y) { + return matrixFunc(X, Y, innerProduct); +} +function euclideanDistance(X, Y) { + return matrixFunc(X, Y, euclidean); +} +function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = 0.5, k = 4) { + if (Math.min(k, embeddingList.length) <= 0) + return []; + const similarityToQuery = cosineSimilarity(Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding], embeddingList)[0]; + const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; + const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; + const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; + while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { + let bestScore = -Infinity; + let bestIndex = -1; + const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); + similarityToQuery.forEach((queryScore, queryScoreIndex) => { + if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) + return; + const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); + const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; + if (score > bestScore) { + bestScore = score; + bestIndex = queryScoreIndex; } - } - return end; + }); + selectedEmbeddings.push(embeddingList[bestIndex]); + selectedEmbeddingsIndexes.push(bestIndex); } - exports.FOLD_BLOCK = FOLD_BLOCK; - exports.FOLD_FLOW = FOLD_FLOW; - exports.FOLD_QUOTED = FOLD_QUOTED; - exports.foldFlowLines = foldFlowLines; + return selectedEmbeddingsIndexes; +} +function argMax(array3) { + if (array3.length === 0) + return { + maxIndex: -1, + maxValue: NaN + }; + let maxValue = array3[0]; + let maxIndex = 0; + for (let i = 1;i < array3.length; i += 1) + if (array3[i] > maxValue) { + maxIndex = i; + maxValue = array3[i]; + } + return { + maxIndex, + maxValue + }; +} +function matrixMaxVal(arrays) { + return arrays.reduce((acc, array3) => Math.max(acc, argMax(array3).maxValue), 0); +} +var math_exports; +var init_math = __esm(() => { + init_runtime2(); + init_similarities(); + init_distances(); + init_euclidean(); + math_exports = /* @__PURE__ */ __exportAll({ + cosineSimilarity: () => cosineSimilarity, + euclideanDistance: () => euclideanDistance, + innerProduct: () => innerProduct2, + matrixFunc: () => matrixFunc, + maximalMarginalRelevance: () => maximalMarginalRelevance, + normalize: () => normalize2 + }); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyString.js -var require_stringifyString = __commonJS((exports) => { - var Scalar = require_Scalar(); - var foldFlowLines = require_foldFlowLines(); - var getFoldOptions = (ctx, isBlock) => ({ - indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, - lineWidth: ctx.options.lineWidth, - minContentWidth: ctx.options.minContentWidth - }); - var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); - function lineLengthOverLimit(str, lineWidth, indentLength) { - if (!lineWidth || lineWidth < 0) - return false; - const limit = lineWidth - indentLength; - const strLen = str.length; - if (strLen <= limit) - return false; - for (let i = 0, start = 0;i < strLen; ++i) { - if (str[i] === ` -`) { - if (i - start > limit) - return true; - start = i + 1; - if (strLen - start <= limit) - return false; - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/ssrf.js +function isIPv4(ip) { + return IPV4_REGEX.test(ip); +} +function isIPv6(ip) { + return expandIpv6(ip) !== null; +} +function isIP(ip) { + return isIPv4(ip) || isIPv6(ip); +} +function parseIp(ip) { + if (isIPv4(ip)) + return ip.split(".").map((octet) => parseInt(octet, 10)); + else if (isIPv6(ip)) { + const expanded = expandIpv6(ip); + if (!expanded) + return null; + const parts = expanded.split(":"); + const result = []; + for (const part of parts) + result.push(parseInt(part, 16)); + return result; + } + return null; +} +function expandIpv6(ip) { + if (!ip || typeof ip !== "string") + return null; + if (!ip.includes(":")) + return null; + if (!/^[0-9a-fA-F:]+$/.test(ip)) + return null; + let normalized = ip; + if (normalized.includes("::")) { + const parts2 = normalized.split("::"); + if (parts2.length > 2) + return null; + const [left, right] = parts2; + const leftParts = left ? left.split(":") : []; + const rightParts = right ? right.split(":") : []; + const missing = 8 - (leftParts.length + rightParts.length); + if (missing < 0) + return null; + const zeros = Array(missing).fill("0"); + normalized = [ + ...leftParts, + ...zeros, + ...rightParts + ].filter((p) => p !== "").join(":"); + } + const parts = normalized.split(":"); + if (parts.length !== 8) + return null; + for (const part of parts) { + if (part.length === 0 || part.length > 4) + return null; + if (!/^[0-9a-fA-F]+$/.test(part)) + return null; + } + return parts.map((p) => p.padStart(4, "0").toLowerCase()).join(":"); +} +function parseCidr(cidr) { + const [addrStr, prefixStr] = cidr.split("/"); + if (!addrStr || !prefixStr) + return null; + const addr = parseIp(addrStr); + if (!addr) + return null; + const prefixLen = parseInt(prefixStr, 10); + if (isNaN(prefixLen)) + return null; + const isIpv6 = isIPv6(addrStr); + if (isIpv6 && prefixLen > 128) + return null; + if (!isIpv6 && prefixLen > 32) + return null; + return { + addr, + prefixLen, + isIpv6 + }; +} +function isIpInCidr(ip, cidr) { + const ipParsed = parseIp(ip); + if (!ipParsed) + return false; + const cidrParsed = parseCidr(cidr); + if (!cidrParsed) + return false; + const isIpv6 = isIPv6(ip); + if (isIpv6 !== cidrParsed.isIpv6) + return false; + const { addr: cidrAddr, prefixLen } = cidrParsed; + if (isIpv6) + for (let i = 0;i < Math.ceil(prefixLen / 16); i++) { + const mask = 65535 << 16 - Math.min(16, prefixLen - i * 16) & 65535; + if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) + return false; + } + else + for (let i = 0;i < Math.ceil(prefixLen / 8); i++) { + const mask = 255 << 8 - Math.min(8, prefixLen - i * 8) & 255; + if ((ipParsed[i] & mask) !== (cidrAddr[i] & mask)) + return false; } + return true; +} +function isPrivateIp(ip) { + if (!isIP(ip)) + return false; + for (const range of PRIVATE_IP_RANGES) + if (isIpInCidr(ip, range)) + return true; + return false; +} +function isCloudMetadata(hostname4, ip) { + if (CLOUD_METADATA_IPS.includes(ip || "")) return true; + const lowerHostname = hostname4.toLowerCase(); + if (CLOUD_METADATA_HOSTNAMES.includes(lowerHostname)) + return true; + return false; +} +function isLocalhost2(hostname4, ip) { + if (ip) { + if (ip === "127.0.0.1" || ip === "::1" || ip === "0.0.0.0") + return true; + if (ip.startsWith("127.")) + return true; } - function doubleQuotedString(value, ctx) { - const json2 = JSON.stringify(value); - if (ctx.options.doubleQuotedAsJSON) - return json2; - const { implicitKey } = ctx; - const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; - const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); - let str = ""; - let start = 0; - for (let i = 0, ch = json2[i];ch; ch = json2[++i]) { - if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") { - str += json2.slice(start, i) + "\\ "; - i += 1; - start = i; - ch = "\\"; + const lowerHostname = hostname4.toLowerCase(); + if (LOCALHOST_NAMES.includes(lowerHostname)) + return true; + return false; +} +function validateSafeUrl(url3, options) { + const allowPrivate = options?.allowPrivate ?? false; + const allowHttp = options?.allowHttp ?? false; + try { + let parsedUrl; + try { + parsedUrl = new URL(url3); + } catch { + throw new Error(`Invalid URL: ${url3}`); + } + const hostname4 = parsedUrl.hostname; + if (!hostname4) + throw new Error("URL missing hostname."); + if (isCloudMetadata(hostname4)) + throw new Error(`URL points to cloud metadata endpoint: ${hostname4}`); + if (isLocalhost2(hostname4)) { + if (!allowPrivate) + throw new Error(`URL points to localhost: ${hostname4}`); + return url3; + } + const scheme = parsedUrl.protocol; + if (scheme !== "http:" && scheme !== "https:") + throw new Error(`Invalid URL scheme: ${scheme}. Only http and https are allowed.`); + if (scheme === "http:" && !allowHttp) + throw new Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true."); + if (isIP(hostname4)) { + const ip = hostname4; + if (isLocalhost2(hostname4, ip)) { + if (!allowPrivate) + throw new Error(`URL points to localhost: ${hostname4}`); + return url3; } - if (ch === "\\") - switch (json2[i + 1]) { - case "u": - { - str += json2.slice(start, i); - const code = json2.substr(i + 2, 4); - switch (code) { - case "0000": - str += "\\0"; - break; - case "0007": - str += "\\a"; - break; - case "000b": - str += "\\v"; - break; - case "001b": - str += "\\e"; - break; - case "0085": - str += "\\N"; - break; - case "00a0": - str += "\\_"; - break; - case "2028": - str += "\\L"; - break; - case "2029": - str += "\\P"; - break; - default: - if (code.substr(0, 2) === "00") - str += "\\x" + code.substr(2); - else - str += json2.substr(i, 6); - } - i += 5; - start = i + 1; - } - break; - case "n": - if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) { - i += 1; - } else { - str += json2.slice(start, i) + ` - -`; - while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') { - str += ` -`; - i += 2; - } - str += indent; - if (json2[i + 2] === " ") - str += "\\"; - i += 1; - start = i + 1; - } - break; - default: - i += 1; - } + if (isCloudMetadata(hostname4, ip)) + throw new Error(`URL resolves to cloud metadata IP: ${ip} (${hostname4})`); + if (isPrivateIp(ip)) { + if (!allowPrivate) + throw new Error(`URL resolves to private IP: ${ip} (${hostname4}). Set allowPrivate: true to allow.`); + } + return url3; } - str = start ? str + json2.slice(start) : json2; - return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); - } - function singleQuotedString(value, ctx) { - if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(` -`) || /[ \t]\n|\n[ \t]/.test(value)) - return doubleQuotedString(value, ctx); - const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); - const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& -${indent}`) + "'"; - return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + return url3; + } catch (error90) { + if (error90 && typeof error90 === "object" && "message" in error90) + throw error90; + throw new Error(`URL validation failed: ${error90}`); } - function quotedString(value, ctx) { - const { singleQuote } = ctx.options; - let qs; - if (singleQuote === false) - qs = doubleQuotedString; - else { - const hasDouble = value.includes('"'); - const hasSingle = value.includes("'"); - if (hasDouble && !hasSingle) - qs = singleQuotedString; - else if (hasSingle && !hasDouble) - qs = doubleQuotedString; - else - qs = singleQuote ? singleQuotedString : doubleQuotedString; - } - return qs(value, ctx); +} +function isSafeUrl(url3, options) { + try { + validateSafeUrl(url3, options); + return true; + } catch { + return false; } - var blockEndNewlines; +} +function isSameOrigin(url1, url22) { try { - blockEndNewlines = new RegExp(`(^|(? -`; - let chomp; - let endStart; - for (endStart = value.length;endStart > 0; --endStart) { - const ch = value[endStart - 1]; - if (ch !== ` -` && ch !== "\t" && ch !== " ") - break; - } - let end = value.substring(endStart); - const endNlPos = end.indexOf(` -`); - if (endNlPos === -1) { - chomp = "-"; - } else if (value === end || endNlPos !== end.length - 1) { - chomp = "+"; - if (onChompKeep) - onChompKeep(); - } else { - chomp = ""; - } - if (end) { - value = value.slice(0, -end.length); - if (end[end.length - 1] === ` -`) - end = end.slice(0, -1); - end = end.replace(blockEndNewlines, `$&${indent}`); +} +var ssrf_exports, PRIVATE_IP_RANGES, CLOUD_METADATA_IPS, CLOUD_METADATA_HOSTNAMES, LOCALHOST_NAMES, IPV4_REGEX; +var init_ssrf = __esm(() => { + init_runtime2(); + ssrf_exports = /* @__PURE__ */ __exportAll({ + isCloudMetadata: () => isCloudMetadata, + isLocalhost: () => isLocalhost2, + isPrivateIp: () => isPrivateIp, + isSafeUrl: () => isSafeUrl, + isSameOrigin: () => isSameOrigin, + validateSafeUrl: () => validateSafeUrl + }); + PRIVATE_IP_RANGES = [ + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "127.0.0.0/8", + "169.254.0.0/16", + "0.0.0.0/8", + "::1/128", + "fc00::/7", + "fe80::/10", + "ff00::/8" + ]; + CLOUD_METADATA_IPS = [ + "169.254.169.254", + "169.254.170.2", + "100.100.100.200" + ]; + CLOUD_METADATA_HOSTNAMES = [ + "metadata.google.internal", + "metadata", + "instance-data" + ]; + LOCALHOST_NAMES = ["localhost", "localhost.localdomain"]; + IPV4_REGEX = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/vectorstores.js +var vectorstores_exports, VectorStoreRetriever, VectorStore, SaveableVectorStore; +var init_vectorstores = __esm(() => { + init_runtime2(); + init_serializable(); + init_retrievers(); + vectorstores_exports = /* @__PURE__ */ __exportAll({ + SaveableVectorStore: () => SaveableVectorStore, + VectorStore: () => VectorStore, + VectorStoreRetriever: () => VectorStoreRetriever + }); + VectorStoreRetriever = class extends BaseRetriever { + static lc_name() { + return "VectorStoreRetriever"; } - let startWithSpace = false; - let startEnd; - let startNlPos = -1; - for (startEnd = 0;startEnd < value.length; ++startEnd) { - const ch = value[startEnd]; - if (ch === " ") - startWithSpace = true; - else if (ch === ` -`) - startNlPos = startEnd; - else - break; + get lc_namespace() { + return ["langchain_core", "vectorstores"]; } - let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); - if (start) { - value = value.substring(start.length); - start = start.replace(/\n+/g, `$&${indent}`); + vectorStore; + k = 4; + searchType = "similarity"; + searchKwargs; + filter; + _vectorstoreType() { + return this.vectorStore._vectorstoreType(); } - const indentSize = indent ? "2" : "1"; - let header = (startWithSpace ? indentSize : "") + chomp; - if (comment) { - header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); - if (onComment) - onComment(); + constructor(fields) { + super(fields); + this.vectorStore = fields.vectorStore; + this.k = fields.k ?? this.k; + this.searchType = fields.searchType ?? this.searchType; + this.filter = fields.filter; + if (fields.searchType === "mmr") + this.searchKwargs = fields.searchKwargs; } - if (!literal2) { - const foldedValue = value.replace(/\n+/g, ` -$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); - let literalFallback = false; - const foldOptions = getFoldOptions(ctx, true); - if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) { - foldOptions.onOverflow = () => { - literalFallback = true; - }; + async _getRelevantDocuments(query3, runManager) { + if (this.searchType === "mmr") { + if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") + throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); + return this.vectorStore.maxMarginalRelevanceSearch(query3, { + k: this.k, + filter: this.filter, + ...this.searchKwargs + }, runManager?.getChild("vectorstore")); } - const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); - if (!literalFallback) - return `>${header} -${indent}${body}`; + return this.vectorStore.similaritySearch(query3, this.k, this.filter, runManager?.getChild("vectorstore")); } - value = value.replace(/\n+/g, `$&${indent}`); - return `|${header} -${indent}${start}${value}${end}`; - } - function plainString(item, ctx, onComment, onChompKeep) { - const { type, value } = item; - const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; - if (implicitKey && value.includes(` -`) || inFlow && /[[\]{},]/.test(value)) { - return quotedString(value, ctx); + async addDocuments(documents, options) { + return this.vectorStore.addDocuments(documents, options); } - if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { - return implicitKey || inFlow || !value.includes(` -`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + }; + VectorStore = class extends Serializable { + lc_namespace = [ + "langchain", + "vectorstores", + this._vectorstoreType() + ]; + embeddings; + constructor(embeddings, dbConfig) { + super(dbConfig); + this.embeddings = embeddings; } - if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(` -`)) { - return blockString(item, ctx, onComment, onChompKeep); + async delete(_params) { + throw new Error("Not implemented."); } - if (containsDocumentMarker(value)) { - if (indent === "") { - ctx.forceBlockIndent = true; - return blockString(item, ctx, onComment, onChompKeep); - } else if (implicitKey && indent === indentStep) { - return quotedString(value, ctx); - } + async similaritySearch(query3, k = 4, filter = undefined, _callbacks = undefined) { + return (await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query3), k, filter)).map((result) => result[0]); } - const str = value.replace(/\n+/g, `$& -${indent}`); - if (actualString) { - const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); - const { compat: compat2, tags } = ctx.doc.schema; - if (tags.some(test) || compat2?.some(test)) - return quotedString(value, ctx); + async similaritySearchWithScore(query3, k = 4, filter = undefined, _callbacks = undefined) { + return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query3), k, filter); } - return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); - } - function stringifyString(item, ctx, onComment, onChompKeep) { - const { implicitKey, inFlow } = ctx; - const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); - let { type } = item; - if (type !== Scalar.Scalar.QUOTE_DOUBLE) { - if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) - type = Scalar.Scalar.QUOTE_DOUBLE; + static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); } - const _stringify3 = (_type) => { - switch (_type) { - case Scalar.Scalar.BLOCK_FOLDED: - case Scalar.Scalar.BLOCK_LITERAL: - return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); - case Scalar.Scalar.QUOTE_DOUBLE: - return doubleQuotedString(ss.value, ctx); - case Scalar.Scalar.QUOTE_SINGLE: - return singleQuotedString(ss.value, ctx); - case Scalar.Scalar.PLAIN: - return plainString(ss, ctx, onComment, onChompKeep); - default: - return null; + static fromDocuments(_docs, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + } + asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { + if (typeof kOrFields === "number") + return new VectorStoreRetriever({ + vectorStore: this, + k: kOrFields, + filter, + tags: [...tags ?? [], this._vectorstoreType()], + metadata, + verbose, + callbacks + }); + else { + const params = { + vectorStore: this, + k: kOrFields?.k, + filter: kOrFields?.filter, + tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], + metadata: kOrFields?.metadata, + verbose: kOrFields?.verbose, + callbacks: kOrFields?.callbacks, + searchType: kOrFields?.searchType + }; + if (kOrFields?.searchType === "mmr") + return new VectorStoreRetriever({ + ...params, + searchKwargs: kOrFields.searchKwargs + }); + return new VectorStoreRetriever({ ...params }); } - }; - let res = _stringify3(type); - if (res === null) { - const { defaultKeyType, defaultStringType } = ctx.options; - const t = implicitKey && defaultKeyType || defaultStringType; - res = _stringify3(t); - if (res === null) - throw new Error(`Unsupported default string type ${t}`); } - return res; - } - exports.stringifyString = stringifyString; + }; + SaveableVectorStore = class extends VectorStore { + static load(_directory, _embeddings) { + throw new Error("Not implemented"); + } + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringify.js -var require_stringify3 = __commonJS((exports) => { - var anchors = require_anchors(); - var identity = require_identity(); - var stringifyComment = require_stringifyComment(); - var stringifyString = require_stringifyString(); - function createStringifyContext(doc2, options) { - const opt = Object.assign({ - blockQuote: true, - commentString: stringifyComment.stringifyComment, - defaultKeyType: null, - defaultStringType: "PLAIN", - directives: null, - doubleQuotedAsJSON: false, - doubleQuotedMinMultiLineLength: 40, - falseStr: "false", - flowCollectionPadding: true, - indentSeq: true, - lineWidth: 80, - minContentWidth: 20, - nullStr: "null", - simpleKeys: false, - singleQuote: null, - trailingComma: false, - trueStr: "true", - verifyAliasOrder: true - }, doc2.schema.toStringOptions, options); - let inFlow; - switch (opt.collectionStyle) { - case "block": - inFlow = false; - break; - case "flow": - inFlow = true; - break; - default: - inFlow = null; - } - return { - anchors: new Set, - doc: doc2, - flowCollectionPadding: opt.flowCollectionPadding ? " " : "", - indent: "", - indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", - inFlow, - options: opt - }; - } - function getTagObject(tags, item) { - if (item.tag) { - const match2 = tags.filter((t) => t.tag === item.tag); - if (match2.length > 0) - return match2.find((t) => t.format === item.format) ?? match2[0]; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/chat_models.js +var FakeChatModel, FakeStreamingChatModel, FakeListChatModel; +var init_chat_models2 = __esm(() => { + init_ai(); + init_outputs(); + init_json_schema3(); + init_base4(); + init_messages(); + init_chat_models(); + FakeChatModel = class extends BaseChatModel { + _combineLLMOutput() { + return []; } - let tagObj = undefined; - let obj; - if (identity.isScalar(item)) { - obj = item.value; - let match2 = tags.filter((t) => t.identify?.(obj)); - if (match2.length > 1) { - const testMatch = match2.filter((t) => t.test); - if (testMatch.length > 0) - match2 = testMatch; - } - tagObj = match2.find((t) => t.format === item.format) ?? match2.find((t) => !t.format); - } else { - obj = item; - tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + _llmType() { + return "fake"; } - if (!tagObj) { - const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); - throw new Error(`Tag not resolved for ${name} value`); + async _generate(messages, options, runManager) { + if (options?.stop?.length) + return { generations: [{ + message: new AIMessage(options.stop[0]), + text: options.stop[0] + }] }; + const text = messages.map((m) => { + if (typeof m.content === "string") + return m.content; + return JSON.stringify(m.content, null, 2); + }).join(` +`); + await runManager?.handleLLMNewToken(text); + return { + generations: [{ + message: new AIMessage(text), + text + }], + llmOutput: {} + }; } - return tagObj; - } - function stringifyProps(node, tagObj, { anchors: anchors$1, doc: doc2 }) { - if (!doc2.directives) - return ""; - const props = []; - const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; - if (anchor && anchors.anchorIsValid(anchor)) { - anchors$1.add(anchor); - props.push(`&${anchor}`); + }; + FakeStreamingChatModel = class FakeStreamingChatModel2 extends BaseChatModel { + sleep = 50; + responses = []; + chunks = []; + toolStyle = "openai"; + thrownErrorString; + tools = []; + constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString, ...rest }) { + super(rest); + this.sleep = sleep; + this.responses = responses; + this.chunks = chunks; + this.toolStyle = toolStyle; + this.thrownErrorString = thrownErrorString; } - const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); - if (tag) - props.push(doc2.directives.tagString(tag)); - return props.join(" "); - } - function stringify4(item, ctx, onComment, onChompKeep) { - if (identity.isPair(item)) - return item.toString(ctx, onComment, onChompKeep); - if (identity.isAlias(item)) { - if (ctx.doc.directives) - return item.toString(ctx); - if (ctx.resolvedAliases?.has(item)) { - throw new TypeError(`Cannot stringify circular structure without alias nodes`); - } else { - if (ctx.resolvedAliases) - ctx.resolvedAliases.add(item); - else - ctx.resolvedAliases = new Set([item]); - item = item.resolve(ctx.doc); - } + _llmType() { + return "fake"; } - let tagObj = undefined; - const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); - tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); - const props = stringifyProps(node, tagObj, ctx); - if (props.length > 0) - ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; - const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); - if (!props) - return str; - return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} -${ctx.indent}${str}`; - } - exports.createStringifyContext = createStringifyContext; - exports.stringify = stringify4; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyPair.js -var require_stringifyPair = __commonJS((exports) => { - var identity = require_identity(); - var Scalar = require_Scalar(); - var stringify4 = require_stringify3(); - var stringifyComment = require_stringifyComment(); - function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { - const { allNullValues, doc: doc2, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; - let keyComment = identity.isNode(key) && key.comment || null; - if (simpleKeys) { - if (keyComment) { - throw new Error("With simple keys, key nodes cannot have comments"); - } - if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") { - const msg = "With simple keys, collection cannot be used as a key value"; - throw new Error(msg); - } + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": + return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": + return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": + return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": + return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: + throw new Error(`Unsupported tool style: ${this.toolStyle}`); + } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeStreamingChatModel2({ + sleep: this.sleep, + responses: this.responses, + chunks: this.chunks, + toolStyle: this.toolStyle, + thrownErrorString: this.thrownErrorString + }); + next.tools = merged; + return next.withConfig({ tools: wrapped }); } - let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); - ctx = Object.assign({}, ctx, { - allNullValues: false, - implicitKey: !explicitKey && (simpleKeys || !allNullValues), - indent: indent + indentStep - }); - let keyCommentDone = false; - let chompKeep = false; - let str = stringify4.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); - if (!explicitKey && !ctx.inFlow && str.length > 1024) { - if (simpleKeys) - throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); - explicitKey = true; + async _generate(messages, _options, _runManager) { + if (this.thrownErrorString) + throw new Error(this.thrownErrorString); + return { generations: [{ + text: "", + message: new AIMessage({ + content: this.responses?.[0]?.content ?? messages[0].content ?? "", + tool_calls: this.chunks?.[0]?.tool_calls + }) + }] }; } - if (ctx.inFlow) { - if (allNullValues || value == null) { - if (keyCommentDone && onComment) - onComment(); - return str === "" ? "?" : explicitKey ? `? ${str}` : str; + async* _streamResponseChunks(_messages, options, runManager) { + if (this.thrownErrorString) + throw new Error(this.thrownErrorString); + if (this.chunks?.length) { + for (const msgChunk of this.chunks) { + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: msgChunk.content, + tool_calls: msgChunk.tool_calls, + additional_kwargs: msgChunk.additional_kwargs ?? {} + }), + text: msgChunk.content?.toString() ?? "" + }); + if (options.signal?.aborted) + break; + yield cg; + await runManager?.handleLLMNewToken(msgChunk.content, undefined, undefined, undefined, undefined, { chunk: cg }); + } + return; + } + const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); + const text = typeof fallback.content === "string" ? fallback.content : ""; + for (const ch of text) { + await new Promise((r) => setTimeout(r, this.sleep)); + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ content: ch }), + text: ch + }); + if (options.signal?.aborted) + break; + yield cg; + await runManager?.handleLLMNewToken(ch, undefined, undefined, undefined, undefined, { chunk: cg }); } - } else if (allNullValues && !simpleKeys || value == null && explicitKey) { - str = `? ${str}`; - if (keyComment && !keyCommentDone) { - str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); - } else if (chompKeep && onChompKeep) - onChompKeep(); - return str; - } - if (keyCommentDone) - keyComment = null; - if (explicitKey) { - if (keyComment) - str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); - str = `? ${str} -${indent}:`; - } else { - str = `${str}:`; - if (keyComment) - str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); - } - let vsb, vcb, valueComment; - if (identity.isNode(value)) { - vsb = !!value.spaceBefore; - vcb = value.commentBefore; - valueComment = value.comment; - } else { - vsb = false; - vcb = null; - valueComment = null; - if (value && typeof value === "object") - value = doc2.createNode(value); } - ctx.implicitKey = false; - if (!explicitKey && !keyComment && identity.isScalar(value)) - ctx.indentAtStart = str.length + 1; - chompKeep = false; - if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) { - ctx.indent = ctx.indent.substring(2); + }; + FakeListChatModel = class FakeListChatModel2 extends BaseChatModel { + static lc_name() { + return "FakeListChatModel"; } - let valueCommentDone = false; - const valueStr = stringify4.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); - let ws = " "; - if (keyComment || vsb || vcb) { - ws = vsb ? ` -` : ""; - if (vcb) { - const cs = commentString(vcb); - ws += ` -${stringifyComment.indentComment(cs, ctx.indent)}`; - } - if (valueStr === "" && !ctx.inFlow) { - if (ws === ` -` && valueComment) - ws = ` - -`; - } else { - ws += ` -${ctx.indent}`; - } - } else if (!explicitKey && identity.isCollection(value)) { - const vs0 = valueStr[0]; - const nl0 = valueStr.indexOf(` -`); - const hasNewline = nl0 !== -1; - const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; - if (hasNewline || !flow) { - let hasPropsLine = false; - if (hasNewline && (vs0 === "&" || vs0 === "!")) { - let sp0 = valueStr.indexOf(" "); - if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { - sp0 = valueStr.indexOf(" ", sp0 + 1); - } - if (sp0 === -1 || nl0 < sp0) - hasPropsLine = true; - } - if (!hasPropsLine) - ws = ` -${ctx.indent}`; - } - } else if (valueStr === "" || valueStr[0] === ` -`) { - ws = ""; + lc_serializable = true; + responses; + i = 0; + sleep; + emitCustomEvent = false; + generationInfo; + tools = []; + toolStyle = "openai"; + constructor(params) { + super(params); + const { responses, sleep, emitCustomEvent, generationInfo } = params; + this.responses = responses; + this.sleep = sleep; + this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; + this.generationInfo = generationInfo; } - str += ws + valueStr; - if (ctx.inFlow) { - if (valueCommentDone && onComment) - onComment(); - } else if (valueComment && !valueCommentDone) { - str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); - } else if (chompKeep && onChompKeep) { - onChompKeep(); + _combineLLMOutput() { + return []; } - return str; - } - exports.stringifyPair = stringifyPair; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/log.js -var require_log = __commonJS((exports) => { - var node_process = __require("process"); - function debug(logLevel, ...messages) { - if (logLevel === "debug") - console.log(...messages); - } - function warn(logLevel, warning) { - if (logLevel === "debug" || logLevel === "warn") { - if (typeof node_process.emitWarning === "function") - node_process.emitWarning(warning); - else - console.warn(warning); + _llmType() { + return "fake-list"; } - } - exports.debug = debug; - exports.warn = warn; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/merge.js -var require_merge = __commonJS((exports) => { - var identity = require_identity(); - var Scalar = require_Scalar(); - var MERGE_KEY = "<<"; - var merge2 = { - identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, - default: "key", - tag: "tag:yaml.org,2002:merge", - test: /^<<$/, - resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { - addToJSMap: addMergeToJSMap - }), - stringify: () => MERGE_KEY - }; - var isMergeKey = (ctx, key) => (merge2.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge2.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge2.tag && tag.default); - function addMergeToJSMap(ctx, map2, value) { - const source = resolveAliasValue(ctx, value); - if (identity.isSeq(source)) - for (const it of source.items) - mergeValue(ctx, map2, it); - else if (Array.isArray(source)) - for (const it of source) - mergeValue(ctx, map2, it); - else - mergeValue(ctx, map2, source); - } - function mergeValue(ctx, map2, value) { - const source = resolveAliasValue(ctx, value); - if (!identity.isMap(source)) - throw new Error("Merge sources must be maps or map aliases"); - const srcMap = source.toJSON(null, ctx, Map); - for (const [key, value2] of srcMap) { - if (map2 instanceof Map) { - if (!map2.has(key)) - map2.set(key, value2); - } else if (map2 instanceof Set) { - map2.add(key); - } else if (!Object.prototype.hasOwnProperty.call(map2, key)) { - Object.defineProperty(map2, key, { - value: value2, - writable: true, - enumerable: true, - configurable: true - }); + async _generate(_messages, options, runManager) { + await this._sleepIfRequested(); + if (options?.thrownErrorString) + throw new Error(options.thrownErrorString); + if (this.emitCustomEvent) + await runManager?.handleCustomEvent("some_test_event", { someval: true }); + if (options?.stop?.length) + return { generations: [this._formatGeneration(options.stop[0])] }; + else { + const response = this._currentResponse(); + this._incrementResponse(); + return { + generations: [this._formatGeneration(response)], + llmOutput: {} + }; } } - return map2; - } - function resolveAliasValue(ctx, value) { - return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; - } - exports.addMergeToJSMap = addMergeToJSMap; - exports.isMergeKey = isMergeKey; - exports.merge = merge2; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/addPairToJSMap.js -var require_addPairToJSMap = __commonJS((exports) => { - var log = require_log(); - var merge2 = require_merge(); - var stringify4 = require_stringify3(); - var identity = require_identity(); - var toJS = require_toJS(); - function addPairToJSMap(ctx, map2, { key, value }) { - if (identity.isNode(key) && key.addToJSMap) - key.addToJSMap(ctx, map2, value); - else if (merge2.isMergeKey(ctx, key)) - merge2.addMergeToJSMap(ctx, map2, value); - else { - const jsKey = toJS.toJS(key, "", ctx); - if (map2 instanceof Map) { - map2.set(jsKey, toJS.toJS(value, jsKey, ctx)); - } else if (map2 instanceof Set) { - map2.add(jsKey); - } else { - const stringKey = stringifyKey(key, jsKey, ctx); - const jsValue = toJS.toJS(value, stringKey, ctx); - if (stringKey in map2) - Object.defineProperty(map2, stringKey, { - value: jsValue, - writable: true, - enumerable: true, - configurable: true - }); - else - map2[stringKey] = jsValue; - } + _formatGeneration(text) { + return { + message: new AIMessage(text), + text + }; } - return map2; - } - function stringifyKey(key, jsKey, ctx) { - if (jsKey === null) - return ""; - if (typeof jsKey !== "object") - return String(jsKey); - if (identity.isNode(key) && ctx?.doc) { - const strCtx = stringify4.createStringifyContext(ctx.doc, {}); - strCtx.anchors = new Set; - for (const node of ctx.anchors.keys()) - strCtx.anchors.add(node.anchor); - strCtx.inFlow = true; - strCtx.inStringifyKey = true; - const strKey = key.toString(strCtx); - if (!ctx.mapKeyWarned) { - let jsonStr = JSON.stringify(strKey); - if (jsonStr.length > 40) - jsonStr = jsonStr.substring(0, 36) + '..."'; - log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); - ctx.mapKeyWarned = true; + async* _streamResponseChunks(_messages, options, runManager) { + const response = this._currentResponse(); + this._incrementResponse(); + if (this.emitCustomEvent) + await runManager?.handleCustomEvent("some_test_event", { someval: true }); + const responseChars = [...response]; + for (let i = 0;i < responseChars.length; i++) { + const text = responseChars[i]; + const isLastChunk = i === responseChars.length - 1; + await this._sleepIfRequested(); + if (options?.thrownErrorString) + throw new Error(options.thrownErrorString); + const chunk = this._createResponseChunk(text, isLastChunk ? this.generationInfo : undefined); + if (options.signal?.aborted) + break; + yield chunk; + runManager?.handleLLMNewToken(text); } - return strKey; - } - return JSON.stringify(jsKey); - } - exports.addPairToJSMap = addPairToJSMap; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/Pair.js -var require_Pair = __commonJS((exports) => { - var createNode = require_createNode(); - var stringifyPair = require_stringifyPair(); - var addPairToJSMap = require_addPairToJSMap(); - var identity = require_identity(); - function createPair(key, value, ctx) { - const k = createNode.createNode(key, undefined, ctx); - const v = createNode.createNode(value, undefined, ctx); - return new Pair(k, v); - } - - class Pair { - constructor(key, value = null) { - Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); - this.key = key; - this.value = value; } - clone(schema) { - let { key, value } = this; - if (identity.isNode(key)) - key = key.clone(schema); - if (identity.isNode(value)) - value = value.clone(schema); - return new Pair(key, value); + async _sleepIfRequested() { + if (this.sleep !== undefined) + await this._sleep(); } - toJSON(_, ctx) { - const pair = ctx?.mapAsMap ? new Map : {}; - return addPairToJSMap.addPairToJSMap(ctx, pair, this); + async _sleep() { + return new Promise((resolve2) => { + setTimeout(() => resolve2(), this.sleep); + }); } - toString(ctx, onComment, onChompKeep) { - return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + _createResponseChunk(text, generationInfo) { + return new ChatGenerationChunk({ + message: new AIMessageChunk({ content: text }), + text, + generationInfo + }); } - } - exports.Pair = Pair; - exports.createPair = createPair; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyCollection.js -var require_stringifyCollection = __commonJS((exports) => { - var identity = require_identity(); - var stringify4 = require_stringify3(); - var stringifyComment = require_stringifyComment(); - function stringifyCollection(collection, ctx, options) { - const flow = ctx.inFlow ?? collection.flow; - const stringify5 = flow ? stringifyFlowCollection : stringifyBlockCollection; - return stringify5(collection, ctx, options); - } - function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { - const { indent, options: { commentString } } = ctx; - const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); - let chompKeep = false; - const lines = []; - for (let i = 0;i < items.length; ++i) { - const item = items[i]; - let comment2 = null; - if (identity.isNode(item)) { - if (!chompKeep && item.spaceBefore) - lines.push(""); - addCommentBefore(ctx, lines, item.commentBefore, chompKeep); - if (item.comment) - comment2 = item.comment; - } else if (identity.isPair(item)) { - const ik = identity.isNode(item.key) ? item.key : null; - if (ik) { - if (!chompKeep && ik.spaceBefore) - lines.push(""); - addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); - } - } - chompKeep = false; - let str2 = stringify4.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); - if (comment2) - str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); - if (chompKeep && comment2) - chompKeep = false; - lines.push(blockItemPrefix + str2); + _currentResponse() { + return this.responses[this.i]; } - let str; - if (lines.length === 0) { - str = flowChars.start + flowChars.end; - } else { - str = lines[0]; - for (let i = 1;i < lines.length; ++i) { - const line = lines[i]; - str += line ? ` -${indent}${line}` : ` -`; - } + _incrementResponse() { + if (this.i < this.responses.length - 1) + this.i += 1; + else + this.i = 0; } - if (comment) { - str += ` -` + stringifyComment.indentComment(commentString(comment), indent); - if (onComment) - onComment(); - } else if (chompKeep && onChompKeep) - onChompKeep(); - return str; - } - function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { - const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; - itemIndent += indentStep; - const itemCtx = Object.assign({}, ctx, { - indent: itemIndent, - inFlow: true, - type: null - }); - let reqNewline = false; - let linesAtValue = 0; - const lines = []; - for (let i = 0;i < items.length; ++i) { - const item = items[i]; - let comment = null; - if (identity.isNode(item)) { - if (item.spaceBefore) - lines.push(""); - addCommentBefore(ctx, lines, item.commentBefore, false); - if (item.comment) - comment = item.comment; - } else if (identity.isPair(item)) { - const ik = identity.isNode(item.key) ? item.key : null; - if (ik) { - if (ik.spaceBefore) - lines.push(""); - addCommentBefore(ctx, lines, ik.commentBefore, false); - if (ik.comment) - reqNewline = true; - } - const iv = identity.isNode(item.value) ? item.value : null; - if (iv) { - if (iv.comment) - comment = iv.comment; - if (iv.commentBefore) - reqNewline = true; - } else if (item.value == null && ik?.comment) { - comment = ik.comment; - } - } - if (comment) - reqNewline = true; - let str = stringify4.stringify(item, itemCtx, () => comment = null); - reqNewline || (reqNewline = lines.length > linesAtValue || str.includes(` -`)); - if (i < items.length - 1) { - str += ","; - } else if (ctx.options.trailingComma) { - if (ctx.options.lineWidth > 0) { - reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); - } - if (reqNewline) { - str += ","; + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": + return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": + return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": + return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": + return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: + throw new Error(`Unsupported tool style: ${this.toolStyle}`); } - } - if (comment) - str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); - lines.push(str); - linesAtValue = lines.length; - } - const { start, end } = flowChars; - if (lines.length === 0) { - return start + end; - } else { - if (!reqNewline) { - const len = lines.reduce((sum, line) => sum + line.length + 2, 2); - reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; - } - if (reqNewline) { - let str = start; - for (const line of lines) - str += line ? ` -${indentStep}${indent}${line}` : ` -`; - return `${str} -${indent}${end}`; - } else { - return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; - } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeListChatModel2({ + responses: this.responses, + sleep: this.sleep, + emitCustomEvent: this.emitCustomEvent, + generationInfo: this.generationInfo + }); + next.tools = merged; + next.toolStyle = this.toolStyle; + next.i = this.i; + return next.withConfig({ tools: wrapped }); } - } - function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { - if (comment && chompKeep) - comment = comment.replace(/^\n+/, ""); - if (comment) { - const ic = stringifyComment.indentComment(commentString(comment), indent); - lines.push(ic.trimStart()); + withStructuredOutput(_params, _config) { + return RunnableLambda.from(async (input) => { + const message = await this.invoke(input); + if (message.tool_calls?.[0]?.args) + return message.tool_calls[0].args; + if (typeof message.content === "string") + return JSON.parse(message.content); + throw new Error("No structured output found"); + }); } - } - exports.stringifyCollection = stringifyCollection; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/YAMLMap.js -var require_YAMLMap = __commonJS((exports) => { - var stringifyCollection = require_stringifyCollection(); - var addPairToJSMap = require_addPairToJSMap(); - var Collection = require_Collection(); - var identity = require_identity(); - var Pair = require_Pair(); - var Scalar = require_Scalar(); - function findPair(items, key) { - const k = identity.isScalar(key) ? key.value : key; - for (const it of items) { - if (identity.isPair(it)) { - if (it.key === key || it.key === k) - return it; - if (identity.isScalar(it.key) && it.key.value === k) - return it; - } +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/embeddings.js +var SyntheticEmbeddings, FakeEmbeddings; +var init_embeddings2 = __esm(() => { + init_embeddings(); + SyntheticEmbeddings = class extends Embeddings { + vectorSize; + constructor(params) { + super(params ?? {}); + this.vectorSize = params?.vectorSize ?? 4; } - return; - } - - class YAMLMap extends Collection.Collection { - static get tagName() { - return "tag:yaml.org,2002:map"; + async embedDocuments(documents) { + return Promise.all(documents.map((doc3) => this.embedQuery(doc3))); } - constructor(schema) { - super(identity.MAP, schema); - this.items = []; + async embedQuery(document2) { + let doc3 = document2; + doc3 = doc3.toLowerCase().replaceAll(/[^a-z ]/g, ""); + const padMod = doc3.length % this.vectorSize; + const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; + const padSize = doc3.length + padGapSize; + doc3 = doc3.padEnd(padSize, " "); + const chunkSize = doc3.length / this.vectorSize; + const docChunk = []; + for (let co = 0;co < doc3.length; co += chunkSize) + docChunk.push(doc3.slice(co, co + chunkSize)); + return docChunk.map((s) => { + let sum = 0; + for (let co = 0;co < s.length; co += 1) + sum += s === " " ? 0 : s.charCodeAt(co); + return sum % 26 / 26; + }); } - static from(schema, obj, ctx) { - const { keepUndefined, replacer } = ctx; - const map2 = new this(schema); - const add = (key, value) => { - if (typeof replacer === "function") - value = replacer.call(obj, key, value); - else if (Array.isArray(replacer) && !replacer.includes(key)) - return; - if (value !== undefined || keepUndefined) - map2.items.push(Pair.createPair(key, value, ctx)); - }; - if (obj instanceof Map) { - for (const [key, value] of obj) - add(key, value); - } else if (obj && typeof obj === "object") { - for (const key of Object.keys(obj)) - add(key, obj[key]); - } - if (typeof schema.sortMapEntries === "function") { - map2.items.sort(schema.sortMapEntries); - } - return map2; + }; + FakeEmbeddings = class extends Embeddings { + constructor(params) { + super(params ?? {}); } - add(pair, overwrite) { - let _pair; - if (identity.isPair(pair)) - _pair = pair; - else if (!pair || typeof pair !== "object" || !("key" in pair)) { - _pair = new Pair.Pair(pair, pair?.value); - } else - _pair = new Pair.Pair(pair.key, pair.value); - const prev = findPair(this.items, _pair.key); - const sortEntries = this.schema?.sortMapEntries; - if (prev) { - if (!overwrite) - throw new Error(`Key ${_pair.key} already set`); - if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) - prev.value.value = _pair.value; - else - prev.value = _pair.value; - } else if (sortEntries) { - const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); - if (i === -1) - this.items.push(_pair); - else - this.items.splice(i, 0, _pair); - } else { - this.items.push(_pair); - } + embedDocuments(documents) { + return Promise.resolve(documents.map(() => [ + 0.1, + 0.2, + 0.3, + 0.4 + ])); } - delete(key) { - const it = findPair(this.items, key); - if (!it) - return false; - const del = this.items.splice(this.items.indexOf(it), 1); - return del.length > 0; + embedQuery(_) { + return Promise.resolve([ + 0.1, + 0.2, + 0.3, + 0.4 + ]); } - get(key, keepScalar) { - const it = findPair(this.items, key); - const node = it?.value; - return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined; + }; +}); + +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/llms.js +var FakeLLM, FakeStreamingLLM; +var init_llms2 = __esm(() => { + init_llms(); + FakeLLM = class extends LLM { + response; + thrownErrorString; + constructor(fields) { + super(fields); + this.response = fields.response; + this.thrownErrorString = fields.thrownErrorString; } - has(key) { - return !!findPair(this.items, key); + _llmType() { + return "fake"; } - set(key, value) { - this.add(new Pair.Pair(key, value), true); + async _call(prompt, _options, runManager) { + if (this.thrownErrorString) + throw new Error(this.thrownErrorString); + const response = this.response ?? prompt; + await runManager?.handleLLMNewToken(response); + return response; } - toJSON(_, ctx, Type) { - const map2 = Type ? new Type : ctx?.mapAsMap ? new Map : {}; - if (ctx?.onCreate) - ctx.onCreate(map2); - for (const item of this.items) - addPairToJSMap.addPairToJSMap(ctx, map2, item); - return map2; + }; + FakeStreamingLLM = class extends LLM { + sleep = 50; + responses; + thrownErrorString; + constructor(fields) { + super(fields); + this.sleep = fields.sleep ?? this.sleep; + this.responses = fields.responses; + this.thrownErrorString = fields.thrownErrorString; } - toString(ctx, onComment, onChompKeep) { - if (!ctx) - return JSON.stringify(this); - for (const item of this.items) { - if (!identity.isPair(item)) - throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + _llmType() { + return "fake"; + } + async _call(prompt) { + if (this.thrownErrorString) + throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + return response ?? prompt; + } + async* _streamResponseChunks(input, _options, runManager) { + if (this.thrownErrorString) + throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + for (const c of response ?? input) { + await new Promise((resolve2) => setTimeout(resolve2, this.sleep)); + yield { + text: c, + generationInfo: {} + }; + await runManager?.handleLLMNewToken(c); } - if (!ctx.allNullValues && this.hasAllNullValues(false)) - ctx = Object.assign({}, ctx, { allNullValues: true }); - return stringifyCollection.stringifyCollection(this, ctx, { - blockItemPrefix: "", - flowChars: { start: "{", end: "}" }, - itemIndent: ctx.indent || "", - onChompKeep, - onComment - }); } - } - exports.YAMLMap = YAMLMap; - exports.findPair = findPair; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/common/map.js -var require_map = __commonJS((exports) => { - var identity = require_identity(); - var YAMLMap = require_YAMLMap(); - var map2 = { - collection: "map", - default: true, - nodeClass: YAMLMap.YAMLMap, - tag: "tag:yaml.org,2002:map", - resolve(map3, onError2) { - if (!identity.isMap(map3)) - onError2("Expected a mapping for this tag"); - return map3; - }, - createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) }; - exports.map = map2; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/nodes/YAMLSeq.js -var require_YAMLSeq = __commonJS((exports) => { - var createNode = require_createNode(); - var stringifyCollection = require_stringifyCollection(); - var Collection = require_Collection(); - var identity = require_identity(); - var Scalar = require_Scalar(); - var toJS = require_toJS(); - - class YAMLSeq extends Collection.Collection { - static get tagName() { - return "tag:yaml.org,2002:seq"; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/message_history.js +var FakeChatMessageHistory, FakeListChatMessageHistory, FakeTracer; +var init_message_history = __esm(() => { + init_ai(); + init_human(); + init_base3(); + init_messages(); + init_chat_history(); + FakeChatMessageHistory = class extends BaseChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); } - constructor(schema) { - super(identity.SEQ, schema); - this.items = []; + async getMessages() { + return this.messages; } - add(value) { - this.items.push(value); + async addMessage(message) { + this.messages.push(message); } - delete(key) { - const idx = asItemIndex(key); - if (typeof idx !== "number") - return false; - const del = this.items.splice(idx, 1); - return del.length > 0; + async addUserMessage(message) { + this.messages.push(new HumanMessage(message)); } - get(key, keepScalar) { - const idx = asItemIndex(key); - if (typeof idx !== "number") - return; - const it = this.items[idx]; - return !keepScalar && identity.isScalar(it) ? it.value : it; + async addAIMessage(message) { + this.messages.push(new AIMessage(message)); } - has(key) { - const idx = asItemIndex(key); - return typeof idx === "number" && idx < this.items.length; + async clear() { + this.messages = []; } - set(key, value) { - const idx = asItemIndex(key); - if (typeof idx !== "number") - throw new Error(`Expected a valid index, not ${key}.`); - const prev = this.items[idx]; - if (identity.isScalar(prev) && Scalar.isScalarValue(value)) - prev.value = value; - else - this.items[idx] = value; + }; + FakeListChatMessageHistory = class extends BaseListChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); } - toJSON(_, ctx) { - const seq = []; - if (ctx?.onCreate) - ctx.onCreate(seq); - let i = 0; - for (const item of this.items) - seq.push(toJS.toJS(item, String(i++), ctx)); - return seq; + async addMessage(message) { + this.messages.push(message); } - toString(ctx, onComment, onChompKeep) { - if (!ctx) - return JSON.stringify(this); - return stringifyCollection.stringifyCollection(this, ctx, { - blockItemPrefix: "- ", - flowChars: { start: "[", end: "]" }, - itemIndent: (ctx.indent || "") + " ", - onChompKeep, - onComment - }); + async getMessages() { + return this.messages; } - static from(schema, obj, ctx) { - const { replacer } = ctx; - const seq = new this(schema); - if (obj && Symbol.iterator in Object(obj)) { - let i = 0; - for (let it of obj) { - if (typeof replacer === "function") { - const key = obj instanceof Set ? it : String(i++); - it = replacer.call(obj, key, it); - } - seq.items.push(createNode.createNode(it, undefined, ctx)); - } - } - return seq; + }; + FakeTracer = class extends BaseTracer { + name = "fake_tracer"; + runs = []; + constructor() { + super(); + } + persistRun(run2) { + this.runs.push(run2); + return Promise.resolve(); } - } - function asItemIndex(key) { - let idx = identity.isScalar(key) ? key.value : key; - if (idx && typeof idx === "string") - idx = Number(idx); - return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; - } - exports.YAMLSeq = YAMLSeq; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/common/seq.js -var require_seq = __commonJS((exports) => { - var identity = require_identity(); - var YAMLSeq = require_YAMLSeq(); - var seq = { - collection: "seq", - default: true, - nodeClass: YAMLSeq.YAMLSeq, - tag: "tag:yaml.org,2002:seq", - resolve(seq2, onError2) { - if (!identity.isSeq(seq2)) - onError2("Expected a sequence for this tag"); - return seq2; - }, - createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) }; - exports.seq = seq; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/common/string.js -var require_string = __commonJS((exports) => { - var stringifyString = require_stringifyString(); - var string4 = { - identify: (value) => typeof value === "string", - default: true, - tag: "tag:yaml.org,2002:str", - resolve: (str) => str, - stringify(item, ctx, onComment, onChompKeep) { - ctx = Object.assign({ actualString: true }, ctx); - return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/output_parsers.js +var FakeSplitIntoListParser; +var init_output_parsers2 = __esm(() => { + init_base6(); + FakeSplitIntoListParser = class extends BaseOutputParser { + lc_namespace = ["tests", "fake"]; + getFormatInstructions() { + return ""; + } + async parse(text) { + return text.split(",").map((value) => value.trim()); } }; - exports.string = string4; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/common/null.js -var require_null = __commonJS((exports) => { - var Scalar = require_Scalar(); - var nullTag = { - identify: (value) => value == null, - createNode: () => new Scalar.Scalar(null), - default: true, - tag: "tag:yaml.org,2002:null", - test: /^(?:~|[Nn]ull|NULL)?$/, - resolve: () => new Scalar.Scalar(null), - stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/retrievers.js +var FakeRetriever; +var init_retrievers2 = __esm(() => { + init_document(); + init_retrievers(); + FakeRetriever = class extends BaseRetriever { + lc_namespace = ["test", "fake"]; + output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; + constructor(fields) { + super(); + this.output = fields?.output ?? this.output; + } + async _getRelevantDocuments(_query) { + return this.output; + } }; - exports.nullTag = nullTag; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/core/bool.js -var require_bool = __commonJS((exports) => { - var Scalar = require_Scalar(); - var boolTag = { - identify: (value) => typeof value === "boolean", - default: true, - tag: "tag:yaml.org,2002:bool", - test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, - resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), - stringify({ source, value }, ctx) { - if (source && boolTag.test.test(source)) { - const sv = source[0] === "t" || source[0] === "T"; - if (value === sv) - return source; - } - return value ? ctx.options.trueStr : ctx.options.falseStr; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/runnables.js +var FakeRunnable; +var init_runnables2 = __esm(() => { + init_base4(); + FakeRunnable = class extends Runnable { + lc_namespace = ["tests", "fake"]; + returnOptions; + constructor(fields) { + super(fields); + this.returnOptions = fields.returnOptions; + } + async invoke(input, options) { + if (this.returnOptions) + return options ?? {}; + return { input }; } }; - exports.boolTag = boolTag; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyNumber.js -var require_stringifyNumber = __commonJS((exports) => { - function stringifyNumber({ format: format3, minFractionDigits, tag, value }) { - if (typeof value === "bigint") - return String(value); - const num = typeof value === "number" ? value : Number(value); - if (!isFinite(num)) - return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; - let n3 = Object.is(value, -0) ? "-0" : JSON.stringify(value); - if (!format3 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n3) && !n3.includes("e")) { - let i = n3.indexOf("."); - if (i < 0) { - i = n3.length; - n3 += "."; - } - let d = minFractionDigits - (n3.length - i - 1); - while (d-- > 0) - n3 += "0"; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/tools.js +var FakeTool; +var init_tools3 = __esm(() => { + init_tools2(); + FakeTool = class extends StructuredTool { + name; + description; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; } - return n3; - } - exports.stringifyNumber = stringifyNumber; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/core/float.js -var require_float = __commonJS((exports) => { - var Scalar = require_Scalar(); - var stringifyNumber = require_stringifyNumber(); - var floatNaN = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, - resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: stringifyNumber.stringifyNumber - }; - var floatExp = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - format: "EXP", - test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, - resolve: (str) => parseFloat(str), - stringify(node) { - const num = Number(node.value); - return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + async _call(arg, _runManager) { + return JSON.stringify(arg); } }; - var float = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, - resolve(str) { - const node = new Scalar.Scalar(parseFloat(str)); - const dot = str.indexOf("."); - if (dot !== -1 && str[str.length - 1] === "0") - node.minFractionDigits = str.length - dot - 1; - return node; - }, - stringify: stringifyNumber.stringifyNumber - }; - exports.float = float; - exports.floatExp = floatExp; - exports.floatNaN = floatNaN; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/core/int.js -var require_int = __commonJS((exports) => { - var stringifyNumber = require_stringifyNumber(); - var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); - var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); - function intStringify(node, radix, prefix) { - const { value } = node; - if (intIdentify(value) && value >= 0) - return prefix + value.toString(radix); - return stringifyNumber.stringifyNumber(node); - } - var intOct = { - identify: (value) => intIdentify(value) && value >= 0, - default: true, - tag: "tag:yaml.org,2002:int", - format: "OCT", - test: /^0o[0-7]+$/, - resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), - stringify: (node) => intStringify(node, 8, "0o") - }; - var int2 = { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - test: /^[-+]?[0-9]+$/, - resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), - stringify: stringifyNumber.stringifyNumber - }; - var intHex = { - identify: (value) => intIdentify(value) && value >= 0, - default: true, - tag: "tag:yaml.org,2002:int", - format: "HEX", - test: /^0x[0-9a-fA-F]+$/, - resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), - stringify: (node) => intStringify(node, 16, "0x") - }; - exports.int = int2; - exports.intHex = intHex; - exports.intOct = intOct; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/core/schema.js -var require_schema = __commonJS((exports) => { - var map2 = require_map(); - var _null4 = require_null(); - var seq = require_seq(); - var string4 = require_string(); - var bool = require_bool(); - var float = require_float(); - var int2 = require_int(); - var schema = [ - map2.map, - seq.seq, - string4.string, - _null4.nullTag, - bool.boolTag, - int2.intOct, - int2.int, - int2.intHex, - float.floatNaN, - float.floatExp, - float.float - ]; - exports.schema = schema; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/json/schema.js -var require_schema2 = __commonJS((exports) => { - var Scalar = require_Scalar(); - var map2 = require_map(); - var seq = require_seq(); - function intIdentify(value) { - return typeof value === "bigint" || Number.isInteger(value); - } - var stringifyJSON = ({ value }) => JSON.stringify(value); - var jsonScalars = [ - { - identify: (value) => typeof value === "string", - default: true, - tag: "tag:yaml.org,2002:str", - resolve: (str) => str, - stringify: stringifyJSON - }, - { - identify: (value) => value == null, - createNode: () => new Scalar.Scalar(null), - default: true, - tag: "tag:yaml.org,2002:null", - test: /^null$/, - resolve: () => null, - stringify: stringifyJSON - }, - { - identify: (value) => typeof value === "boolean", - default: true, - tag: "tag:yaml.org,2002:bool", - test: /^true$|^false$/, - resolve: (str) => str === "true", - stringify: stringifyJSON - }, - { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - test: /^-?(?:0|[1-9][0-9]*)$/, - resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), - stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) - }, - { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, - resolve: (str) => parseFloat(str), - stringify: stringifyJSON +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/tracers.js +var SingleRunExtractor; +var init_tracers = __esm(() => { + init_base3(); + SingleRunExtractor = class extends BaseTracer { + runPromiseResolver; + runPromise; + name = "single_run_extractor"; + constructor() { + super(); + this.runPromise = new Promise((extract) => { + this.runPromiseResolver = extract; + }); } - ]; - var jsonError = { - default: true, - tag: "", - test: /^/, - resolve(str, onError2) { - onError2(`Unresolved plain scalar ${JSON.stringify(str)}`); - return str; + async persistRun(run2) { + this.runPromiseResolver(run2); + } + async extract() { + return this.runPromise; } }; - var schema = [map2.map, seq.seq].concat(jsonScalars, jsonError); - exports.schema = schema; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/binary.js -var require_binary = __commonJS((exports) => { - var node_buffer = __require("buffer"); - var Scalar = require_Scalar(); - var stringifyString = require_stringifyString(); - var binary = { - identify: (value) => value instanceof Uint8Array, - default: false, - tag: "tag:yaml.org,2002:binary", - resolve(src, onError2) { - if (typeof node_buffer.Buffer === "function") { - return node_buffer.Buffer.from(src, "base64"); - } else if (typeof atob === "function") { - const str = atob(src.replace(/[\n\r]/g, "")); - const buffer = new Uint8Array(str.length); - for (let i = 0;i < str.length; ++i) - buffer[i] = str.charCodeAt(i); - return buffer; - } else { - onError2("This environment does not support reading binary tags; either Buffer or atob is required"); - return src; - } - }, - stringify({ comment, type, value }, ctx, onComment, onChompKeep) { - if (!value) - return ""; - const buf = value; - let str; - if (typeof node_buffer.Buffer === "function") { - str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); - } else if (typeof btoa === "function") { - let s = ""; - for (let i = 0;i < buf.length; ++i) - s += String.fromCharCode(buf[i]); - str = btoa(s); - } else { - throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); - } - type ?? (type = Scalar.Scalar.BLOCK_LITERAL); - if (type !== Scalar.Scalar.QUOTE_DOUBLE) { - const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); - const n3 = Math.ceil(str.length / lineWidth); - const lines = new Array(n3); - for (let i = 0, o = 0;i < n3; ++i, o += lineWidth) { - lines[i] = str.substr(o, lineWidth); - } - str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? ` -` : " "); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/vectorstores.js +var FakeVectorStore; +var init_vectorstores2 = __esm(() => { + init_document(); + init_similarities(); + init_vectorstores(); + FakeVectorStore = class FakeVectorStore2 extends VectorStore { + memoryVectors = []; + similarity; + _vectorstoreType() { + return "memory"; + } + constructor(embeddings, { similarity, ...rest } = {}) { + super(embeddings, rest); + this.similarity = similarity ?? cosine; + } + async addDocuments(documents) { + const texts = documents.map(({ pageContent }) => pageContent); + return this.addVectors(await this.embeddings.embedDocuments(texts), documents); + } + async addVectors(vectors, documents) { + const memoryVectors = vectors.map((embedding, idx) => ({ + content: documents[idx].pageContent, + embedding, + metadata: documents[idx].metadata + })); + this.memoryVectors = this.memoryVectors.concat(memoryVectors); + } + async similaritySearchVectorWithScore(query3, k, filter) { + const filterFunction = (memoryVector) => { + if (!filter) + return true; + return filter(new Document({ + metadata: memoryVector.metadata, + pageContent: memoryVector.content + })); + }; + const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); + return filteredMemoryVectors.map((vector, index2) => ({ + similarity: this.similarity(query3, vector.embedding), + index: index2 + })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k).map((search) => [new Document({ + metadata: filteredMemoryVectors[search.index].metadata, + pageContent: filteredMemoryVectors[search.index].content + }), search.similarity]); + } + static async fromTexts(texts, metadatas, embeddings, dbConfig) { + const docs = []; + for (let i = 0;i < texts.length; i += 1) { + const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; + const newDoc = new Document({ + pageContent: texts[i], + metadata + }); + docs.push(newDoc); } - return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + return FakeVectorStore2.fromDocuments(docs, embeddings, dbConfig); + } + static async fromDocuments(docs, embeddings, dbConfig) { + const instance = new this(embeddings, dbConfig); + await instance.addDocuments(docs); + return instance; + } + static async fromExistingIndex(embeddings, dbConfig) { + return new this(embeddings, dbConfig); } }; - exports.binary = binary; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/pairs.js -var require_pairs = __commonJS((exports) => { - var identity = require_identity(); - var Pair = require_Pair(); - var Scalar = require_Scalar(); - var YAMLSeq = require_YAMLSeq(); - function resolvePairs(seq, onError2) { - if (identity.isSeq(seq)) { - for (let i = 0;i < seq.items.length; ++i) { - let item = seq.items[i]; - if (identity.isPair(item)) - continue; - else if (identity.isMap(item)) { - if (item.items.length > 1) - onError2("Each pair must have its own sequence indicator"); - const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); - if (item.commentBefore) - pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} -${pair.key.commentBefore}` : item.commentBefore; - if (item.comment) { - const cn = pair.value ?? pair.key; - cn.comment = cn.comment ? `${item.comment} -${cn.comment}` : item.comment; - } - item = pair; - } - seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); - } - } else - onError2("Expected a sequence for this tag"); - return seq; - } - function createPairs(schema, iterable, ctx) { - const { replacer } = ctx; - const pairs2 = new YAMLSeq.YAMLSeq(schema); - pairs2.tag = "tag:yaml.org,2002:pairs"; - let i = 0; - if (iterable && Symbol.iterator in Object(iterable)) - for (let it of iterable) { - if (typeof replacer === "function") - it = replacer.call(iterable, String(i++), it); - let key, value; - if (Array.isArray(it)) { - if (it.length === 2) { - key = it[0]; - value = it[1]; - } else - throw new TypeError(`Expected [key, value] tuple: ${it}`); - } else if (it && it instanceof Object) { - const keys = Object.keys(it); - if (keys.length === 1) { - key = keys[0]; - value = it[key]; - } else { - throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); - } - } else { - key = it; - } - pairs2.items.push(Pair.createPair(key, value, ctx)); - } - return pairs2; - } - var pairs = { - collection: "seq", - default: false, - tag: "tag:yaml.org,2002:pairs", - resolve: resolvePairs, - createNode: createPairs - }; - exports.createPairs = createPairs; - exports.pairs = pairs; - exports.resolvePairs = resolvePairs; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/utils/testing/index.js +var testing_exports2; +var init_testing2 = __esm(() => { + init_runtime2(); + init_chat_models2(); + init_embeddings2(); + init_llms2(); + init_message_history(); + init_output_parsers2(); + init_retrievers2(); + init_runnables2(); + init_tools3(); + init_tracers(); + init_vectorstores2(); + testing_exports2 = /* @__PURE__ */ __exportAll({ + FakeChatMessageHistory: () => FakeChatMessageHistory, + FakeChatModel: () => FakeChatModel, + FakeEmbeddings: () => FakeEmbeddings, + FakeLLM: () => FakeLLM, + FakeListChatMessageHistory: () => FakeListChatMessageHistory, + FakeListChatModel: () => FakeListChatModel, + FakeRetriever: () => FakeRetriever, + FakeRunnable: () => FakeRunnable, + FakeSplitIntoListParser: () => FakeSplitIntoListParser, + FakeStreamingChatModel: () => FakeStreamingChatModel, + FakeStreamingLLM: () => FakeStreamingLLM, + FakeTool: () => FakeTool, + FakeTracer: () => FakeTracer, + FakeVectorStore: () => FakeVectorStore, + SingleRunExtractor: () => SingleRunExtractor, + SyntheticEmbeddings: () => SyntheticEmbeddings + }); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/omap.js -var require_omap = __commonJS((exports) => { - var identity = require_identity(); - var toJS = require_toJS(); - var YAMLMap = require_YAMLMap(); - var YAMLSeq = require_YAMLSeq(); - var pairs = require_pairs(); +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/import_map.js +var import_map_exports; +var init_import_map = __esm(() => { + init_runtime2(); + init_dist2(); + init_agents(); + init_hash2(); + init_errors3(); + init_serializable(); + init_tool(); + init_caches(); + init_uuid(); + init_env(); + init_base2(); + init_base3(); + init_console(); + init_tracer_langchain(); + init_promises(); + init_manager(); + init_singletons(); + init_stream(); + init_log_stream(); + init_outputs(); + init_async_caller2(); + init_standard_schema(); + init_json_schema3(); + init_graph(); + init_messages(); + init_chat_history(); + init_documents(); + init_base7(); + init_langsmith2(); + init_embeddings(); + init_example_selectors(); + init_indexing(); + init_prompt_values(); + init_tiktoken(); + init_base5(); + init_runnables(); + init_json_patch(); + init_output_parsers(); + init_types3(); + init_structured_output(); + init_stream2(); + init_compat2(); + init_chat_models(); + init_event(); + init_llms(); + init_profile(); + init_memory(); + init_openai_functions(); + init_openai_tools(); + init_prompts2(); + init_document_compressors(); + init_retrievers(); + init_stores(); + init_structured_query(); + init_testing(); + init_tools2(); + init_run_collector(); + init_stream3(); + init_chunk_array(); + init_context2(); + init_event_source_parse(); + init_format3(); + init_function_calling(); + init_math(); + init_ssrf(); + init_vectorstores(); + init_testing2(); + import_map_exports = /* @__PURE__ */ __exportAll({ + agents: () => agents_exports, + caches: () => caches_exports, + callbacks__base: () => base_exports, + callbacks__manager: () => manager_exports, + callbacks__promises: () => promises_exports, + chat_history: () => chat_history_exports, + document_loaders__base: () => base_exports4, + document_loaders__langsmith: () => langsmith_exports, + documents: () => documents_exports, + embeddings: () => embeddings_exports, + errors: () => errors_exports, + example_selectors: () => example_selectors_exports, + index: () => src_exports, + indexing: () => indexing_exports, + language_models__base: () => base_exports3, + language_models__chat_models: () => chat_models_exports, + language_models__compat: () => compat_exports, + language_models__event: () => event_exports, + language_models__llms: () => llms_exports, + language_models__profile: () => profile_exports, + language_models__stream: () => stream_exports2, + language_models__structured_output: () => structured_output_exports, + load__serializable: () => serializable_exports, + memory: () => memory_exports, + messages: () => messages_exports, + messages__tool: () => tool_exports, + output_parsers: () => output_parsers_exports, + output_parsers__openai_functions: () => openai_functions_exports, + output_parsers__openai_tools: () => openai_tools_exports, + outputs: () => outputs_exports, + prompt_values: () => prompt_values_exports, + prompts: () => prompts_exports, + retrievers: () => retrievers_exports, + retrievers__document_compressors: () => document_compressors_exports, + runnables: () => runnables_exports, + runnables__graph: () => graph_exports, + singletons: () => singletons_exports, + stores: () => stores_exports, + structured_query: () => structured_query_exports, + testing: () => testing_exports, + tools: () => tools_exports, + tracers__base: () => base_exports2, + tracers__console: () => console_exports, + tracers__log_stream: () => log_stream_exports, + tracers__run_collector: () => run_collector_exports, + tracers__tracer_langchain: () => tracer_langchain_exports, + types__stream: () => stream_exports3, + utils__async_caller: () => async_caller_exports, + utils__chunk_array: () => chunk_array_exports, + utils__context: () => context_exports, + utils__env: () => env_exports, + utils__event_source_parse: () => event_source_parse_exports, + utils__format: () => format_exports, + utils__function_calling: () => function_calling_exports, + utils__hash: () => hash_exports, + utils__json_patch: () => json_patch_exports, + utils__json_schema: () => json_schema_exports, + utils__math: () => math_exports, + utils__ssrf: () => ssrf_exports, + utils__standard_schema: () => standard_schema_exports, + utils__stream: () => stream_exports, + utils__testing: () => testing_exports2, + utils__tiktoken: () => tiktoken_exports, + utils__types: () => types_exports, + utils__uuid: () => uuid_exports, + vectorstores: () => vectorstores_exports + }); +}); - class YAMLOMap extends YAMLSeq.YAMLSeq { - constructor() { - super(); - this.add = YAMLMap.YAMLMap.prototype.add.bind(this); - this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); - this.get = YAMLMap.YAMLMap.prototype.get.bind(this); - this.has = YAMLMap.YAMLMap.prototype.has.bind(this); - this.set = YAMLMap.YAMLMap.prototype.set.bind(this); - this.tag = YAMLOMap.tag; - } - toJSON(_, ctx) { - if (!ctx) - return super.toJSON(_); - const map2 = new Map; - if (ctx?.onCreate) - ctx.onCreate(map2); - for (const pair of this.items) { - let key, value; - if (identity.isPair(pair)) { - key = toJS.toJS(pair.key, "", ctx); - value = toJS.toJS(pair.value, key, ctx); - } else { - key = toJS.toJS(pair, "", ctx); - } - if (map2.has(key)) - throw new Error("Ordered maps must not include duplicate keys"); - map2.set(key, value); - } - return map2; +// ../../node_modules/.pnpm/@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentel_u3imeeuhhdzvgksuk7cdlxkm4u/node_modules/@langchain/core/dist/load/index.js +function combineAliasesAndInvert(constructor) { + const aliases = {}; + for (let current = constructor;current && current.prototype; current = Object.getPrototypeOf(current)) + Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); + return Object.entries(aliases).reduce((acc, [key, value]) => { + acc[value] = key; + return acc; + }, {}); +} +async function reviver(value) { + const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path: path2, depth, maxDepth } = this; + const pathStr = path2.join("."); + if (depth > maxDepth) + throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`); + if (typeof value !== "object" || value == null) + return value; + if (Array.isArray(value)) + return Promise.all(value.map((v, i) => reviver.call({ + ...this, + path: [...path2, `${i}`], + depth: depth + 1 + }, v))); + const record3 = value; + if (isEscapedObject(record3)) + return unescapeValue(record3); + if ("lc" in record3 && "type" in record3 && "id" in record3 && record3.lc === 1 && record3.type === "secret") { + const [key] = record3.id; + if (key in secretsMap) + return secretsMap[key]; + else if (secretsFromEnv) { + const secretValueInEnv = getEnvironmentVariable(key); + if (secretValueInEnv) + return secretValueInEnv; } - static from(schema, iterable, ctx) { - const pairs$1 = pairs.createPairs(schema, iterable, ctx); - const omap2 = new this; - omap2.items = pairs$1.items; - return omap2; + throw new Error(`Missing secret "${key}" at ${pathStr}`); + } + if ("lc" in record3 && "type" in record3 && "id" in record3 && record3.lc === 1 && record3.type === "not_implemented") { + const str = JSON.stringify(record3); + throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); + } + if ("lc" in record3 && "type" in record3 && "id" in record3 && "kwargs" in record3 && record3.lc === 1 && record3.type === "constructor") { + const serialized = record3; + const str = JSON.stringify(serialized); + const [name, ...namespaceReverse] = serialized.id.slice().reverse(); + const namespace = namespaceReverse.reverse(); + const importMaps = { + langchain_core: import_map_exports, + langchain: importMap + }; + let module = null; + const optionalImportNamespaceAliases = [namespace.join("/")]; + if (namespace[0] === "langchain_community") + optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); + const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => (alias in optionalImportsMap)); + if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) + if (matchingNamespaceAlias !== undefined) + module = await optionalImportsMap[matchingNamespaceAlias]; + else + throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); + else { + let finalImportMap; + if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { + finalImportMap = importMaps[namespace[0]]; + namespace.shift(); + } else + throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + if (namespace.length === 0) + throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + let importMapKey; + do { + importMapKey = namespace.join("__"); + if (importMapKey in finalImportMap) + break; + else + namespace.pop(); + } while (namespace.length > 0); + if (importMapKey in finalImportMap) + module = finalImportMap[importMapKey]; } + if (typeof module !== "object" || module === null) + throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); + if (typeof builder !== "function") + throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); + const instance = new builder(mapKeys(await reviver.call({ + ...this, + path: [...path2, "kwargs"], + depth: depth + 1 + }, serialized.kwargs), keyFromJson, combineAliasesAndInvert(builder))); + Object.defineProperty(instance.constructor, "name", { value: name }); + return instance; } - YAMLOMap.tag = "tag:yaml.org,2002:omap"; - var omap = { - collection: "seq", - identify: (value) => value instanceof Map, - nodeClass: YAMLOMap, - default: false, - tag: "tag:yaml.org,2002:omap", - resolve(seq, onError2) { - const pairs$1 = pairs.resolvePairs(seq, onError2); - const seenKeys = []; - for (const { key } of pairs$1.items) { - if (identity.isScalar(key)) { - if (seenKeys.includes(key.value)) { - onError2(`Ordered maps must not include duplicate keys: ${key.value}`); - } else { - seenKeys.push(key.value); - } - } - } - return Object.assign(new YAMLOMap, pairs$1); - }, - createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) + const result = {}; + for (const [key, val] of Object.entries(record3)) + result[key] = await reviver.call({ + ...this, + path: [...path2, key], + depth: depth + 1 + }, val); + return result; +} +async function load(text, options) { + const json3 = JSON.parse(text); + const context2 = { + optionalImportsMap: options?.optionalImportsMap ?? {}, + optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [], + secretsMap: options?.secretsMap ?? {}, + secretsFromEnv: options?.secretsFromEnv ?? false, + importMap: options?.importMap ?? {}, + path: ["$"], + depth: 0, + maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH }; - exports.YAMLOMap = YAMLOMap; - exports.omap = omap; + return reviver.call(context2, json3); +} +var DEFAULT_MAX_DEPTH = 50; +var init_load = __esm(() => { + init_map_keys(); + init_validation(); + init_serializable(); + init_env(); + init_import_constants(); + init_import_map(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/bool.js -var require_bool2 = __commonJS((exports) => { - var Scalar = require_Scalar(); - function boolStringify({ value, source }, ctx) { - const boolObj = value ? trueTag : falseTag; - if (source && boolObj.test.test(source)) - return source; - return value ? ctx.options.trueStr : ctx.options.falseStr; - } - var trueTag = { - identify: (value) => value === true, - default: true, - tag: "tag:yaml.org,2002:bool", - test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, - resolve: () => new Scalar.Scalar(true), - stringify: boolStringify - }; - var falseTag = { - identify: (value) => value === false, - default: true, - tag: "tag:yaml.org,2002:bool", - test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, - resolve: () => new Scalar.Scalar(false), - stringify: boolStringify +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js +function isLangChainSerializedObject(value) { + return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); +} +async function _reviver(value) { + if (value && typeof value === "object") + if (Array.isArray(value)) + return await Promise.all(value.map((item) => _reviver(item))); + else { + const revivedObj = {}; + for (const [k, v] of Object.entries(value)) + revivedObj[k] = await _reviver(v); + if (revivedObj.lc === 2 && revivedObj.type === "undefined") + return; + else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) + try { + const constructorName = revivedObj.id[revivedObj.id.length - 1]; + let constructor; + switch (constructorName) { + case "Set": + constructor = Set; + break; + case "Map": + constructor = Map; + break; + case "RegExp": + constructor = RegExp; + break; + case "Error": + constructor = Error; + break; + case "Uint8Array": + constructor = Uint8Array; + break; + default: + return revivedObj; + } + if (revivedObj.method) + return constructor[revivedObj.method](...revivedObj.args || []); + else + return new constructor(...revivedObj.args || []); + } catch { + return revivedObj; + } + else if (isLangChainSerializedObject(revivedObj)) + return load(JSON.stringify(revivedObj)); + return revivedObj; + } + return value; +} +function _encodeConstructorArgs(constructor, method, args, kwargs) { + return { + lc: 2, + type: "constructor", + id: [constructor.name], + method: method ?? null, + args: args ?? [], + kwargs: kwargs ?? {} }; - exports.falseTag = falseTag; - exports.trueTag = trueTag; +} +function _default5(obj) { + if (obj === undefined) + return { + lc: 2, + type: "undefined" + }; + else if (obj instanceof Set || obj instanceof Map) + return _encodeConstructorArgs(obj.constructor, undefined, [Array.from(obj)]); + else if (obj instanceof RegExp) + return _encodeConstructorArgs(RegExp, undefined, [obj.source, obj.flags]); + else if (obj instanceof Error) + return _encodeConstructorArgs(obj.constructor, undefined, [obj.message]); + else if (obj?.lg_name === "Send") + return { + node: obj.node, + args: obj.args + }; + else if (obj instanceof Uint8Array) + return _encodeConstructorArgs(Uint8Array, "from", [Array.from(obj)]); + else + return obj; +} +var JsonPlusSerializer = class { + _dumps(obj) { + return new TextEncoder().encode(stringify4(obj, (_, value) => { + return _default5(value); + })); + } + async dumpsTyped(obj) { + if (obj instanceof Uint8Array) + return ["bytes", obj]; + else + return ["json", this._dumps(obj)]; + } + async _loads(data) { + return _reviver(JSON.parse(data)); + } + async loadsTyped(type, data) { + if (type === "bytes") + return typeof data === "string" ? new TextEncoder().encode(data) : data; + else if (type === "json") + return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); + else + throw new Error(`Unknown serialization type: ${type}`); + } +}; +var init_jsonplus = __esm(() => { + init_fast_safe_stringify2(); + init_load(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/float.js -var require_float2 = __commonJS((exports) => { - var Scalar = require_Scalar(); - var stringifyNumber = require_stringifyNumber(); - var floatNaN = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, - resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, - stringify: stringifyNumber.stringifyNumber +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/base.js +function deepCopy(obj) { + if (typeof obj !== "object" || obj === null) + return obj; + const newObj = Array.isArray(obj) ? [] : {}; + for (const key in obj) + if (Object.prototype.hasOwnProperty.call(obj, key)) + newObj[key] = deepCopy(obj[key]); + return newObj; +} +function emptyCheckpoint() { + return { + v: 4, + id: uuid63(-2), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: {}, + channel_versions: {}, + versions_seen: {} }; - var floatExp = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - format: "EXP", - test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, - resolve: (str) => parseFloat(str.replace(/_/g, "")), - stringify(node) { - const num = Number(node.value); - return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); - } +} +function copyCheckpoint(checkpoint) { + return { + v: checkpoint.v, + id: checkpoint.id, + ts: checkpoint.ts, + channel_values: { ...checkpoint.channel_values }, + channel_versions: { ...checkpoint.channel_versions }, + versions_seen: deepCopy(checkpoint.versions_seen) }; - var float = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, - resolve(str) { - const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); - const dot = str.indexOf("."); - if (dot !== -1) { - const f3 = str.substring(dot + 1).replace(/_/g, ""); - if (f3[f3.length - 1] === "0") - node.minFractionDigits = f3.length; - } - return node; - }, - stringify: stringifyNumber.stringifyNumber +} +function compareChannelVersions(a, b) { + if (typeof a === "number" && typeof b === "number") + return Math.sign(a - b); + return String(a).localeCompare(String(b)); +} +function maxChannelVersion(...versions3) { + return versions3.reduce((max, version6, idx) => { + if (idx === 0) + return version6; + return compareChannelVersions(max, version6) >= 0 ? max : version6; + }); +} +function getCheckpointId(config3) { + return config3.configurable?.checkpoint_id || config3.configurable?.thread_ts || ""; +} +var BaseCheckpointSaver = class { + serde = new JsonPlusSerializer; + constructor(serde) { + this.serde = serde || this.serde; + } + async get(config3) { + const value = await this.getTuple(config3); + return value ? value.checkpoint : undefined; + } + getNextVersion(current) { + if (typeof current === "string") + throw new Error("Please override this method to use string versions."); + return current !== undefined && typeof current === "number" ? current + 1 : 1; + } +}, WRITES_IDX_MAP; +var init_base12 = __esm(() => { + init_id3(); + init_types5(); + init_jsonplus(); + WRITES_IDX_MAP = { + [ERROR3]: -1, + [SCHEDULED]: -2, + [INTERRUPT2]: -3, + [RESUME2]: -4 }; - exports.float = float; - exports.floatExp = floatExp; - exports.floatNaN = floatNaN; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/int.js -var require_int2 = __commonJS((exports) => { - var stringifyNumber = require_stringifyNumber(); - var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); - function intResolve(str, offset, radix, { intAsBigInt }) { - const sign = str[0]; - if (sign === "-" || sign === "+") - offset += 1; - str = str.substring(offset).replace(/_/g, ""); - if (intAsBigInt) { - switch (radix) { - case 2: - str = `0b${str}`; - break; - case 8: - str = `0o${str}`; - break; - case 16: - str = `0x${str}`; - break; - } - const n4 = BigInt(str); - return sign === "-" ? BigInt(-1) * n4 : n4; - } - const n3 = parseInt(str, radix); - return sign === "-" ? -1 * n3 : n3; - } - function intStringify(node, radix, prefix) { - const { value } = node; - if (intIdentify(value)) { - const str = value.toString(radix); - return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; - } - return stringifyNumber.stringifyNumber(node); +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/memory.js +function assertSafeStorageKey(field, value, options = {}) { + const { allowEmpty = false } = options; + if (typeof value !== "string") { + const observed = value === null ? "null" : value === undefined ? "undefined" : Array.isArray(value) ? "array" : typeof value; + throw new Error(`Invalid configurable value for key "${field}": expected a string identifier (got ${observed}). This guard protects MemorySaver from prototype pollution.`); } - var intBin = { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - format: "BIN", - test: /^[-+]?0b[0-1_]+$/, - resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), - stringify: (node) => intStringify(node, 2, "0b") - }; - var intOct = { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - format: "OCT", - test: /^[-+]?0[0-7_]+$/, - resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), - stringify: (node) => intStringify(node, 8, "0") + if (!allowEmpty && value === "") + throw new Error(`Invalid configurable value for key "${field}": empty string is not permitted as an in-memory storage key.`); + if (POLLUTION_KEYS.has(value)) + throw new Error(`Invalid configurable value for key "${field}": value "${value}" is reserved (would mutate Object.prototype). This guard protects MemorySaver from prototype pollution.`); +} +function _generateKey(threadId, checkpointNamespace, checkpointId) { + return JSON.stringify([ + threadId, + checkpointNamespace, + checkpointId + ]); +} +function _parseKey(key) { + const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key); + return { + threadId, + checkpointNamespace, + checkpointId }; - var int2 = { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - test: /^[-+]?[0-9][0-9_]*$/, - resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), - stringify: stringifyNumber.stringifyNumber - }; - var intHex = { - identify: intIdentify, - default: true, - tag: "tag:yaml.org,2002:int", - format: "HEX", - test: /^[-+]?0x[0-9a-fA-F_]+$/, - resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), - stringify: (node) => intStringify(node, 16, "0x") - }; - exports.int = int2; - exports.intBin = intBin; - exports.intHex = intHex; - exports.intOct = intOct; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/set.js -var require_set = __commonJS((exports) => { - var identity = require_identity(); - var Pair = require_Pair(); - var YAMLMap = require_YAMLMap(); - - class YAMLSet extends YAMLMap.YAMLMap { - constructor(schema) { - super(schema); - this.tag = YAMLSet.tag; - } - add(key) { - let pair; - if (identity.isPair(key)) - pair = key; - else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) - pair = new Pair.Pair(key.key, null); - else - pair = new Pair.Pair(key, null); - const prev = YAMLMap.findPair(this.items, pair.key); - if (!prev) - this.items.push(pair); +} +var POLLUTION_KEYS, MemorySaver; +var init_memory2 = __esm(() => { + init_types5(); + init_base12(); + POLLUTION_KEYS = new Set([ + "__proto__", + "constructor", + "prototype" + ]); + MemorySaver = class extends BaseCheckpointSaver { + storage = Object.create(null); + writes = Object.create(null); + constructor(serde) { + super(serde); } - get(key, keepPair) { - const pair = YAMLMap.findPair(this.items, key); - return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; + async _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) { + const deseriablizableCheckpoint = mutableCheckpoint; + const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId); + const pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS2).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped("json", writes))); + deseriablizableCheckpoint.channel_values ??= {}; + deseriablizableCheckpoint.channel_values[TASKS2] = pendingSends; + deseriablizableCheckpoint.channel_versions ??= {}; + deseriablizableCheckpoint.channel_versions[TASKS2] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(undefined); } - set(key, value) { - if (typeof value !== "boolean") - throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); - const prev = YAMLMap.findPair(this.items, key); - if (prev && !value) { - this.items.splice(this.items.indexOf(prev), 1); - } else if (!prev && value) { - this.items.push(new Pair.Pair(key)); + async getTuple(config3) { + const thread_id = config3.configurable?.thread_id; + const checkpoint_ns = config3.configurable?.checkpoint_ns ?? ""; + let checkpoint_id = getCheckpointId(config3); + if (thread_id !== undefined) + assertSafeStorageKey("thread_id", thread_id); + assertSafeStorageKey("checkpoint_ns", checkpoint_ns, { allowEmpty: true }); + if (checkpoint_id) + assertSafeStorageKey("checkpoint_id", checkpoint_id); + if (checkpoint_id) { + const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id]; + if (saved !== undefined) { + const [checkpoint, metadata, parentCheckpointId] = saved; + const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) + await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); + const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const checkpointTuple = { + config: config3, + checkpoint: deserializedCheckpoint, + metadata: await this.serde.loadsTyped("json", metadata), + pendingWrites + }; + if (parentCheckpointId !== undefined) + checkpointTuple.parentConfig = { configurable: { + thread_id, + checkpoint_ns, + checkpoint_id: parentCheckpointId + } }; + return checkpointTuple; + } + } else { + const checkpoints = this.storage[thread_id]?.[checkpoint_ns]; + if (checkpoints !== undefined) { + checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0]; + const [checkpoint, metadata, parentCheckpointId] = checkpoints[checkpoint_id]; + const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) + await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); + const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const checkpointTuple = { + config: { configurable: { + thread_id, + checkpoint_id, + checkpoint_ns + } }, + checkpoint: deserializedCheckpoint, + metadata: await this.serde.loadsTyped("json", metadata), + pendingWrites + }; + if (parentCheckpointId !== undefined) + checkpointTuple.parentConfig = { configurable: { + thread_id, + checkpoint_ns, + checkpoint_id: parentCheckpointId + } }; + return checkpointTuple; + } } } - toJSON(_, ctx) { - return super.toJSON(_, ctx, Set); + async* list(config3, options) { + let { before, limit, filter } = options ?? {}; + if (config3.configurable?.thread_id !== undefined) + assertSafeStorageKey("thread_id", config3.configurable.thread_id); + if (config3.configurable?.checkpoint_ns !== undefined) + assertSafeStorageKey("checkpoint_ns", config3.configurable.checkpoint_ns, { allowEmpty: true }); + if (config3.configurable?.checkpoint_id) + assertSafeStorageKey("checkpoint_id", config3.configurable.checkpoint_id); + if (before?.configurable?.checkpoint_id) + assertSafeStorageKey("checkpoint_id", before.configurable.checkpoint_id); + const threadIds = config3.configurable?.thread_id ? [config3.configurable?.thread_id] : Object.keys(this.storage); + const configCheckpointNamespace = config3.configurable?.checkpoint_ns; + const configCheckpointId = config3.configurable?.checkpoint_id; + for (const threadId of threadIds) + for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) { + if (configCheckpointNamespace !== undefined && checkpointNamespace !== configCheckpointNamespace) + continue; + const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {}; + const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0])); + for (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) { + if (configCheckpointId && checkpointId !== configCheckpointId) + continue; + if (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) + continue; + const metadata = await this.serde.loadsTyped("json", metadataStr); + if (filter && !Object.entries(filter).every(([key2, value]) => metadata[key2] === value)) + continue; + if (limit !== undefined) { + if (limit <= 0) + break; + limit -= 1; + } + const key = _generateKey(threadId, checkpointNamespace, checkpointId); + const writes = Object.values(this.writes[key] || {}); + const pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== undefined) + await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId); + const checkpointTuple = { + config: { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: checkpointId + } }, + checkpoint: deserializedCheckpoint, + metadata, + pendingWrites + }; + if (parentCheckpointId !== undefined) + checkpointTuple.parentConfig = { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: parentCheckpointId + } }; + yield checkpointTuple; + } + } } - toString(ctx, onComment, onChompKeep) { - if (!ctx) - return JSON.stringify(this); - if (this.hasAllNullValues(true)) - return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); - else - throw new Error("Set items must all have null values"); + async put(config3, checkpoint, metadata) { + const preparedCheckpoint = copyCheckpoint(checkpoint); + const threadId = config3.configurable?.thread_id; + const checkpointNamespace = config3.configurable?.checkpoint_ns ?? ""; + if (threadId === undefined) + throw new Error('Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })'); + assertSafeStorageKey("thread_id", threadId); + assertSafeStorageKey("checkpoint_ns", checkpointNamespace, { allowEmpty: true }); + assertSafeStorageKey("checkpoint_id", checkpoint.id); + if (!this.storage[threadId]) + this.storage[threadId] = Object.create(null); + if (!this.storage[threadId][checkpointNamespace]) + this.storage[threadId][checkpointNamespace] = Object.create(null); + const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]); + this.storage[threadId][checkpointNamespace][checkpoint.id] = [ + serializedCheckpoint, + serializedMetadata, + config3.configurable?.checkpoint_id + ]; + return { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: checkpoint.id + } }; } - static from(schema, iterable, ctx) { - const { replacer } = ctx; - const set3 = new this(schema); - if (iterable && Symbol.iterator in Object(iterable)) - for (let value of iterable) { - if (typeof replacer === "function") - value = replacer.call(iterable, value, value); - set3.items.push(Pair.createPair(value, null, ctx)); - } - return set3; + async putWrites(config3, writes, taskId) { + const threadId = config3.configurable?.thread_id; + const checkpointNamespace = config3.configurable?.checkpoint_ns; + const checkpointId = config3.configurable?.checkpoint_id; + if (threadId === undefined) + throw new Error('Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property. When using a checkpointer, you must pass a "thread_id" so the checkpointer knows which conversation thread to persist state for. Example: graph.stream(input, { configurable: { thread_id: "my-thread-id" } })'); + if (checkpointId === undefined) + throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.`); + assertSafeStorageKey("thread_id", threadId); + assertSafeStorageKey("checkpoint_ns", checkpointNamespace, { allowEmpty: true }); + assertSafeStorageKey("checkpoint_id", checkpointId); + assertSafeStorageKey("task_id", taskId); + const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId); + const outerWrites_ = this.writes[outerKey]; + if (this.writes[outerKey] === undefined) + this.writes[outerKey] = Object.create(null); + await Promise.all(writes.map(async ([channel, value], idx) => { + const [, serializedValue] = await this.serde.dumpsTyped(value); + const innerKey = [taskId, WRITES_IDX_MAP[channel] || idx]; + const innerKeyStr = `${innerKey[0]},${innerKey[1]}`; + if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) + return; + this.writes[outerKey][innerKeyStr] = [ + taskId, + channel, + serializedValue + ]; + })); } - } - YAMLSet.tag = "tag:yaml.org,2002:set"; - var set2 = { - collection: "map", - identify: (value) => value instanceof Set, - nodeClass: YAMLSet, - default: false, - tag: "tag:yaml.org,2002:set", - createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), - resolve(map2, onError2) { - if (identity.isMap(map2)) { - if (map2.hasAllNullValues(true)) - return Object.assign(new YAMLSet, map2); - else - onError2("Set items must all have null values"); - } else - onError2("Expected a mapping for this tag"); - return map2; + async deleteThread(threadId) { + assertSafeStorageKey("thread_id", threadId); + delete this.storage[threadId]; + for (const key of Object.keys(this.writes)) + if (_parseKey(key).threadId === threadId) + delete this.writes[key]; } }; - exports.YAMLSet = YAMLSet; - exports.set = set2; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js -var require_timestamp = __commonJS((exports) => { - var stringifyNumber = require_stringifyNumber(); - function parseSexagesimal(str, asBigInt) { - const sign = str[0]; - const parts = sign === "-" || sign === "+" ? str.substring(1) : str; - const num = (n3) => asBigInt ? BigInt(n3) : Number(n3); - const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); - return sign === "-" ? num(-1) * res : res; +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/store/base.js +function validateNamespace(namespace) { + if (namespace.length === 0) + throw new InvalidNamespaceError("Namespace cannot be empty."); + for (const label of namespace) { + if (typeof label !== "string") + throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); + if (label.includes(".")) + throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); + if (label === "") + throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); } - function stringifySexagesimal(node) { - let { value } = node; - let num = (n3) => n3; - if (typeof value === "bigint") - num = (n3) => BigInt(n3); - else if (isNaN(value) || !isFinite(value)) - return stringifyNumber.stringifyNumber(node); - let sign = ""; - if (value < 0) { - sign = "-"; - value *= num(-1); - } - const _60 = num(60); - const parts = [value % _60]; - if (value < 60) { - parts.unshift(0); - } else { - value = (value - parts[0]) / _60; - parts.unshift(value % _60); - if (value >= 60) { - value = (value - parts[0]) / _60; - parts.unshift(value); - } - } - return sign + parts.map((n3) => String(n3).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + if (namespace[0] === "langgraph") + throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); +} +var InvalidNamespaceError, BaseStore2 = class { + async get(namespace, key) { + return (await this.batch([{ + namespace, + key + }]))[0]; } - var intTime = { - identify: (value) => typeof value === "bigint" || Number.isInteger(value), - default: true, - tag: "tag:yaml.org,2002:int", - format: "TIME", - test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, - resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), - stringify: stringifySexagesimal - }; - var floatTime = { - identify: (value) => typeof value === "number", - default: true, - tag: "tag:yaml.org,2002:float", - format: "TIME", - test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, - resolve: (str) => parseSexagesimal(str, false), - stringify: stringifySexagesimal - }; - var timestamp = { - identify: (value) => value instanceof Date, - default: true, - tag: "tag:yaml.org,2002:timestamp", - test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"), - resolve(str) { - const match2 = str.match(timestamp.test); - if (!match2) - throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); - const [, year, month, day, hour, minute, second] = match2.map(Number); - const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0; - let date6 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); - const tz = match2[8]; - if (tz && tz !== "Z") { - let d = parseSexagesimal(tz, false); - if (Math.abs(d) < 30) - d *= 60; - date6 -= 60000 * d; - } - return new Date(date6); - }, - stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + async search(namespacePrefix, options = {}) { + const { filter, limit = 10, offset = 0, query: query3 } = options; + return (await this.batch([{ + namespacePrefix, + filter, + limit, + offset, + query: query3 + }]))[0]; + } + async put(namespace, key, value, index2) { + validateNamespace(namespace); + await this.batch([{ + namespace, + key, + value, + index: index2 + }]); + } + async delete(namespace, key) { + await this.batch([{ + namespace, + key, + value: null + }]); + } + async listNamespaces(options = {}) { + const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; + const matchConditions = []; + if (prefix) + matchConditions.push({ + matchType: "prefix", + path: prefix + }); + if (suffix) + matchConditions.push({ + matchType: "suffix", + path: suffix + }); + return (await this.batch([{ + matchConditions: matchConditions.length ? matchConditions : undefined, + maxDepth, + limit, + offset + }]))[0]; + } + start() {} + stop() {} +}; +var init_base13 = __esm(() => { + InvalidNamespaceError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidNamespaceError"; + } }; - exports.floatTime = floatTime; - exports.intTime = intTime; - exports.timestamp = timestamp; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/yaml-1.1/schema.js -var require_schema3 = __commonJS((exports) => { - var map2 = require_map(); - var _null4 = require_null(); - var seq = require_seq(); - var string4 = require_string(); - var binary = require_binary(); - var bool = require_bool2(); - var float = require_float2(); - var int2 = require_int2(); - var merge2 = require_merge(); - var omap = require_omap(); - var pairs = require_pairs(); - var set2 = require_set(); - var timestamp = require_timestamp(); - var schema = [ - map2.map, - seq.seq, - string4.string, - _null4.nullTag, - bool.trueTag, - bool.falseTag, - int2.intBin, - int2.intOct, - int2.int, - int2.intHex, - float.floatNaN, - float.floatExp, - float.float, - binary.binary, - merge2.merge, - omap.omap, - pairs.pairs, - set2.set, - timestamp.intTime, - timestamp.floatTime, - timestamp.timestamp - ]; - exports.schema = schema; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/tags.js -var require_tags = __commonJS((exports) => { - var map2 = require_map(); - var _null4 = require_null(); - var seq = require_seq(); - var string4 = require_string(); - var bool = require_bool(); - var float = require_float(); - var int2 = require_int(); - var schema = require_schema(); - var schema$1 = require_schema2(); - var binary = require_binary(); - var merge2 = require_merge(); - var omap = require_omap(); - var pairs = require_pairs(); - var schema$2 = require_schema3(); - var set2 = require_set(); - var timestamp = require_timestamp(); - var schemas3 = new Map([ - ["core", schema.schema], - ["failsafe", [map2.map, seq.seq, string4.string]], - ["json", schema$1.schema], - ["yaml11", schema$2.schema], - ["yaml-1.1", schema$2.schema] - ]); - var tagsByName = { - binary: binary.binary, - bool: bool.boolTag, - float: float.float, - floatExp: float.floatExp, - floatNaN: float.floatNaN, - floatTime: timestamp.floatTime, - int: int2.int, - intHex: int2.intHex, - intOct: int2.intOct, - intTime: timestamp.intTime, - map: map2.map, - merge: merge2.merge, - null: _null4.nullTag, - omap: omap.omap, - pairs: pairs.pairs, - seq: seq.seq, - set: set2.set, - timestamp: timestamp.timestamp - }; - var coreKnownTags = { - "tag:yaml.org,2002:binary": binary.binary, - "tag:yaml.org,2002:merge": merge2.merge, - "tag:yaml.org,2002:omap": omap.omap, - "tag:yaml.org,2002:pairs": pairs.pairs, - "tag:yaml.org,2002:set": set2.set, - "tag:yaml.org,2002:timestamp": timestamp.timestamp - }; - function getTags(customTags, schemaName, addMergeTag) { - const schemaTags = schemas3.get(schemaName); - if (schemaTags && !customTags) { - return addMergeTag && !schemaTags.includes(merge2.merge) ? schemaTags.concat(merge2.merge) : schemaTags.slice(); +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js +var extractStore = (input) => { + if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") + return input.store; + return input; +}, AsyncBatchedStore; +var init_batch = __esm(() => { + init_base13(); + AsyncBatchedStore = class extends BaseStore2 { + lg_name = "AsyncBatchedStore"; + store; + queue = /* @__PURE__ */ new Map; + nextKey = 0; + running = false; + processingTask = null; + constructor(store) { + super(); + this.store = extractStore(store); } - let tags = schemaTags; - if (!tags) { - if (Array.isArray(customTags)) - tags = []; - else { - const keys = Array.from(schemas3.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); - throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); - } + get isRunning() { + return this.running; } - if (Array.isArray(customTags)) { - for (const tag of customTags) - tags = tags.concat(tag); - } else if (typeof customTags === "function") { - tags = customTags(tags.slice()); + async batch(_operations) { + throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); } - if (addMergeTag) - tags = tags.concat(merge2.merge); - return tags.reduce((tags2, tag) => { - const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; - if (!tagObj) { - const tagName = JSON.stringify(tag); - const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); - throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); - } - if (!tags2.includes(tagObj)) - tags2.push(tagObj); - return tags2; - }, []); - } - exports.coreKnownTags = coreKnownTags; - exports.getTags = getTags; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/schema/Schema.js -var require_Schema = __commonJS((exports) => { - var identity = require_identity(); - var map2 = require_map(); - var seq = require_seq(); - var string4 = require_string(); - var tags = require_tags(); - var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; - - class Schema { - constructor({ compat: compat2, customTags, merge: merge2, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { - this.compat = Array.isArray(compat2) ? tags.getTags(compat2, "compat") : compat2 ? tags.getTags(null, compat2) : null; - this.name = typeof schema === "string" && schema || "core"; - this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; - this.tags = tags.getTags(customTags, this.name, merge2); - this.toStringOptions = toStringDefaults ?? null; - Object.defineProperty(this, identity.MAP, { value: map2.map }); - Object.defineProperty(this, identity.SCALAR, { value: string4.string }); - Object.defineProperty(this, identity.SEQ, { value: seq.seq }); - this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + async get(namespace, key) { + return this.enqueueOperation({ + namespace, + key + }); } - clone() { - const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); - copy.tags = this.tags.slice(); - return copy; + async search(namespacePrefix, options) { + const { filter, limit = 10, offset = 0, query: query3 } = options || {}; + return this.enqueueOperation({ + namespacePrefix, + filter, + limit, + offset, + query: query3 + }); } - } - exports.Schema = Schema; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/stringify/stringifyDocument.js -var require_stringifyDocument = __commonJS((exports) => { - var identity = require_identity(); - var stringify4 = require_stringify3(); - var stringifyComment = require_stringifyComment(); - function stringifyDocument(doc2, options) { - const lines = []; - let hasDirectives = options.directives === true; - if (options.directives !== false && doc2.directives) { - const dir = doc2.directives.toString(doc2); - if (dir) { - lines.push(dir); - hasDirectives = true; - } else if (doc2.directives.docStart) - hasDirectives = true; + async put(namespace, key, value) { + return this.enqueueOperation({ + namespace, + key, + value + }); } - if (hasDirectives) - lines.push("---"); - const ctx = stringify4.createStringifyContext(doc2, options); - const { commentString } = ctx.options; - if (doc2.commentBefore) { - if (lines.length !== 1) - lines.unshift(""); - const cs = commentString(doc2.commentBefore); - lines.unshift(stringifyComment.indentComment(cs, "")); + async delete(namespace, key) { + return this.enqueueOperation({ + namespace, + key, + value: null + }); } - let chompKeep = false; - let contentComment = null; - if (doc2.contents) { - if (identity.isNode(doc2.contents)) { - if (doc2.contents.spaceBefore && hasDirectives) - lines.push(""); - if (doc2.contents.commentBefore) { - const cs = commentString(doc2.contents.commentBefore); - lines.push(stringifyComment.indentComment(cs, "")); - } - ctx.forceBlockIndent = !!doc2.comment; - contentComment = doc2.contents.comment; + start() { + if (!this.running) { + this.running = true; + this.processingTask = this.processBatchQueue(); } - const onChompKeep = contentComment ? undefined : () => chompKeep = true; - let body = stringify4.stringify(doc2.contents, ctx, () => contentComment = null, onChompKeep); - if (contentComment) - body += stringifyComment.lineComment(body, "", commentString(contentComment)); - if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { - lines[lines.length - 1] = `--- ${body}`; - } else - lines.push(body); - } else { - lines.push(stringify4.stringify(doc2.contents, ctx)); } - if (doc2.directives?.docEnd) { - if (doc2.comment) { - const cs = commentString(doc2.comment); - if (cs.includes(` -`)) { - lines.push("..."); - lines.push(stringifyComment.indentComment(cs, "")); - } else { - lines.push(`... ${cs}`); + async stop() { + this.running = false; + if (this.processingTask) + await this.processingTask; + } + enqueueOperation(operation) { + return new Promise((resolve2, reject) => { + const key = this.nextKey; + this.nextKey += 1; + this.queue.set(key, { + operation, + resolve: resolve2, + reject + }); + }); + } + async processBatchQueue() { + while (this.running) { + await new Promise((resolve2) => { + setTimeout(resolve2, 0); + }); + if (this.queue.size === 0) + continue; + const batch = new Map(this.queue); + this.queue.clear(); + try { + const operations = Array.from(batch.values()).map(({ operation }) => operation); + const results = await this.store.batch(operations); + batch.forEach(({ resolve: resolve2 }, key) => { + resolve2(results[Array.from(batch.keys()).indexOf(key)]); + }); + } catch (e) { + batch.forEach(({ reject }) => { + reject(e); + }); } - } else { - lines.push("..."); - } - } else { - let dc = doc2.comment; - if (dc && chompKeep) - dc = dc.replace(/^\n+/, ""); - if (dc) { - if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") - lines.push(""); - lines.push(stringifyComment.indentComment(commentString(dc), "")); } } - return lines.join(` -`) + ` -`; - } - exports.stringifyDocument = stringifyDocument; + toJSON() { + return { + queue: this.queue, + nextKey: this.nextKey, + running: this.running, + store: "[LangGraphStore]" + }; + } + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/doc/Document.js -var require_Document = __commonJS((exports) => { - var Alias = require_Alias(); - var Collection = require_Collection(); - var identity = require_identity(); - var Pair = require_Pair(); - var toJS = require_toJS(); - var Schema = require_Schema(); - var stringifyDocument = require_stringifyDocument(); - var anchors = require_anchors(); - var applyReviver = require_applyReviver(); - var createNode = require_createNode(); - var directives = require_directives(); - - class Document2 { - constructor(value, replacer, options) { - this.commentBefore = null; - this.comment = null; - this.errors = []; - this.warnings = []; - Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); - let _replacer = null; - if (typeof replacer === "function" || Array.isArray(replacer)) { - _replacer = replacer; - } else if (options === undefined && replacer) { - options = replacer; - replacer = undefined; +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js +function tokenizePath(path2) { + if (!path2) + return []; + const tokens = []; + let current = []; + let i = 0; + while (i < path2.length) { + const char = path2[i]; + if (char === "[") { + if (current.length) { + tokens.push(current.join("")); + current = []; } - const opt = Object.assign({ - intAsBigInt: false, - keepSourceTokens: false, - logLevel: "warn", - prettyErrors: true, - strict: true, - stringKeys: false, - uniqueKeys: true, - version: "1.2" - }, options); - this.options = opt; - let { version: version4 } = opt; - if (options?._directives) { - this.directives = options._directives.atDocument(); - if (this.directives.yaml.explicit) - version4 = this.directives.yaml.version; - } else - this.directives = new directives.Directives({ version: version4 }); - this.setSchema(version4, options); - this.contents = value === undefined ? null : this.createNode(value, _replacer, options); - } - clone() { - const copy = Object.create(Document2.prototype, { - [identity.NODE_TYPE]: { value: identity.DOC } - }); - copy.commentBefore = this.commentBefore; - copy.comment = this.comment; - copy.errors = this.errors.slice(); - copy.warnings = this.warnings.slice(); - copy.options = Object.assign({}, this.options); - if (this.directives) - copy.directives = this.directives.clone(); - copy.schema = this.schema.clone(); - copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; - if (this.range) - copy.range = this.range.slice(); - return copy; - } - add(value) { - if (assertCollection(this.contents)) - this.contents.add(value); - } - addIn(path2, value) { - if (assertCollection(this.contents)) - this.contents.addIn(path2, value); - } - createAlias(node, name) { - if (!node.anchor) { - const prev = anchors.anchorNames(this); - node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + let bracketCount = 1; + const indexChars = ["["]; + i += 1; + while (i < path2.length && bracketCount > 0) { + if (path2[i] === "[") + bracketCount += 1; + else if (path2[i] === "]") + bracketCount -= 1; + indexChars.push(path2[i]); + i += 1; } - return new Alias.Alias(node.anchor); - } - createNode(value, replacer, options) { - let _replacer = undefined; - if (typeof replacer === "function") { - value = replacer.call({ "": value }, "", value); - _replacer = replacer; - } else if (Array.isArray(replacer)) { - const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; - const asStr = replacer.filter(keyToStr).map(String); - if (asStr.length > 0) - replacer = replacer.concat(asStr); - _replacer = replacer; - } else if (options === undefined && replacer) { - options = replacer; - replacer = undefined; + tokens.push(indexChars.join("")); + continue; + } else if (char === "{") { + if (current.length) { + tokens.push(current.join("")); + current = []; } - const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; - const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a"); - const ctx = { - aliasDuplicateObjects: aliasDuplicateObjects ?? true, - keepUndefined: keepUndefined ?? false, - onAnchor, - onTagObj, - replacer: _replacer, - schema: this.schema, - sourceObjects - }; - const node = createNode.createNode(value, tag, ctx); - if (flow && identity.isCollection(node)) - node.flow = true; - setAnchors(); - return node; - } - createPair(key, value, options = {}) { - const k = this.createNode(key, null, options); - const v = this.createNode(value, null, options); - return new Pair.Pair(k, v); - } - delete(key) { - return assertCollection(this.contents) ? this.contents.delete(key) : false; - } - deleteIn(path2) { - if (Collection.isEmptyPath(path2)) { - if (this.contents == null) - return false; - this.contents = null; - return true; + let braceCount = 1; + const fieldChars = ["{"]; + i += 1; + while (i < path2.length && braceCount > 0) { + if (path2[i] === "{") + braceCount += 1; + else if (path2[i] === "}") + braceCount -= 1; + fieldChars.push(path2[i]); + i += 1; } - return assertCollection(this.contents) ? this.contents.deleteIn(path2) : false; - } - get(key, keepScalar) { - return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined; - } - getIn(path2, keepScalar) { - if (Collection.isEmptyPath(path2)) - return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; - return identity.isCollection(this.contents) ? this.contents.getIn(path2, keepScalar) : undefined; - } - has(key) { - return identity.isCollection(this.contents) ? this.contents.has(key) : false; - } - hasIn(path2) { - if (Collection.isEmptyPath(path2)) - return this.contents !== undefined; - return identity.isCollection(this.contents) ? this.contents.hasIn(path2) : false; - } - set(key, value) { - if (this.contents == null) { - this.contents = Collection.collectionFromPath(this.schema, [key], value); - } else if (assertCollection(this.contents)) { - this.contents.set(key, value); + tokens.push(fieldChars.join("")); + continue; + } else if (char === ".") { + if (current.length) { + tokens.push(current.join("")); + current = []; } - } - setIn(path2, value) { - if (Collection.isEmptyPath(path2)) { - this.contents = value; - } else if (this.contents == null) { - this.contents = Collection.collectionFromPath(this.schema, Array.from(path2), value); - } else if (assertCollection(this.contents)) { - this.contents.setIn(path2, value); + } else + current.push(char); + i += 1; + } + if (current.length) + tokens.push(current.join("")); + return tokens; +} +function isFilterOperators(obj) { + return typeof obj === "object" && obj !== null && Object.keys(obj).every((key) => key === "$eq" || key === "$ne" || key === "$gt" || key === "$gte" || key === "$lt" || key === "$lte" || key === "$in" || key === "$nin"); +} +function compareValues(itemValue, filterValue) { + if (isFilterOperators(filterValue)) + return Object.keys(filterValue).filter((k) => k.startsWith("$")).every((op) => { + const value = filterValue[op]; + switch (op) { + case "$eq": + return itemValue === value; + case "$ne": + return itemValue !== value; + case "$gt": + return Number(itemValue) > Number(value); + case "$gte": + return Number(itemValue) >= Number(value); + case "$lt": + return Number(itemValue) < Number(value); + case "$lte": + return Number(itemValue) <= Number(value); + case "$in": + return Array.isArray(value) ? value.includes(itemValue) : false; + case "$nin": + return Array.isArray(value) ? !value.includes(itemValue) : true; + default: + return false; } + }); + return itemValue === filterValue; +} +function getTextAtPath(obj, path2) { + if (!path2 || path2 === "$") + return [JSON.stringify(obj, null, 2)]; + const tokens = Array.isArray(path2) ? path2 : tokenizePath(path2); + function extractFromObj(obj2, tokens2, pos) { + if (pos >= tokens2.length) { + if (typeof obj2 === "string" || typeof obj2 === "number" || typeof obj2 === "boolean") + return [String(obj2)]; + if (obj2 === null || obj2 === undefined) + return []; + if (Array.isArray(obj2) || typeof obj2 === "object") + return [JSON.stringify(obj2, null, 2)]; + return []; } - setSchema(version4, options = {}) { - if (typeof version4 === "number") - version4 = String(version4); - let opt; - switch (version4) { - case "1.1": - if (this.directives) - this.directives.yaml.version = "1.1"; - else - this.directives = new directives.Directives({ version: "1.1" }); - opt = { resolveKnownTags: false, schema: "yaml-1.1" }; - break; - case "1.2": - case "next": - if (this.directives) - this.directives.yaml.version = version4; - else - this.directives = new directives.Directives({ version: version4 }); - opt = { resolveKnownTags: true, schema: "core" }; - break; - case null: - if (this.directives) - delete this.directives; - opt = null; - break; - default: { - const sv = JSON.stringify(version4); - throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); - } - } - if (options.schema instanceof Object) - this.schema = options.schema; - else if (opt) - this.schema = new Schema.Schema(Object.assign(opt, options)); + const token = tokens2[pos]; + const results = []; + if (pos === 0 && token === "$") + results.push(JSON.stringify(obj2, null, 2)); + if (token.startsWith("[") && token.endsWith("]")) { + if (!Array.isArray(obj2)) + return []; + const index2 = token.slice(1, -1); + if (index2 === "*") + for (const item of obj2) + results.push(...extractFromObj(item, tokens2, pos + 1)); else - throw new Error(`With a null YAML version, the { schema: Schema } option is required`); - } - toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver: reviver2 } = {}) { - const ctx = { - anchors: new Map, - doc: this, - keep: !json2, - mapAsMap: mapAsMap === true, - mapKeyWarned: false, - maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 - }; - const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); - if (typeof onAnchor === "function") - for (const { count, res: res2 } of ctx.anchors.values()) - onAnchor(res2, count); - return typeof reviver2 === "function" ? applyReviver.applyReviver(reviver2, { "": res }, "", res) : res; - } - toJSON(jsonArg, onAnchor) { - return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); - } - toString(options = {}) { - if (this.errors.length > 0) - throw new Error("Document with errors cannot be stringified"); - if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { - const s = JSON.stringify(options.indent); - throw new Error(`"indent" option must be a positive integer, not ${s}`); + try { + let idx = parseInt(index2, 10); + if (idx < 0) + idx = obj2.length + idx; + if (idx >= 0 && idx < obj2.length) + results.push(...extractFromObj(obj2[idx], tokens2, pos + 1)); + } catch { + return []; + } + } else if (token.startsWith("{") && token.endsWith("}")) { + if (typeof obj2 !== "object" || obj2 === null) + return []; + const fields = token.slice(1, -1).split(",").map((f3) => f3.trim()); + for (const field of fields) { + const nestedTokens = tokenizePath(field); + if (nestedTokens.length) { + let currentObj = obj2; + for (const nestedToken of nestedTokens) + if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) + currentObj = currentObj[nestedToken]; + else { + currentObj = undefined; + break; + } + if (currentObj !== undefined) { + if (typeof currentObj === "string" || typeof currentObj === "number" || typeof currentObj === "boolean") + results.push(String(currentObj)); + else if (Array.isArray(currentObj) || typeof currentObj === "object") + results.push(JSON.stringify(currentObj, null, 2)); + } + } } - return stringifyDocument.stringifyDocument(this, options); - } - } - function assertCollection(contents) { - if (identity.isCollection(contents)) - return true; - throw new Error("Expected a YAML collection as document contents"); + } else if (token === "*") { + if (Array.isArray(obj2)) + for (const item of obj2) + results.push(...extractFromObj(item, tokens2, pos + 1)); + else if (typeof obj2 === "object" && obj2 !== null) + for (const value of Object.values(obj2)) + results.push(...extractFromObj(value, tokens2, pos + 1)); + } else if (typeof obj2 === "object" && obj2 !== null && token in obj2) + results.push(...extractFromObj(obj2[token], tokens2, pos + 1)); + return results; } - exports.Document = Document2; -}); + return extractFromObj(obj, tokens, 0); +} +var init_utils7 = () => {}; -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/errors.js -var require_errors = __commonJS((exports) => { - class YAMLError extends Error { - constructor(name, pos, code, message) { +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js +var InMemoryStore2; +var init_memory3 = __esm(() => { + init_base13(); + init_utils7(); + InMemoryStore2 = class extends BaseStore2 { + data = /* @__PURE__ */ new Map; + vectors = /* @__PURE__ */ new Map; + _indexConfig; + constructor(options) { super(); - this.name = name; - this.code = code; - this.message = message; - this.pos = pos; + if (options?.index) + this._indexConfig = { + ...options.index, + __tokenizedFields: (options.index.fields ?? ["$"]).map((p) => [p, p === "$" ? [p] : tokenizePath(p)]) + }; } - } - - class YAMLParseError extends YAMLError { - constructor(pos, code, message) { - super("YAMLParseError", pos, code, message); + async batch(operations) { + const results = []; + const putOps = /* @__PURE__ */ new Map; + const searchOps = /* @__PURE__ */ new Map; + for (let i = 0;i < operations.length; i += 1) { + const op = operations[i]; + if ("key" in op && "namespace" in op && !("value" in op)) + results.push(this.getOperation(op)); + else if ("namespacePrefix" in op) { + const candidates = this.filterItems(op); + searchOps.set(i, [op, candidates]); + results.push(null); + } else if ("value" in op) { + const key = `${op.namespace.join(":")}:${op.key}`; + putOps.set(key, op); + results.push(null); + } else if ("matchConditions" in op) + results.push(this.listNamespacesOperation(op)); + } + if (searchOps.size > 0) + if (this._indexConfig?.embeddings) { + const queries = /* @__PURE__ */ new Set; + for (const [op] of searchOps.values()) + if (op.query) + queries.add(op.query); + const queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : []; + const queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])); + for (const [i, [op, candidates]] of searchOps.entries()) + if (op.query && queryVectors[op.query]) { + const queryVector = queryVectors[op.query]; + results[i] = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10); + } else + results[i] = this.paginateResults(candidates.map((item) => ({ + ...item, + score: undefined + })), op.offset ?? 0, op.limit ?? 10); + } else + for (const [i, [op, candidates]] of searchOps.entries()) + results[i] = this.paginateResults(candidates.map((item) => ({ + ...item, + score: undefined + })), op.offset ?? 0, op.limit ?? 10); + if (putOps.size > 0 && this._indexConfig?.embeddings) { + const toEmbed = this.extractTexts(Array.from(putOps.values())); + if (Object.keys(toEmbed).length > 0) { + const embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed)); + this.insertVectors(toEmbed, embeddings); + } + } + for (const op of putOps.values()) + this.putOperation(op); + return results; } - } - - class YAMLWarning extends YAMLError { - constructor(pos, code, message) { - super("YAMLWarning", pos, code, message); + getOperation(op) { + const namespaceKey = op.namespace.join(":"); + return this.data.get(namespaceKey)?.get(op.key) ?? null; } - } - var prettifyError2 = (src, lc) => (error51) => { - if (error51.pos[0] === -1) - return; - error51.linePos = error51.pos.map((pos) => lc.linePos(pos)); - const { line, col } = error51.linePos[0]; - error51.message += ` at line ${line}, column ${col}`; - let ci = col - 1; - let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); - if (ci >= 60 && lineStr.length > 80) { - const trimStart = Math.min(ci - 39, lineStr.length - 79); - lineStr = "…" + lineStr.substring(trimStart); - ci -= trimStart - 1; + putOperation(op) { + const namespaceKey = op.namespace.join(":"); + if (!this.data.has(namespaceKey)) + this.data.set(namespaceKey, /* @__PURE__ */ new Map); + const namespaceMap = this.data.get(namespaceKey); + if (op.value === null) + namespaceMap.delete(op.key); + else { + const now = /* @__PURE__ */ new Date; + if (namespaceMap.has(op.key)) { + const item = namespaceMap.get(op.key); + item.value = op.value; + item.updatedAt = now; + } else + namespaceMap.set(op.key, { + value: op.value, + key: op.key, + namespace: op.namespace, + createdAt: now, + updatedAt: now + }); + } } - if (lineStr.length > 80) - lineStr = lineStr.substring(0, 79) + "…"; - if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { - let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); - if (prev.length > 80) - prev = prev.substring(0, 79) + `… -`; - lineStr = prev + lineStr; + listNamespacesOperation(op) { + let namespaces = Array.from(this.data.keys()).map((ns3) => ns3.split(":")); + if (op.matchConditions && op.matchConditions.length > 0) + namespaces = namespaces.filter((ns3) => op.matchConditions.every((condition) => this.doesMatch(condition, ns3))); + if (op.maxDepth !== undefined) + namespaces = Array.from(new Set(namespaces.map((ns3) => ns3.slice(0, op.maxDepth).join(":")))).map((ns3) => ns3.split(":")); + namespaces.sort((a, b) => a.join(":").localeCompare(b.join(":"))); + return namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length)); } - if (/[^ ]/.test(lineStr)) { - let count = 1; - const end = error51.linePos[1]; - if (end?.line === line && end.col > col) { - count = Math.max(1, Math.min(end.col - col, 80 - ci)); + doesMatch(matchCondition, key) { + const { matchType, path: path2 } = matchCondition; + if (matchType === "prefix") { + if (path2.length > key.length) + return false; + return path2.every((pElem, index2) => { + const kElem = key[index2]; + return pElem === "*" || kElem === pElem; + }); + } else if (matchType === "suffix") { + if (path2.length > key.length) + return false; + return path2.every((pElem, index2) => { + const kElem = key[key.length - path2.length + index2]; + return pElem === "*" || kElem === pElem; + }); } - const pointer2 = " ".repeat(ci) + "^".repeat(count); - error51.message += `: - -${lineStr} -${pointer2} -`; + throw new Error(`Unsupported match type: ${matchType}`); } - }; - exports.YAMLError = YAMLError; - exports.YAMLParseError = YAMLParseError; - exports.YAMLWarning = YAMLWarning; - exports.prettifyError = prettifyError2; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-props.js -var require_resolve_props = __commonJS((exports) => { - function resolveProps(tokens, { flow, indicator, next, offset, onError: onError2, parentIndent, startOnNewline }) { - let spaceBefore = false; - let atNewline = startOnNewline; - let hasSpace = startOnNewline; - let comment = ""; - let commentSep = ""; - let hasNewline = false; - let reqSpace = false; - let tab = null; - let anchor = null; - let tag = null; - let newlineAfterProp = null; - let comma = null; - let found = null; - let start = null; - for (const token of tokens) { - if (reqSpace) { - if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") - onError2(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); - reqSpace = false; + filterItems(op) { + const candidates = []; + for (const [namespace, items] of this.data.entries()) + if (namespace.startsWith(op.namespacePrefix.join(":"))) + candidates.push(...items.values()); + let filteredCandidates = candidates; + if (op.filter) + filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value))); + return filteredCandidates; + } + scoreResults(candidates, queryVector, offset = 0, limit = 10) { + const flatItems = []; + const flatVectors = []; + const scoreless = []; + for (const item of candidates) { + const vectors = this.getVectors(item); + if (vectors.length) + for (const vector of vectors) { + flatItems.push(item); + flatVectors.push(vector); + } + else + scoreless.push(item); } - if (tab) { - if (atNewline && token.type !== "comment" && token.type !== "newline") { - onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + const sortedResults = this.cosineSimilarity(queryVector, flatVectors).map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]); + const seen = /* @__PURE__ */ new Set; + const kept = []; + for (const [score, item] of sortedResults) { + const key = `${item.namespace.join(":")}:${item.key}`; + if (seen.has(key)) + continue; + const ix = seen.size; + if (ix >= offset + limit) + break; + if (ix < offset) { + seen.add(key); + continue; } - tab = null; + seen.add(key); + kept.push([score, item]); } - switch (token.type) { - case "space": - if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) { - tab = token; + if (scoreless.length && kept.length < limit) + for (const item of scoreless.slice(0, limit - kept.length)) { + const key = `${item.namespace.join(":")}:${item.key}`; + if (!seen.has(key)) { + seen.add(key); + kept.push([undefined, item]); } - hasSpace = true; - break; - case "comment": { - if (!hasSpace) - onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); - const cb = token.source.substring(1) || " "; - if (!comment) - comment = cb; - else - comment += commentSep + cb; - commentSep = ""; - atNewline = false; - break; - } - case "newline": - if (atNewline) { - if (comment) - comment += token.source; - else if (!found || indicator !== "seq-item-ind") - spaceBefore = true; - } else - commentSep += token.source; - atNewline = true; - hasNewline = true; - if (anchor || tag) - newlineAfterProp = token; - hasSpace = true; - break; - case "anchor": - if (anchor) - onError2(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); - if (token.source.endsWith(":")) - onError2(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); - anchor = token; - start ?? (start = token.offset); - atNewline = false; - hasSpace = false; - reqSpace = true; - break; - case "tag": { - if (tag) - onError2(token, "MULTIPLE_TAGS", "A node can have at most one tag"); - tag = token; - start ?? (start = token.offset); - atNewline = false; - hasSpace = false; - reqSpace = true; - break; } - case indicator: - if (anchor || tag) - onError2(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); - if (found) - onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); - found = token; - atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; - hasSpace = false; - break; - case "comma": - if (flow) { - if (comma) - onError2(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); - comma = token; - atNewline = false; - hasSpace = false; - break; + return kept.map(([score, item]) => ({ + ...item, + score + })); + } + paginateResults(results, offset, limit) { + return results.slice(offset, offset + limit); + } + extractTexts(ops) { + if (!ops.length || !this._indexConfig) + return {}; + const toEmbed = {}; + for (const op of ops) + if (op.value !== null && op.index !== false) { + const paths = op.index === null || op.index === undefined ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, tokenizePath(ix)]); + for (const [path2, field] of paths) { + const texts = getTextAtPath(op.value, field); + if (texts.length) + if (texts.length > 1) + texts.forEach((text, i) => { + if (!toEmbed[text]) + toEmbed[text] = []; + toEmbed[text].push([ + op.namespace, + op.key, + `${path2}.${i}` + ]); + }); + else { + if (!toEmbed[texts[0]]) + toEmbed[texts[0]] = []; + toEmbed[texts[0]].push([ + op.namespace, + op.key, + path2 + ]); + } } - default: - onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); - atNewline = false; - hasSpace = false; + } + return toEmbed; + } + insertVectors(texts, embeddings) { + for (const [text, metadata] of Object.entries(texts)) { + const embedding = embeddings.shift(); + if (!embedding) + throw new Error(`No embedding found for text: ${text}`); + for (const [namespace, key, field] of metadata) { + const namespaceKey = namespace.join(":"); + if (!this.vectors.has(namespaceKey)) + this.vectors.set(namespaceKey, /* @__PURE__ */ new Map); + const namespaceMap = this.vectors.get(namespaceKey); + if (!namespaceMap.has(key)) + namespaceMap.set(key, /* @__PURE__ */ new Map); + namespaceMap.get(key).set(field, embedding); + } } } - const last = tokens[tokens.length - 1]; - const end = last ? last.offset + last.source.length : offset; - if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { - onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + getVectors(item) { + const namespaceKey = item.namespace.join(":"); + const itemKey = item.key; + if (!this.vectors.has(namespaceKey)) + return []; + const namespaceMap = this.vectors.get(namespaceKey); + if (!namespaceMap.has(itemKey)) + return []; + const itemMap = namespaceMap.get(itemKey); + const vectors = Array.from(itemMap.values()); + if (!vectors.length) + return []; + return vectors; } - if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) - onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); - return { - comma, - found, - spaceBefore, - comment, - hasNewline, - anchor, - tag, - newlineAfterProp, - end, - start: start ?? end - }; - } - exports.resolveProps = resolveProps; + cosineSimilarity(X, Y) { + if (!Y.length) + return []; + const dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0)); + const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0)); + const magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))); + return dotProducts.map((dot, i) => { + const magnitude2 = magnitudes2[i]; + return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0; + }); + } + get indexConfig() { + return this._indexConfig; + } + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/util-contains-newline.js -var require_util_contains_newline = __commonJS((exports) => { - function containsNewline(key) { - if (!key) - return null; - switch (key.type) { - case "alias": - case "scalar": - case "double-quoted-scalar": - case "single-quoted-scalar": - if (key.source.includes(` -`)) - return true; - if (key.end) { - for (const st of key.end) - if (st.type === "newline") - return true; - } - return false; - case "flow-collection": - for (const it of key.items) { - for (const st of it.start) - if (st.type === "newline") - return true; - if (it.sep) { - for (const st of it.sep) - if (st.type === "newline") - return true; - } - if (containsNewline(it.key) || containsNewline(it.value)) - return true; - } - return false; - default: - return true; - } +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js +var BaseCache2 = class { + serde = new JsonPlusSerializer; + constructor(serde) { + this.serde = serde || this.serde; } - exports.containsNewline = containsNewline; +}; +var init_base14 = __esm(() => { + init_jsonplus(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/util-flow-indent-check.js -var require_util_flow_indent_check = __commonJS((exports) => { - var utilContainsNewline = require_util_contains_newline(); - function flowIndentCheck(indent, fc, onError2) { - if (fc?.type === "flow-collection") { - const end = fc.end[0]; - if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) { - const msg = "Flow end indicator should be more indented than parent"; - onError2(end, "BAD_INDENT", msg, true); - } - } - } - exports.flowIndentCheck = flowIndentCheck; +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js +var init_memory4 = __esm(() => { + init_base14(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/util-map-includes.js -var require_util_map_includes = __commonJS((exports) => { - var identity = require_identity(); - function mapIncludes(ctx, items, search) { - const { uniqueKeys } = ctx.options; - if (uniqueKeys === false) - return false; - const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; - return items.some((pair) => isEqual(pair.key, search)); - } - exports.mapIncludes = mapIncludes; +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js +var init_cache = __esm(() => { + init_base14(); + init_memory4(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-block-map.js -var require_resolve_block_map = __commonJS((exports) => { - var Pair = require_Pair(); - var YAMLMap = require_YAMLMap(); - var resolveProps = require_resolve_props(); - var utilContainsNewline = require_util_contains_newline(); - var utilFlowIndentCheck = require_util_flow_indent_check(); - var utilMapIncludes = require_util_map_includes(); - var startColMsg = "All mapping items must start at the same column"; - function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError2, tag) { - const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; - const map2 = new NodeClass(ctx.schema); - if (ctx.atRoot) - ctx.atRoot = false; - let offset = bm.offset; - let commentEnd = null; - for (const collItem of bm.items) { - const { start, key, sep: sep2, value } = collItem; - const keyProps = resolveProps.resolveProps(start, { - indicator: "explicit-key-ind", - next: key ?? sep2?.[0], - offset, - onError: onError2, - parentIndent: bm.indent, - startOnNewline: true - }); - const implicitKey = !keyProps.found; - if (implicitKey) { - if (key) { - if (key.type === "block-seq") - onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); - else if ("indent" in key && key.indent !== bm.indent) - onError2(offset, "BAD_INDENT", startColMsg); - } - if (!keyProps.anchor && !keyProps.tag && !sep2) { - commentEnd = keyProps.end; - if (keyProps.comment) { - if (map2.comment) - map2.comment += ` -` + keyProps.comment; - else - map2.comment = keyProps.comment; - } - continue; - } - if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { - onError2(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); - } - } else if (keyProps.found?.indent !== bm.indent) { - onError2(offset, "BAD_INDENT", startColMsg); - } - ctx.atKey = true; - const keyStart = keyProps.end; - const keyNode = key ? composeNode(ctx, key, keyProps, onError2) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError2); - if (ctx.schema.compat) - utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError2); - ctx.atKey = false; - if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode)) - onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); - const valueProps = resolveProps.resolveProps(sep2 ?? [], { - indicator: "map-value-ind", - next: value, - offset: keyNode.range[2], - onError: onError2, - parentIndent: bm.indent, - startOnNewline: !key || key.type === "block-scalar" - }); - offset = valueProps.end; - if (valueProps.found) { - if (implicitKey) { - if (value?.type === "block-map" && !valueProps.hasNewline) - onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); - if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) - onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); - } - const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : composeEmptyNode(ctx, offset, sep2, null, valueProps, onError2); - if (ctx.schema.compat) - utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError2); - offset = valueNode.range[2]; - const pair = new Pair.Pair(keyNode, valueNode); - if (ctx.options.keepSourceTokens) - pair.srcToken = collItem; - map2.items.push(pair); - } else { - if (implicitKey) - onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); - if (valueProps.comment) { - if (keyNode.comment) - keyNode.comment += ` -` + valueProps.comment; - else - keyNode.comment = valueProps.comment; - } - const pair = new Pair.Pair(keyNode); - if (ctx.options.keepSourceTokens) - pair.srcToken = collItem; - map2.items.push(pair); - } - } - if (commentEnd && commentEnd < offset) - onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); - map2.range = [bm.offset, offset, commentEnd ?? offset]; - return map2; - } - exports.resolveBlockMap = resolveBlockMap; +// ../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.3_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opente_7xcfe3dw7jilwvxrzb56xcx3vm/node_modules/@langchain/langgraph-checkpoint/dist/index.js +var init_dist3 = __esm(() => { + init_id3(); + init_types5(); + init_base12(); + init_memory2(); + init_base13(); + init_batch(); + init_memory3(); + init_base14(); + init_memory4(); + init_cache(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-block-seq.js -var require_resolve_block_seq = __commonJS((exports) => { - var YAMLSeq = require_YAMLSeq(); - var resolveProps = require_resolve_props(); - var utilFlowIndentCheck = require_util_flow_indent_check(); - function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError2, tag) { - const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; - const seq = new NodeClass(ctx.schema); - if (ctx.atRoot) - ctx.atRoot = false; - if (ctx.atKey) - ctx.atKey = false; - let offset = bs.offset; - let commentEnd = null; - for (const { start, value } of bs.items) { - const props = resolveProps.resolveProps(start, { - indicator: "seq-item-ind", - next: value, - offset, - onError: onError2, - parentIndent: bs.indent, - startOnNewline: true - }); - if (!props.found) { - if (props.anchor || props.tag || value) { - if (value?.type === "block-seq") - onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column"); - else - onError2(offset, "MISSING_CHAR", "Sequence item without - indicator"); - } else { - commentEnd = props.end; - if (props.comment) - seq.comment = props.comment; - continue; - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/base.js +function isBaseChannel(obj) { + return obj != null && obj.lg_is_channel === true; +} +function getOnlyChannels(channels) { + if (channels[IS_ONLY_BASE_CHANNEL] === true) + return channels; + const newChannels = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) + continue; + const value = channels[k]; + if (isBaseChannel(value)) + newChannels[k] = value; + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +function emptyChannels(channels, checkpoint) { + const filteredChannels = getOnlyChannels(channels); + const newChannels = {}; + for (const k in filteredChannels) { + if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) + continue; + const channelValue = checkpoint.channel_values[k]; + newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +function createCheckpoint(checkpoint, channels, step, options) { + let values; + if (channels === undefined) + values = checkpoint.channel_values; + else { + values = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) + continue; + try { + values[k] = channels[k].checkpoint(); + } catch (error90) { + if (error90.name === EmptyChannelError.unminifiable_name) {} else + throw error90; } - const node = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, start, null, props, onError2); - if (ctx.schema.compat) - utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError2); - offset = node.range[2]; - seq.items.push(node); } - seq.range = [bs.offset, offset, commentEnd ?? offset]; - return seq; } - exports.resolveBlockSeq = resolveBlockSeq; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-end.js -var require_resolve_end = __commonJS((exports) => { - function resolveEnd(end, offset, reqSpace, onError2) { - let comment = ""; - if (end) { - let hasSpace = false; - let sep2 = ""; - for (const token of end) { - const { source, type } = token; - switch (type) { - case "space": - hasSpace = true; - break; - case "comment": { - if (reqSpace && !hasSpace) - onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); - const cb = source.substring(1) || " "; - if (!comment) - comment = cb; - else - comment += sep2 + cb; - sep2 = ""; - break; - } - case "newline": - if (comment) - sep2 += source; - hasSpace = true; - break; - default: - onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); - } - offset += source.length; - } + return { + v: 4, + id: options?.id ?? uuid63(step), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: values, + channel_versions: checkpoint.channel_versions, + versions_seen: checkpoint.versions_seen + }; +} +var BaseChannel = class { + ValueType; + UpdateType; + lg_is_channel = true; + consume() { + return false; + } + finish() { + return false; + } + isAvailable() { + try { + this.get(); + return true; + } catch (error90) { + if (error90.name === EmptyChannelError.unminifiable_name) + return false; + throw error90; } - return { comment, offset }; } - exports.resolveEnd = resolveEnd; + equals(other) { + return this === other; + } +}, IS_ONLY_BASE_CHANNEL; +var init_base15 = __esm(() => { + init_errors7(); + init_dist3(); + IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-flow-collection.js -var require_resolve_flow_collection = __commonJS((exports) => { - var identity = require_identity(); - var Pair = require_Pair(); - var YAMLMap = require_YAMLMap(); - var YAMLSeq = require_YAMLSeq(); - var resolveEnd = require_resolve_end(); - var resolveProps = require_resolve_props(); - var utilContainsNewline = require_util_contains_newline(); - var utilMapIncludes = require_util_map_includes(); - var blockMsg = "Block collections are not allowed within flow collections"; - var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); - function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError2, tag) { - const isMap = fc.start.source === "{"; - const fcName = isMap ? "flow map" : "flow sequence"; - const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq); - const coll = new NodeClass(ctx.schema); - coll.flow = true; - const atRoot = ctx.atRoot; - if (atRoot) - ctx.atRoot = false; - if (ctx.atKey) - ctx.atKey = false; - let offset = fc.offset + fc.start.source.length; - for (let i = 0;i < fc.items.length; ++i) { - const collItem = fc.items[i]; - const { start, key, sep: sep2, value } = collItem; - const props = resolveProps.resolveProps(start, { - flow: fcName, - indicator: "explicit-key-ind", - next: key ?? sep2?.[0], - offset, - onError: onError2, - parentIndent: fc.indent, - startOnNewline: false - }); - if (!props.found) { - if (!props.anchor && !props.tag && !sep2 && !value) { - if (i === 0 && props.comma) - onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); - else if (i < fc.items.length - 1) - onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); - if (props.comment) { - if (coll.comment) - coll.comment += ` -` + props.comment; - else - coll.comment = props.comment; - } - offset = props.end; - continue; - } - if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) - onError2(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); - } - if (i === 0) { - if (props.comma) - onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); - } else { - if (!props.comma) - onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); - if (props.comment) { - let prevItemComment = ""; - loop: - for (const st of start) { - switch (st.type) { - case "comma": - case "space": - break; - case "comment": - prevItemComment = st.source.substring(1); - break loop; - default: - break loop; - } - } - if (prevItemComment) { - let prev = coll.items[coll.items.length - 1]; - if (identity.isPair(prev)) - prev = prev.value ?? prev.key; - if (prev.comment) - prev.comment += ` -` + prevItemComment; - else - prev.comment = prevItemComment; - props.comment = props.comment.substring(prevItemComment.length + 1); - } - } - } - if (!isMap && !sep2 && !props.found) { - const valueNode = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, sep2, null, props, onError2); - coll.items.push(valueNode); - offset = valueNode.range[2]; - if (isBlock(value)) - onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); - } else { - ctx.atKey = true; - const keyStart = props.end; - const keyNode = key ? composeNode(ctx, key, props, onError2) : composeEmptyNode(ctx, keyStart, start, null, props, onError2); - if (isBlock(key)) - onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg); - ctx.atKey = false; - const valueProps = resolveProps.resolveProps(sep2 ?? [], { - flow: fcName, - indicator: "map-value-ind", - next: value, - offset: keyNode.range[2], - onError: onError2, - parentIndent: fc.indent, - startOnNewline: false - }); - if (valueProps.found) { - if (!isMap && !props.found && ctx.options.strict) { - if (sep2) - for (const st of sep2) { - if (st === valueProps.found) - break; - if (st.type === "newline") { - onError2(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); - break; - } - } - if (props.start < valueProps.found.offset - 1024) - onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); - } - } else if (value) { - if ("source" in value && value.source?.[0] === ":") - onError2(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); - else - onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); - } - const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep2, null, valueProps, onError2) : null; - if (valueNode) { - if (isBlock(value)) - onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); - } else if (valueProps.comment) { - if (keyNode.comment) - keyNode.comment += ` -` + valueProps.comment; - else - keyNode.comment = valueProps.comment; - } - const pair = new Pair.Pair(keyNode, valueNode); - if (ctx.options.keepSourceTokens) - pair.srcToken = collItem; - if (isMap) { - const map2 = coll; - if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode)) - onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); - map2.items.push(pair); - } else { - const map2 = new YAMLMap.YAMLMap(ctx.schema); - map2.flow = true; - map2.items.push(pair); - const endRange = (valueNode ?? keyNode).range; - map2.range = [keyNode.range[0], endRange[1], endRange[2]]; - coll.items.push(map2); - } - offset = valueNode ? valueNode.range[2] : valueProps.end; - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/binop.js +var isBinaryOperatorAggregate = (value) => { + return value != null && value.lc_graph_name === "BinaryOperatorAggregate"; +}, BinaryOperatorAggregate; +var init_binop = __esm(() => { + init_constants3(); + init_errors7(); + init_base15(); + BinaryOperatorAggregate = class BinaryOperatorAggregate2 extends BaseChannel { + lc_graph_name = "BinaryOperatorAggregate"; + value; + operator; + initialValueFactory; + constructor(operator, initialValueFactory) { + super(); + this.operator = operator; + this.initialValueFactory = initialValueFactory; + this.value = initialValueFactory?.(); } - const expectedEnd = isMap ? "}" : "]"; - const [ce, ...ee] = fc.end; - let cePos = offset; - if (ce?.source === expectedEnd) - cePos = ce.offset + ce.source.length; - else { - const name = fcName[0].toUpperCase() + fcName.substring(1); - const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; - onError2(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); - if (ce && ce.source.length !== 1) - ee.unshift(ce); + fromCheckpoint(checkpoint) { + const empty = new BinaryOperatorAggregate2(this.operator, this.initialValueFactory); + if (typeof checkpoint !== "undefined") + empty.value = checkpoint; + return empty; } - if (ee.length > 0) { - const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError2); - if (end.comment) { - if (coll.comment) - coll.comment += ` -` + end.comment; + update(values) { + let newValues = values; + if (!newValues.length) + return false; + if (this.value === undefined) { + const first = newValues[0]; + const [isOverwrite, overwriteVal] = _getOverwriteValue(first); + if (isOverwrite) + this.value = overwriteVal; else - coll.comment = end.comment; + this.value = first; + newValues = newValues.slice(1); } - coll.range = [fc.offset, cePos, end.offset]; - } else { - coll.range = [fc.offset, cePos, cePos]; + let seenOverwrite = false; + for (const incoming of newValues) + if (_isOverwriteValue(incoming)) { + if (seenOverwrite) + throw new InvalidUpdateError("Can receive only one Overwrite value per step."); + const [, val] = _getOverwriteValue(incoming); + this.value = val; + seenOverwrite = true; + continue; + } else if (!seenOverwrite && this.value !== undefined) + this.value = this.operator(this.value, incoming); + return true; } - return coll; - } - exports.resolveFlowCollection = resolveFlowCollection; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/compose-collection.js -var require_compose_collection = __commonJS((exports) => { - var identity = require_identity(); - var Scalar = require_Scalar(); - var YAMLMap = require_YAMLMap(); - var YAMLSeq = require_YAMLSeq(); - var resolveBlockMap = require_resolve_block_map(); - var resolveBlockSeq = require_resolve_block_seq(); - var resolveFlowCollection = require_resolve_flow_collection(); - function resolveCollection(CN, ctx, token, onError2, tagName, tag) { - const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError2, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError2, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError2, tag); - const Coll = coll.constructor; - if (tagName === "!" || tagName === Coll.tagName) { - coll.tag = Coll.tagName; - return coll; + get() { + if (this.value === undefined) + throw new EmptyChannelError; + return this.value; } - if (tagName) - coll.tag = tagName; - return coll; - } - function composeCollection(CN, ctx, token, props, onError2) { - const tagToken = props.tag; - const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)); - if (token.type === "block-seq") { - const { anchor, newlineAfterProp: nl } = props; - const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; - if (lastProp && (!nl || nl.offset < lastProp.offset)) { - const message = "Missing newline after block sequence props"; - onError2(lastProp, "MISSING_CHAR", message); - } + checkpoint() { + if (this.value === undefined) + throw new EmptyChannelError; + return this.value; } - const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; - if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") { - return resolveCollection(CN, ctx, token, onError2, tagName); + isAvailable() { + return this.value !== undefined; } - let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); - if (!tag) { - const kt = ctx.schema.knownTags[tagName]; - if (kt?.collection === expType) { - ctx.schema.tags.push(Object.assign({}, kt, { default: false })); - tag = kt; - } else { - if (kt) { - onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); - } else { - onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); - } - return resolveCollection(CN, ctx, token, onError2, tagName); - } + equals(other) { + if (this === other) + return true; + if (!isBinaryOperatorAggregate(other)) + return false; + return this.operator === other.operator; } - const coll = resolveCollection(CN, ctx, token, onError2, tagName, tag); - const res = tag.resolve?.(coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; - const node = identity.isNode(res) ? res : new Scalar.Scalar(res); - node.range = coll.range; - node.tag = tagName; - if (tag?.format) - node.format = tag.format; - return node; - } - exports.composeCollection = composeCollection; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-block-scalar.js -var require_resolve_block_scalar = __commonJS((exports) => { - var Scalar = require_Scalar(); - function resolveBlockScalar(ctx, scalar, onError2) { - const start = scalar.offset; - const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2); - if (!header) - return { value: "", type: null, comment: "", range: [start, start, start] }; - const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; - const lines = scalar.source ? splitLines(scalar.source) : []; - let chompStart = lines.length; - for (let i = lines.length - 1;i >= 0; --i) { - const content = lines[i][1]; - if (content === "" || content === "\r") - chompStart = i; - else - break; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/last_value.js +var LastValue, LastValueAfterFinish; +var init_last_value = __esm(() => { + init_errors7(); + init_base15(); + LastValue = class LastValue2 extends BaseChannel { + lc_graph_name = "LastValue"; + value = []; + constructor(initialValueFactory) { + super(); + this.initialValueFactory = initialValueFactory; + if (initialValueFactory) + this.value = [initialValueFactory()]; } - if (chompStart === 0) { - const value2 = header.chomp === "+" && lines.length > 0 ? ` -`.repeat(Math.max(1, lines.length - 1)) : ""; - let end2 = start + header.length; - if (scalar.source) - end2 += scalar.source.length; - return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; + fromCheckpoint(checkpoint) { + const empty = new LastValue2(this.initialValueFactory); + if (typeof checkpoint !== "undefined") + empty.value = [checkpoint]; + return empty; } - let trimIndent = scalar.indent + header.indent; - let offset = scalar.offset + header.length; - let contentStart = 0; - for (let i = 0;i < chompStart; ++i) { - const [indent, content] = lines[i]; - if (content === "" || content === "\r") { - if (header.indent === 0 && indent.length > trimIndent) - trimIndent = indent.length; - } else { - if (indent.length < trimIndent) { - const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; - onError2(offset + indent.length, "MISSING_CHAR", message); - } - if (header.indent === 0) - trimIndent = indent.length; - contentStart = i; - if (trimIndent === 0 && !ctx.atRoot) { - const message = "Block scalar values in collections must be indented"; - onError2(offset, "BAD_INDENT", message); - } - break; - } - offset += indent.length + content.length + 1; + update(values) { + if (values.length === 0) + return false; + if (values.length !== 1) + throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this.value = [values[values.length - 1]]; + return true; } - for (let i = lines.length - 1;i >= chompStart; --i) { - if (lines[i][0].length > trimIndent) - chompStart = i + 1; + get() { + if (this.value.length === 0) + throw new EmptyChannelError; + return this.value[0]; } - let value = ""; - let sep2 = ""; - let prevMoreIndented = false; - for (let i = 0;i < contentStart; ++i) - value += lines[i][0].slice(trimIndent) + ` -`; - for (let i = contentStart;i < chompStart; ++i) { - let [indent, content] = lines[i]; - offset += indent.length + content.length + 1; - const crlf = content[content.length - 1] === "\r"; - if (crlf) - content = content.slice(0, -1); - if (content && indent.length < trimIndent) { - const src = header.indent ? "explicit indentation indicator" : "first line"; - const message = `Block scalar lines must not be less indented than their ${src}`; - onError2(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); - indent = ""; - } - if (type === Scalar.Scalar.BLOCK_LITERAL) { - value += sep2 + indent.slice(trimIndent) + content; - sep2 = ` -`; - } else if (indent.length > trimIndent || content[0] === "\t") { - if (sep2 === " ") - sep2 = ` -`; - else if (!prevMoreIndented && sep2 === ` -`) - sep2 = ` - -`; - value += sep2 + indent.slice(trimIndent) + content; - sep2 = ` -`; - prevMoreIndented = true; - } else if (content === "") { - if (sep2 === ` -`) - value += ` -`; - else - sep2 = ` -`; - } else { - value += sep2 + content; - sep2 = " "; - prevMoreIndented = false; + checkpoint() { + if (this.value.length === 0) + throw new EmptyChannelError; + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } + }; + LastValueAfterFinish = class LastValueAfterFinish2 extends BaseChannel { + lc_graph_name = "LastValueAfterFinish"; + value = []; + finished = false; + fromCheckpoint(checkpoint) { + const empty = new LastValueAfterFinish2; + if (typeof checkpoint !== "undefined") { + const [value, finished] = checkpoint; + empty.value = [value]; + empty.finished = finished; } + return empty; } - switch (header.chomp) { - case "-": - break; - case "+": - for (let i = chompStart;i < lines.length; ++i) - value += ` -` + lines[i][0].slice(trimIndent); - if (value[value.length - 1] !== ` -`) - value += ` -`; - break; - default: - value += ` -`; + update(values) { + if (values.length === 0) + return false; + this.finished = false; + this.value = [values[values.length - 1]]; + return true; } - const end = start + header.length + scalar.source.length; - return { value, type, comment: header.comment, range: [start, end, end] }; - } - function parseBlockScalarHeader({ offset, props }, strict, onError2) { - if (props[0].type !== "block-scalar-header") { - onError2(props[0], "IMPOSSIBLE", "Block scalar header not found"); - return null; + get() { + if (this.value.length === 0 || !this.finished) + throw new EmptyChannelError; + return this.value[0]; } - const { source } = props[0]; - const mode = source[0]; - let indent = 0; - let chomp = ""; - let error51 = -1; - for (let i = 1;i < source.length; ++i) { - const ch = source[i]; - if (!chomp && (ch === "-" || ch === "+")) - chomp = ch; - else { - const n3 = Number(ch); - if (!indent && n3) - indent = n3; - else if (error51 === -1) - error51 = offset + i; + checkpoint() { + if (this.value.length === 0) + return; + return [this.value[0], this.finished]; + } + consume() { + if (this.finished) { + this.finished = false; + this.value = []; + return true; } + return false; } - if (error51 !== -1) - onError2(error51, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); - let hasSpace = false; - let comment = ""; - let length = source.length; - for (let i = 1;i < props.length; ++i) { - const token = props[i]; - switch (token.type) { - case "space": - hasSpace = true; - case "newline": - length += token.source.length; - break; - case "comment": - if (strict && !hasSpace) { - const message = "Comments must be separated from other tokens by white space characters"; - onError2(token, "MISSING_CHAR", message); - } - length += token.source.length; - comment = token.source.substring(1); - break; - case "error": - onError2(token, "UNEXPECTED_TOKEN", token.message); - length += token.source.length; - break; - default: { - const message = `Unexpected token in block scalar header: ${token.type}`; - onError2(token, "UNEXPECTED_TOKEN", message); - const ts = token.source; - if (ts && typeof ts === "string") - length += ts.length; - } + finish() { + if (!this.finished && this.value.length > 0) { + this.finished = true; + return true; } + return false; } - return { mode, indent, chomp, comment, length }; + isAvailable() { + return this.value.length !== 0 && this.finished; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/annotation.js +function getChannel(reducer) { + if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) + return new BinaryOperatorAggregate(reducer.reducer, reducer.default); + if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) + return new BinaryOperatorAggregate(reducer.value, reducer.default); + return new LastValue; +} +var AnnotationRoot = class { + lc_graph_name = "AnnotationRoot"; + spec; + constructor(s) { + this.spec = s; } - function splitLines(source) { - const split = source.split(/\n( *)/); - const first = split[0]; - const m = first.match(/^( *)/); - const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; - const lines = [line0]; - for (let i = 1;i < split.length; i += 2) - lines.push([split[i], split[i + 1]]); - return lines; + static isInstance(value) { + return typeof value === "object" && value !== null && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot"; } - exports.resolveBlockScalar = resolveBlockScalar; +}, Annotation = function(annotation) { + if (annotation) + return getChannel(annotation); + else + return new LastValue; +}; +var init_annotation = __esm(() => { + init_binop(); + init_last_value(); + Annotation.Root = (sd) => new AnnotationRoot(sd); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/resolve-flow-scalar.js -var require_resolve_flow_scalar = __commonJS((exports) => { - var Scalar = require_Scalar(); - var resolveEnd = require_resolve_end(); - function resolveFlowScalar(scalar, strict, onError2) { - const { offset, type, source, end } = scalar; - let _type; - let value; - const _onError = (rel, code, msg) => onError2(offset + rel, code, msg); - switch (type) { - case "scalar": - _type = Scalar.Scalar.PLAIN; - value = plainValue(source, _onError); - break; - case "single-quoted-scalar": - _type = Scalar.Scalar.QUOTE_SINGLE; - value = singleQuotedValue(source, _onError); - break; - case "double-quoted-scalar": - _type = Scalar.Scalar.QUOTE_DOUBLE; - value = doubleQuotedValue(source, _onError); - break; - default: - onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); - return { - value: "", - type: null, - comment: "", - range: [offset, offset + source.length, offset + source.length] - }; - } - const valueEnd = offset + source.length; - const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError2); - return { - value, - type: _type, - comment: re.comment, - range: [offset, valueEnd, re.offset] - }; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/utils/config.js +function propagateConfigurableToMetadata(configurable, metadata) { + if (!configurable) + return metadata; + const result = metadata ?? {}; + for (const key of PROPAGATE_TO_METADATA) { + if (key in result) + continue; + const value = configurable[key]; + if (value !== undefined) + result[key] = value; } - function plainValue(source, onError2) { - let badChar = ""; - switch (source[0]) { - case "\t": - badChar = "a tab character"; - break; - case ",": - badChar = "flow indicator character ,"; - break; - case "%": - badChar = "directive indicator character %"; - break; - case "|": - case ">": { - badChar = `block scalar indicator ${source[0]}`; - break; - } - case "@": - case "`": { - badChar = `reserved character ${source[0]}`; - break; - } - } - if (badChar) - onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); - return foldLines(source); + return result; +} +function ensureLangGraphConfig(...configs) { + const empty = { + tags: [], + metadata: {}, + callbacks: undefined, + recursionLimit: DEFAULT_RECURSION_LIMIT, + configurable: {} + }; + const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (implicitConfig !== undefined) { + for (const [k, v] of Object.entries(implicitConfig)) + if (v !== undefined) + if (COPIABLE_KEYS.includes(k)) { + let copiedValue; + if (Array.isArray(v)) + copiedValue = [...v]; + else if (typeof v === "object") + if (k === "callbacks" && "copy" in v && typeof v.copy === "function") + copiedValue = v.copy(); + else + copiedValue = { ...v }; + else + copiedValue = v; + empty[k] = copiedValue; + } else + empty[k] = v; } - function singleQuotedValue(source, onError2) { - if (source[source.length - 1] !== "'" || source.length === 1) - onError2(source.length, "MISSING_CHAR", "Missing closing 'quote"); - return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + for (const config3 of configs) { + if (config3 === undefined) + continue; + for (const [k, v] of Object.entries(config3)) + if (v !== undefined && CONFIG_KEYS.includes(k)) + empty[k] = v; } - function foldLines(source) { - let first, line; - try { - first = new RegExp(`(.*?)(? !part.match(/^\d+$/)).map((part) => part.split(":")[0]).join("|"); +} +function getParentCheckpointNamespace(namespace) { + const parts = namespace.split("|"); + while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) + parts.pop(); + return parts.slice(0, -1).join("|"); +} +var COPIABLE_KEYS, CONFIG_KEYS, DEFAULT_RECURSION_LIMIT = 25, PROPAGATE_TO_METADATA; +var init_config2 = __esm(() => { + init_constants3(); + init_singletons(); + COPIABLE_KEYS = [ + "tags", + "metadata", + "callbacks", + "configurable" + ]; + CONFIG_KEYS = [ + "tags", + "metadata", + "callbacks", + "runName", + "maxConcurrency", + "recursionLimit", + "configurable", + "runId", + "outputKeys", + "streamMode", + "store", + "writer", + "interrupt", + "context", + "interruptBefore", + "interruptAfter", + "checkpointDuring", + "durability", + "signal", + "executionInfo", + "serverInfo" + ]; + PROPAGATE_TO_METADATA = new Set([ + "thread_id", + "checkpoint_id", + "checkpoint_ns", + "task_id", + "run_id", + "assistant_id", + "graph_id" + ]); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/stream-channel.js +function isStreamChannel(value) { + return StreamChannel.isInstance(value); +} +var STREAM_CHANNEL_BRAND, StreamChannel; +var init_stream_channel = __esm(() => { + STREAM_CHANNEL_BRAND = Symbol.for("langgraph.stream_channel"); + StreamChannel = class StreamChannel2 { + [STREAM_CHANNEL_BRAND] = true; + channelName; + #items = []; + #waiters = []; + #done = false; + #error; + #onPush; + constructor(name) { + this.channelName = name; } - let match2 = first.exec(source); - if (!match2) - return source; - let res = match2[1]; - let sep2 = " "; - let pos = first.lastIndex; - line.lastIndex = pos; - while (match2 = line.exec(source)) { - if (match2[1] === "") { - if (sep2 === ` -`) - res += sep2; - else - sep2 = ` -`; - } else { - res += sep2 + match2[1]; - sep2 = " "; - } - pos = line.lastIndex; + static local() { + return new StreamChannel2; } - const last = /[ \t]*(.*)/sy; - last.lastIndex = pos; - match2 = last.exec(source); - return res + sep2 + (match2?.[1] ?? ""); - } - function doubleQuotedValue(source, onError2) { - let res = ""; - for (let i = 1;i < source.length - 1; ++i) { - const ch = source[i]; - if (ch === "\r" && source[i + 1] === ` -`) - continue; - if (ch === ` -`) { - const { fold, offset } = foldNewline(source, i); - res += fold; - i = offset; - } else if (ch === "\\") { - let next = source[++i]; - const cc = escapeCodes[next]; - if (cc) - res += cc; - else if (next === ` -`) { - next = source[i + 1]; - while (next === " " || next === "\t") - next = source[++i + 1]; - } else if (next === "\r" && source[i + 1] === ` -`) { - next = source[++i + 1]; - while (next === " " || next === "\t") - next = source[++i + 1]; - } else if (next === "x" || next === "u" || next === "U") { - const length = next === "x" ? 2 : next === "u" ? 4 : 8; - res += parseCharCode(source, i + 1, length, onError2); - i += length; - } else { - const raw2 = source.substr(i - 1, 2); - onError2(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`); - res += raw2; - } - } else if (ch === " " || ch === "\t") { - const wsStart = i; - let next = source[i + 1]; - while (next === " " || next === "\t") - next = source[++i + 1]; - if (next !== ` -` && !(next === "\r" && source[i + 2] === ` -`)) - res += i > wsStart ? source.slice(wsStart, i + 1) : ch; - } else { - res += ch; - } + static remote(name) { + return new StreamChannel2(name); } - if (source[source.length - 1] !== '"' || source.length === 1) - onError2(source.length, "MISSING_CHAR", 'Missing closing "quote'); - return res; - } - function foldNewline(source, offset) { - let fold = ""; - let ch = source[offset + 1]; - while (ch === " " || ch === "\t" || ch === ` -` || ch === "\r") { - if (ch === "\r" && source[offset + 2] !== ` -`) - break; - if (ch === ` -`) - fold += ` -`; - offset += 1; - ch = source[offset + 1]; + static isInstance(value) { + return typeof value === "object" && value !== null && STREAM_CHANNEL_BRAND in value && value[STREAM_CHANNEL_BRAND] === true; } - if (!fold) - fold = " "; - return { fold, offset }; - } - var escapeCodes = { - "0": "\x00", - a: "\x07", - b: "\b", - e: "\x1B", - f: "\f", - n: ` -`, - r: "\r", - t: "\t", - v: "\v", - N: "…", - _: " ", - L: "\u2028", - P: "\u2029", - " ": " ", - '"': '"', - "/": "/", - "\\": "\\", - "\t": "\t" - }; - function parseCharCode(source, offset, length, onError2) { - const cc = source.substr(offset, length); - const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); - const code = ok ? parseInt(cc, 16) : NaN; - try { - return String.fromCodePoint(code); - } catch { - const raw2 = source.substr(offset - 2, length + 2); - onError2(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`); - return raw2; + push(item) { + this.#items.push(item); + this.#wake(); + this.#onPush?.(item); } - } - exports.resolveFlowScalar = resolveFlowScalar; -}); + iterate(startAt = 0) { + let cursor = startAt; + return { next: async () => { + while (true) { + if (cursor < this.#items.length) + return { + value: this.#items[cursor++], + done: false + }; + if (this.#done) { + if (this.#error) + throw this.#error; + return { + value: undefined, + done: true + }; + } + await new Promise((resolve2) => this.#waiters.push(resolve2)); + } + } }; + } + toAsyncIterable(startAt = 0) { + return { [Symbol.asyncIterator]: () => this.iterate(startAt) }; + } + toEventStream(options = {}) { + const encoder2 = new TextEncoder; + const iterator = this.iterate(options.startAt); + const event = options.event ?? this.channelName; + const serialize2 = options.serialize ?? ((item) => JSON.stringify(item) ?? "null"); + return new ReadableStream({ + async pull(controller) { + try { + const next = await iterator.next(); + if (next.done) { + controller.close(); + return; + } + const lines = []; + if (event != null) + lines.push(`event: ${event}`); + for (const line of serialize2(next.value).split(/\r\n|\r|\n/)) + lines.push(`data: ${line}`); + controller.enqueue(encoder2.encode(`${lines.join(` +`)} -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/compose-scalar.js -var require_compose_scalar = __commonJS((exports) => { - var identity = require_identity(); - var Scalar = require_Scalar(); - var resolveBlockScalar = require_resolve_block_scalar(); - var resolveFlowScalar = require_resolve_flow_scalar(); - function composeScalar(ctx, token, tagToken, onError2) { - const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError2) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError2); - const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; - let tag; - if (ctx.options.stringKeys && ctx.atKey) { - tag = ctx.schema[identity.SCALAR]; - } else if (tagName) - tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError2); - else if (token.type === "scalar") - tag = findScalarTagByTest(ctx, value, token, onError2); - else - tag = ctx.schema[identity.SCALAR]; - let scalar; - try { - const res = tag.resolve(value, (msg) => onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); - scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); - } catch (error51) { - const msg = error51 instanceof Error ? error51.message : String(error51); - onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); - scalar = new Scalar.Scalar(value); +`)); + } catch (error90) { + controller.error(error90); + } + }, + async cancel() { + await iterator.return?.(); + } + }); } - scalar.range = range; - scalar.source = value; - if (type) - scalar.type = type; - if (tagName) - scalar.tag = tagName; - if (tag.format) - scalar.format = tag.format; - if (comment) - scalar.comment = comment; - return scalar; - } - function findScalarTagByName(schema, value, tagName, tagToken, onError2) { - if (tagName === "!") - return schema[identity.SCALAR]; - const matchWithTest = []; - for (const tag of schema.tags) { - if (!tag.collection && tag.tag === tagName) { - if (tag.default && tag.test) - matchWithTest.push(tag); - else - return tag; - } + get(index2) { + if (index2 < 0 || index2 >= this.#items.length) + throw new RangeError(`StreamChannel index ${index2} out of bounds (size=${this.#items.length})`); + return this.#items[index2]; } - for (const tag of matchWithTest) - if (tag.test?.test(value)) - return tag; - const kt = schema.knownTags[tagName]; - if (kt && !kt.collection) { - schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); - return kt; + get size() { + return this.#items.length; } - onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); - return schema[identity.SCALAR]; - } - function findScalarTagByTest({ atKey, directives, schema }, value, token, onError2) { - const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR]; - if (schema.compat) { - const compat2 = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR]; - if (tag.tag !== compat2.tag) { - const ts = directives.tagString(tag.tag); - const cs = directives.tagString(compat2.tag); - const msg = `Value may be parsed as either ${ts} or ${cs}`; - onError2(token, "TAG_RESOLVE_FAILED", msg, true); - } + get done() { + return this.#done; } - return tag; - } - exports.composeScalar = composeScalar; + close() { + this.#done = true; + this.#wake(); + } + fail(err) { + this.#error = err; + this.#done = true; + this.#wake(); + } + _wire(fn) { + this.#onPush = fn; + } + _close() { + this.close(); + } + _fail(err) { + this.fail(err); + } + [Symbol.asyncIterator]() { + return this.iterate(); + } + #wake() { + const waiters = this.#waiters.splice(0); + for (const w of waiters) + w(); + } + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/util-empty-scalar-position.js -var require_util_empty_scalar_position = __commonJS((exports) => { - function emptyScalarPosition(offset, before, pos) { - if (before) { - pos ?? (pos = before.length); - for (let i = pos - 1;i >= 0; --i) { - let st = before[i]; - switch (st.type) { - case "space": - case "comment": - case "newline": - offset -= st.source.length; - continue; - } - st = before[++i]; - while (st?.type === "space") { - offset += st.source.length; - st = before[++i]; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/convert.js +function unwrapMessagesPayload(payload) { + if (!Array.isArray(payload) || payload.length !== 2) + return { data: payload }; + const [data, metadata] = payload; + if (metadata == null || typeof metadata !== "object") + return { data: payload }; + const record3 = metadata; + const node = typeof record3.langgraph_node === "string" ? record3.langgraph_node : undefined; + const runId = typeof record3.run_id === "string" ? record3.run_id : undefined; + return { + data: runId != null && data != null && typeof data === "object" ? { + ...data, + run_id: runId + } : data, + node + }; +} +function convertToProtocolEvent({ namespace: ns3, mode, payload, seq, meta: meta3 }) { + const timestamp = Date.now(); + const base = { type: "event" }; + switch (mode) { + case "messages": { + const { data, node } = unwrapMessagesPayload(payload); + return [{ + ...base, + seq, + method: "messages", + params: { + namespace: ns3, + timestamp, + ...node ? { node } : {}, + data } - break; - } + }]; } - return offset; - } - exports.emptyScalarPosition = emptyScalarPosition; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/compose-node.js -var require_compose_node = __commonJS((exports) => { - var Alias = require_Alias(); - var identity = require_identity(); - var composeCollection = require_compose_collection(); - var composeScalar = require_compose_scalar(); - var resolveEnd = require_resolve_end(); - var utilEmptyScalarPosition = require_util_empty_scalar_position(); - var CN = { composeNode, composeEmptyNode }; - function composeNode(ctx, token, props, onError2) { - const atKey = ctx.atKey; - const { spaceBefore, comment, anchor, tag } = props; - let node; - let isSrcToken = true; - switch (token.type) { - case "alias": - node = composeAlias(ctx, token, onError2); - if (anchor || tag) - onError2(token, "ALIAS_PROPS", "An alias node must not specify any properties"); - break; - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": - case "block-scalar": - node = composeScalar.composeScalar(ctx, token, tag, onError2); - if (anchor) - node.anchor = anchor.source.substring(1); - break; - case "block-map": - case "block-seq": - case "flow-collection": - try { - node = composeCollection.composeCollection(CN, ctx, token, props, onError2); - if (anchor) - node.anchor = anchor.source.substring(1); - } catch (error51) { - const message = error51 instanceof Error ? error51.message : String(error51); - onError2(token, "RESOURCE_EXHAUSTION", message); + case "tools": + return [{ + ...base, + seq, + method: "tools", + params: { + namespace: ns3, + timestamp, + data: convertToolsPayload(payload) } - break; - default: { - const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; - onError2(token, "UNEXPECTED_TOKEN", message); - isSrcToken = false; - } + }]; + case "values": { + const events = []; + if (meta3?.checkpoint != null) + events.push({ + ...base, + seq, + method: "checkpoints", + params: { + namespace: ns3, + timestamp, + data: meta3.checkpoint + } + }); + events.push({ + ...base, + seq: meta3?.checkpoint != null ? seq + 1 : seq, + method: "values", + params: { + namespace: ns3, + timestamp, + data: payload + } + }); + return events; } - node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError2)); - if (anchor && node.anchor === "") - onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); - if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { - const msg = "With stringKeys, all keys must be strings"; - onError2(tag ?? token, "NON_STRING_KEY", msg); + case "updates": { + const data = convertUpdatesPayload(payload); + return [{ + ...base, + seq, + method: "updates", + params: { + namespace: ns3, + timestamp, + ...typeof data.node === "string" ? { node: data.node } : {}, + data + } + }]; } - if (spaceBefore) - node.spaceBefore = true; - if (comment) { - if (token.type === "scalar" && token.source === "") - node.comment = comment; - else - node.commentBefore = comment; + case "custom": { + const data = typeof payload === "object" && payload !== null && !Array.isArray(payload) && "name" in payload ? payload : { payload }; + return [{ + ...base, + seq, + method: "custom", + params: { + namespace: ns3, + timestamp, + data + } + }]; } - if (ctx.options.keepSourceTokens && isSrcToken) - node.srcToken = token; - return node; + case "tasks": + return [{ + ...base, + seq, + method: "tasks", + params: { + namespace: ns3, + timestamp, + data: payload + } + }]; + default: + return []; } - function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError2) { - const token = { - type: "scalar", - offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), - indent: -1, - source: "" +} +function convertToolsPayload(payload) { + if (typeof payload !== "object" || payload === null) + return { + event: "tool-error", + tool_call_id: "", + message: "Unexpected tools payload shape" }; - const node = composeScalar.composeScalar(ctx, token, tag, onError2); - if (anchor) { - node.anchor = anchor.source.substring(1); - if (node.anchor === "") - onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); - } - if (spaceBefore) - node.spaceBefore = true; - if (comment) { - node.comment = comment; - node.range[2] = end; + const p = payload; + const tool_call_id = String(p.toolCallId ?? ""); + switch (p.event) { + case "on_tool_start": + return { + event: "tool-started", + tool_call_id, + tool_name: String(p.name ?? "unknown"), + input: p.input + }; + case "on_tool_event": + return { + event: "tool-output-delta", + tool_call_id, + delta: typeof p.data === "string" ? p.data : JSON.stringify(p.data ?? "") + }; + case "on_tool_end": + return { + event: "tool-finished", + tool_call_id, + output: p.output + }; + case "on_tool_error": { + const err = p.error; + return { + event: "tool-error", + tool_call_id, + message: typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err ?? "unknown error") + }; } - return node; - } - function composeAlias({ options }, { offset, source, end }, onError2) { - const alias = new Alias.Alias(source.substring(1)); - if (alias.source === "") - onError2(offset, "BAD_ALIAS", "Alias cannot be an empty string"); - if (alias.source.endsWith(":")) - onError2(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); - const valueEnd = offset + source.length; - const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError2); - alias.range = [offset, valueEnd, re.offset]; - if (re.comment) - alias.comment = re.comment; - return alias; + default: + return { + event: "tool-error", + tool_call_id: "", + message: `Unknown tool event: ${String(p.event)}` + }; } - exports.composeEmptyNode = composeEmptyNode; - exports.composeNode = composeNode; -}); +} +function convertUpdatesPayload(payload) { + if (typeof payload !== "object" || payload === null) + return { values: {} }; + const entries = Object.entries(payload); + if (entries.length === 0) + return { values: {} }; + const [node, values] = entries[0]; + return { + node, + values: typeof values === "object" && values !== null ? values : { value: values } + }; +} +var STREAM_EVENTS_V3_MODES; +var init_convert = __esm(() => { + STREAM_EVENTS_V3_MODES = [ + "values", + "updates", + "messages", + "tools", + "custom", + "tasks" + ]; +}); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/compose-doc.js -var require_compose_doc = __commonJS((exports) => { - var Document2 = require_Document(); - var composeNode = require_compose_node(); - var resolveEnd = require_resolve_end(); - var resolveProps = require_resolve_props(); - function composeDoc(options, directives, { offset, start, value, end }, onError2) { - const opts = Object.assign({ _directives: directives }, options); - const doc2 = new Document2.Document(undefined, opts); - const ctx = { - atKey: false, - atRoot: true, - directives: doc2.directives, - options: doc2.options, - schema: doc2.schema - }; - const props = resolveProps.resolveProps(start, { - indicator: "doc-start", - next: value ?? end?.[0], - offset, - onError: onError2, - parentIndent: 0, - startOnNewline: true - }); - if (props.found) { - doc2.directives.docStart = true; - if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) - onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/mux.js +function isPromiseLike(value) { + return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; +} +async function pump(source, mux) { + let seq = 0; + try { + for await (const chunk of source) { + const [ns3, mode, payload, meta3] = chunk; + if (mode === "values" && isInterrupted(payload)) { + const interrupts = payload[INTERRUPT]; + mux.markInterrupted(interrupts.map((i) => ({ + interruptId: i.id ?? "", + payload: i.value + }))); + } + const events = convertToProtocolEvent({ + namespace: ns3, + mode, + payload, + seq, + meta: meta3 + }); + seq += events.length; + for (const event of events) + mux.push(ns3, event); } - doc2.contents = value ? composeNode.composeNode(ctx, value, props, onError2) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError2); - const contentEnd = doc2.contents.range[2]; - const re = resolveEnd.resolveEnd(end, contentEnd, false, onError2); - if (re.comment) - doc2.comment = re.comment; - doc2.range = [offset, contentEnd, re.offset]; - return doc2; + } catch (err) { + mux.fail(err); + return; } - exports.composeDoc = composeDoc; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/compose/composer.js -var require_composer = __commonJS((exports) => { - var node_process = __require("process"); - var directives = require_directives(); - var Document2 = require_Document(); - var errors4 = require_errors(); - var identity = require_identity(); - var composeDoc = require_compose_doc(); - var resolveEnd = require_resolve_end(); - function getErrorPos(src) { - if (typeof src === "number") - return [src, src + 1]; - if (Array.isArray(src)) - return src.length === 2 ? src : [src[0], src[1]]; - const { offset, source } = src; - return [offset, offset + (typeof source === "string" ? source.length : 1)]; + mux.close(); +} +function nsKey(ns3) { + return ns3.join("\x00"); +} +function hasPrefix(ns3, prefix) { + if (prefix.length > ns3.length) + return false; + for (let i = 0;i < prefix.length; i += 1) + if (ns3[i] !== prefix[i]) + return false; + return true; +} +var RESOLVE_VALUES, REJECT_VALUES, StreamMux = class { + _events = StreamChannel.local(); + _discoveries = StreamChannel.local(); + #nextEmitSeq = 0; + #closed = false; + #error; + #interrupted = false; + #currentNamespace = []; + #transformers = []; + #channels = []; + #streamMap = /* @__PURE__ */ new Map; + #latestValues = /* @__PURE__ */ new Map; + #interrupts = []; + #finalValues = []; + register(path2, stream2) { + this.#streamMap.set(nsKey(path2), stream2); } - function parsePrelude(prelude) { - let comment = ""; - let atComment = false; - let afterEmptyLine = false; - for (let i = 0;i < prelude.length; ++i) { - const source = prelude[i]; - switch (source[0]) { - case "#": - comment += (comment === "" ? "" : afterEmptyLine ? ` - -` : ` -`) + (source.substring(1) || " "); - atComment = true; - afterEmptyLine = false; - break; - case "%": - if (prelude[i + 1]?.[0] !== "#") - i += 1; - atComment = false; - break; - default: - if (!atComment) - afterEmptyLine = true; - atComment = false; + addTransformer(transformer) { + const snapshot = this._events.size; + this.#transformers.push(transformer); + if (transformer.onRegister) + transformer.onRegister({ push: (ns3, event) => this.push(ns3, event) }); + for (let i = 0;i < snapshot; i += 1) + transformer.process(this._events.get(i)); + if (this.#closed) + if (this.#error !== undefined) + transformer.fail?.(this.#error); + else + transformer.finalize?.(); + } + wireChannels(projection) { + for (const [key, value] of Object.entries(projection)) { + if (isStreamChannel(value)) { + this.#channels.push(value); + if (typeof value.channelName !== "string") + continue; + value._wire((item) => { + this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method: value.channelName, + params: { + namespace: this.#currentNamespace, + timestamp: Date.now(), + data: item + } + }); + }); + continue; } + if (isPromiseLike(value)) + this.#finalValues.push({ + name: key, + promise: Promise.resolve(value) + }); } - return { comment, afterEmptyLine }; } - - class Composer { - constructor(options = {}) { - this.doc = null; - this.atDirectives = false; - this.prelude = []; - this.errors = []; - this.warnings = []; - this.onError = (source, code, message, warning) => { - const pos = getErrorPos(source); - if (warning) - this.warnings.push(new errors4.YAMLWarning(pos, code, message)); - else - this.errors.push(new errors4.YAMLParseError(pos, code, message)); - }; - this.directives = new directives.Directives({ version: options.version || "1.2" }); - this.options = options; + push(ns3, event) { + if (event.method === "values") + this.#latestValues.set(nsKey(ns3), event.params.data); + const outerNamespace = this.#currentNamespace; + this.#currentNamespace = ns3; + let keep = true; + for (const transformer of this.#transformers) + if (!transformer.process(event)) + keep = false; + this.#currentNamespace = outerNamespace; + if (keep) + this._events.push({ + ...event, + seq: this.#nextEmitSeq++ + }); + } + close() { + this.#closed = true; + for (const [key, values] of this.#latestValues.entries()) { + const ns3 = key ? key.split("\x00") : []; + this.#streamMap.get(nsKey(ns3))?.[RESOLVE_VALUES](values); } - decorate(doc2, afterDoc) { - const { comment, afterEmptyLine } = parsePrelude(this.prelude); - if (comment) { - const dc = doc2.contents; - if (afterDoc) { - doc2.comment = doc2.comment ? `${doc2.comment} -${comment}` : comment; - } else if (afterEmptyLine || doc2.directives.docStart || !dc) { - doc2.commentBefore = comment; - } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { - let it = dc.items[0]; - if (identity.isPair(it)) - it = it.key; - const cb = it.commentBefore; - it.commentBefore = cb ? `${comment} -${cb}` : comment; - } else { - const cb = dc.commentBefore; - dc.commentBefore = cb ? `${comment} -${cb}` : comment; - } + const finalizePromises = []; + for (const transformer of this.#transformers) { + const result = transformer.finalize?.(); + if (result != null && typeof result.then === "function") + finalizePromises.push(result); + } + for (const channel of this.#channels) + channel._close(); + const finalValues = this.#finalValues; + if (finalValues.length === 0 && finalizePromises.length === 0) { + this._events.close(); + this._discoveries.close(); + } else + Promise.allSettled([...finalizePromises, ...finalValues.map(async ({ name, promise: promise3 }) => { + try { + const resolved = await promise3; + if (!this._events.done) + this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method: "custom", + params: { + namespace: [], + timestamp: Date.now(), + data: { + name, + payload: resolved + } + } + }); + } catch {} + })]).then(() => { + this._events.close(); + this._discoveries.close(); + }); + for (const stream2 of this.#streamMap.values()) + stream2[RESOLVE_VALUES](undefined); + } + fail(err) { + this.#closed = true; + this.#error = err; + for (const transformer of this.#transformers) + transformer.fail?.(err); + for (const channel of this.#channels) + channel._fail(err); + this._events.fail(err); + this._discoveries.fail(err); + for (const stream2 of this.#streamMap.values()) + stream2[REJECT_VALUES](err); + } + markInterrupted(interrupts) { + this.#interrupted = true; + this.#interrupts.push(...interrupts); + } + get interrupted() { + return this.#interrupted; + } + get interrupts() { + return this.#interrupts; + } + subscribeEvents(path2, startAt = 0) { + const base = this._events.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return result; + if (hasPrefix(result.value.params.namespace, path2)) + return result; } - if (afterDoc) { - Array.prototype.push.apply(doc2.errors, this.errors); - Array.prototype.push.apply(doc2.warnings, this.warnings); - } else { - doc2.errors = this.errors; - doc2.warnings = this.warnings; + } }; + } +}; +var init_mux = __esm(() => { + init_constants3(); + init_stream_channel(); + init_convert(); + RESOLVE_VALUES = Symbol("resolveValues"); + REJECT_VALUES = Symbol("rejectValues"); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/transformers/lifecycle.js +function filterLifecycleEntries(log, path2, startAt = 0) { + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + if (hasPrefix(result.value.namespace, path2)) + return { + value: result.value, + done: false + }; } - this.prelude = []; - this.errors = []; - this.warnings = []; + } }; + } }; +} +function defaultGuessGraphName(ns3) { + if (ns3.length === 0) + return DEFAULT_ROOT_GRAPH_NAME; + const last = ns3[ns3.length - 1]; + const colon = last.indexOf(":"); + return colon === -1 ? last : last.slice(0, colon); +} +function defaultSerializeError(err) { + if (err instanceof Error) + return err.message; + if (typeof err === "string") + return err; + try { + return JSON.stringify(err); + } catch { + return String(err); + } +} +function isRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function extractCause(data) { + if (!isRecord(data)) + return; + if (data.event !== "started") + return; + const cause = data.cause; + if (!isRecord(cause)) + return; + if (typeof cause.type !== "string") + return; + return cause; +} +function extractTaskResultCompletion(data) { + if (!isRecord(data)) + return; + if (!("result" in data)) + return; + if (typeof data.name !== "string") + return; + if (typeof data.id !== "string") + return; + if (data.name.startsWith("__")) + return; + return { + name: data.name, + id: data.id + }; +} +function createLifecycleTransformer(options = {}) { + const rootGraphName = options.rootGraphName ?? DEFAULT_ROOT_GRAPH_NAME; + const initialStatus = options.initialStatus ?? "running"; + const emitRootOnRegister = options.emitRootOnRegister ?? true; + const getGraphName = options.getGraphName ?? defaultGuessGraphName; + const serializeError = options.serializeError ?? defaultSerializeError; + const getTerminalStatusOverride = options.getTerminalStatusOverride; + const log = StreamChannel.local(); + const namespaces = /* @__PURE__ */ new Map; + const namespaceCause = /* @__PURE__ */ new Map; + const pendingInterruptIds = /* @__PURE__ */ new Set; + const pendingCompletions = []; + let emitter; + let inSelfEmit = 0; + let finalized = false; + const resolveGraphName = (ns3) => ns3.length === 0 ? rootGraphName : getGraphName(ns3); + const emit = (ns3, status, extras) => { + const key = nsKey(ns3); + let current = namespaces.get(key); + const graphName = current?.graphName ?? resolveGraphName(ns3); + if (current != null && current.status === status && current.graphName === graphName && extras?.error == null) + return; + if (current == null) { + current = { + namespace: ns3, + graphName, + status + }; + namespaces.set(key, current); + } else + current.status = status; + const data = { + event: status, + graph_name: graphName, + ...extras?.cause != null ? { cause: extras.cause } : {}, + ...extras?.error != null ? { error: extras.error } : {} + }; + const timestamp = Date.now(); + log.push({ + namespace: ns3, + timestamp, + ...data + }); + if (ns3.length === 0 && !emitRootOnRegister) + return; + if (emitter == null) + return; + inSelfEmit += 1; + try { + emitter.push(ns3, { + type: "event", + seq: 0, + method: "lifecycle", + params: { + namespace: ns3, + timestamp, + data + } + }); + } finally { + inSelfEmit -= 1; } - streamInfo() { - return { - comment: parsePrelude(this.prelude).comment, - directives: this.directives, - errors: this.errors, - warnings: this.warnings + }; + const trackNamespace = (ns3) => { + const key = nsKey(ns3); + let rec = namespaces.get(key); + if (rec == null) { + rec = { + namespace: ns3, + graphName: resolveGraphName(ns3), + status: undefined }; + namespaces.set(key, rec); } - *compose(tokens, forceDoc = false, endOffset = -1) { - for (const token of tokens) - yield* this.next(token); - yield* this.end(forceDoc, endOffset); + return rec; + }; + const flushPendingCompletions = () => { + if (pendingCompletions.length === 0) + return; + const toFlush = pendingCompletions.splice(0, pendingCompletions.length); + for (const completion of toFlush) { + const key = nsKey(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") + continue; + emit(completion.namespace, "completed"); } - *next(token) { - if (node_process.env.LOG_STREAM) - console.dir(token, { depth: null }); - switch (token.type) { - case "directive": - this.directives.add(token.source, (offset, message, warning) => { - const pos = getErrorPos(token); - pos[0] += offset; - this.onError(pos, "BAD_DIRECTIVE", message, warning); - }); - this.prelude.push(token.source); - this.atDirectives = true; - break; - case "document": { - const doc2 = composeDoc.composeDoc(this.options, this.directives, token, this.onError); - if (this.atDirectives && !doc2.directives.docStart) - this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); - this.decorate(doc2, false); - if (this.doc) - yield this.doc; - this.doc = doc2; - this.atDirectives = false; - break; - } - case "byte-order-mark": - case "space": - break; - case "comment": - case "newline": - this.prelude.push(token.source); - break; - case "error": { - const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; - const error51 = new errors4.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); - if (this.atDirectives || !this.doc) - this.errors.push(error51); - else - this.doc.errors.push(error51); - break; - } - case "doc-end": { - if (!this.doc) { - const msg = "Unexpected doc-end without preceding document"; - this.errors.push(new errors4.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); - break; - } - this.doc.directives.docEnd = true; - const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); - this.decorate(this.doc, true); - if (end.comment) { - const dc = this.doc.comment; - this.doc.comment = dc ? `${dc} -${end.comment}` : end.comment; - } - this.doc.range[2] = end.offset; - break; - } - default: - this.errors.push(new errors4.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); - } + }; + const enqueueCompletion = (completion) => { + const key = nsKey(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") + return; + if (pendingCompletions.some((pending) => nsKey(pending.namespace) === key)) + return; + pendingCompletions.push(completion); + }; + const removePendingNodeCompletions = (parent, node) => { + for (let index2 = pendingCompletions.length - 1;index2 >= 0; index2 -= 1) { + const pending = pendingCompletions[index2]; + if (pending.source.type !== "node") + continue; + if (pending.source.node !== node) + continue; + if (nsKey(pending.source.parent) !== nsKey(parent)) + continue; + pendingCompletions.splice(index2, 1); } - *end(forceDoc = false, endOffset = -1) { - if (this.doc) { - this.decorate(this.doc, true); - yield this.doc; - this.doc = null; - } else if (forceDoc) { - const opts = Object.assign({ _directives: this.directives }, this.options); - const doc2 = new Document2.Document(undefined, opts); - if (this.atDirectives) - this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); - doc2.range = [0, endOffset, endOffset]; - this.decorate(doc2, false); - yield doc2; - } + }; + const ensureStarted = (ns3) => { + for (let length = 1;length <= ns3.length; length += 1) { + const prefix = ns3.slice(0, length); + const key = nsKey(prefix); + if (namespaces.has(key)) + continue; + trackNamespace(prefix); + const cause = namespaceCause.get(key); + emit(prefix, "started", cause != null ? { cause } : undefined); } - } - exports.Composer = Composer; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/cst-scalar.js -var require_cst_scalar = __commonJS((exports) => { - var resolveBlockScalar = require_resolve_block_scalar(); - var resolveFlowScalar = require_resolve_flow_scalar(); - var errors4 = require_errors(); - var stringifyString = require_stringifyString(); - function resolveAsScalar(token, strict = true, onError2) { - if (token) { - const _onError = (pos, code, message) => { - const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; - if (onError2) - onError2(offset, code, message); - else - throw new errors4.YAMLParseError([offset, offset + 1], code, message); + }; + const defaultTerminalStatus = () => pendingInterruptIds.size > 0 ? "interrupted" : "completed"; + const cascadeTerminalStatus = (status) => { + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) + continue; + if (rec.status !== "started") + continue; + emit(rec.namespace, status); + } + emit([], status); + log.close(); + }; + const resolveTerminalStatusOverride = async () => { + if (getTerminalStatusOverride == null) + return defaultTerminalStatus(); + try { + return await getTerminalStatusOverride() ?? defaultTerminalStatus(); + } catch { + return defaultTerminalStatus(); + } + }; + const findStartedChildForNode = (parentNamespace, node) => { + const prefix = `${node}:`; + for (const rec of namespaces.values()) { + if (rec.namespace.length !== parentNamespace.length + 1) + continue; + if (rec.status !== "started") + continue; + if (!hasPrefix(rec.namespace, parentNamespace)) + continue; + const last = rec.namespace[rec.namespace.length - 1]; + if (last === node || last.startsWith(prefix)) + return rec.namespace; + } + }; + const findStartedChildForTask = (parentNamespace, task) => { + const namespace = [...parentNamespace, `${task.name}:${task.id}`]; + return namespaces.get(nsKey(namespace))?.status === "started" ? namespace : undefined; + }; + return { + __native: true, + init() { + return { + _lifecycleLog: log, + lifecycle: filterLifecycleEntries(log, [], 0) }; - switch (token.type) { - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": - return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); - case "block-scalar": - return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + }, + onRegister(handle) { + emitter = handle; + trackNamespace([]); + if (emitRootOnRegister) + emit([], initialStatus); + }, + process(event) { + const ns3 = event.params.namespace; + if (inSelfEmit > 0) + return true; + const taskCompletion = event.method === "tasks" ? extractTaskResultCompletion(event.params.data) : undefined; + if (taskCompletion != null) + removePendingNodeCompletions(ns3, taskCompletion.name); + flushPendingCompletions(); + if (event.method === "lifecycle") { + const cause = extractCause(event.params.data); + if (cause != null) + namespaceCause.set(nsKey(ns3), cause); + ensureStarted(ns3); + return false; } - } - return null; - } - function createScalarToken(value, context2) { - const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context2; - const source = stringifyString.stringifyString({ type, value }, { - implicitKey, - indent: indent > 0 ? " ".repeat(indent) : "", - inFlow, - options: { blockQuote: true, lineWidth: -1 } - }); - const end = context2.end ?? [ - { type: "newline", offset: -1, indent, source: ` -` } - ]; - switch (source[0]) { - case "|": - case ">": { - const he = source.indexOf(` -`); - const head = source.substring(0, he); - const body = source.substring(he + 1) + ` -`; - const props = [ - { type: "block-scalar-header", offset, indent, source: head } - ]; - if (!addEndtoBlockProps(props, end)) - props.push({ type: "newline", offset: -1, indent, source: ` -` }); - return { type: "block-scalar", offset, indent, props, source: body }; + ensureStarted(ns3); + if (event.method === "input" && isRecord(event.params.data) && event.params.data.event === "requested") { + const id = event.params.data.id; + if (typeof id === "string") + pendingInterruptIds.add(id); } - case '"': - return { type: "double-quoted-scalar", offset, indent, source, end }; - case "'": - return { type: "single-quoted-scalar", offset, indent, source, end }; - default: - return { type: "scalar", offset, indent, source, end }; - } - } - function setScalarValue(token, value, context2 = {}) { - let { afterKey = false, implicitKey = false, inFlow = false, type } = context2; - let indent = "indent" in token ? token.indent : null; - if (afterKey && typeof indent === "number") - indent += 2; - if (!type) - switch (token.type) { - case "single-quoted-scalar": - type = "QUOTE_SINGLE"; - break; - case "double-quoted-scalar": - type = "QUOTE_DOUBLE"; - break; - case "block-scalar": { - const header = token.props[0]; - if (header.type !== "block-scalar-header") - throw new Error("Invalid block scalar header"); - type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; - break; - } - default: - type = "PLAIN"; + if (taskCompletion != null) { + const childNamespace = findStartedChildForTask(ns3, taskCompletion); + if (childNamespace != null) + enqueueCompletion({ + namespace: childNamespace, + source: { type: "task" } + }); } - const source = stringifyString.stringifyString({ type, value }, { - implicitKey: implicitKey || indent === null, - indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", - inFlow, - options: { blockQuote: true, lineWidth: -1 } - }); - switch (source[0]) { - case "|": - case ">": - setBlockScalarValue(token, source); - break; - case '"': - setFlowScalarValue(token, source, "double-quoted-scalar"); - break; - case "'": - setFlowScalarValue(token, source, "single-quoted-scalar"); - break; - default: - setFlowScalarValue(token, source, "scalar"); - } - } - function setBlockScalarValue(token, source) { - const he = source.indexOf(` -`); - const head = source.substring(0, he); - const body = source.substring(he + 1) + ` -`; - if (token.type === "block-scalar") { - const header = token.props[0]; - if (header.type !== "block-scalar-header") - throw new Error("Invalid block scalar header"); - header.source = head; - token.source = body; - } else { - const { offset } = token; - const indent = "indent" in token ? token.indent : -1; - const props = [ - { type: "block-scalar-header", offset, indent, source: head } - ]; - if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined)) - props.push({ type: "newline", offset: -1, indent, source: ` -` }); - for (const key of Object.keys(token)) - if (key !== "type" && key !== "offset") - delete token[key]; - Object.assign(token, { type: "block-scalar", indent, props, source: body }); - } - } - function addEndtoBlockProps(props, end) { - if (end) - for (const st of end) - switch (st.type) { - case "space": - case "comment": - props.push(st); - break; - case "newline": - props.push(st); - return true; + if (event.method === "updates") { + const node = event.params.node; + if (typeof node === "string" && !node.startsWith("__")) { + const childNamespace = findStartedChildForNode(ns3, node); + if (childNamespace != null) + enqueueCompletion({ + namespace: childNamespace, + source: { + type: "node", + parent: ns3, + node + } + }); } - return false; - } - function setFlowScalarValue(token, source, type) { - switch (token.type) { - case "scalar": - case "double-quoted-scalar": - case "single-quoted-scalar": - token.type = type; - token.source = source; - break; - case "block-scalar": { - const end = token.props.slice(1); - let oa = source.length; - if (token.props[0].type === "block-scalar-header") - oa -= token.props[0].source.length; - for (const tok of end) - tok.offset += oa; - delete token.props; - Object.assign(token, { type, source, end }); - break; } - case "block-map": - case "block-seq": { - const offset = token.offset + source.length; - const nl = { type: "newline", offset, indent: token.indent, source: ` -` }; - delete token.items; - Object.assign(token, { type, source, end: [nl] }); - break; + return true; + }, + finalize() { + if (finalized) + return; + finalized = true; + flushPendingCompletions(); + if (getTerminalStatusOverride == null) { + cascadeTerminalStatus(defaultTerminalStatus()); + return; } - default: { - const indent = "indent" in token ? token.indent : -1; - const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; - for (const key of Object.keys(token)) - if (key !== "type" && key !== "offset") - delete token[key]; - Object.assign(token, { type, indent, source, end }); + return resolveTerminalStatusOverride().then(cascadeTerminalStatus).catch((err) => { + log.fail(err); + }); + }, + fail(err) { + if (finalized) + return; + finalized = true; + const errorMessage = serializeError(err); + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) + continue; + if (rec.status !== "started") + continue; + emit(rec.namespace, "failed"); } + emit([], "failed", { error: errorMessage }); + log.fail(err); } - } - exports.createScalarToken = createScalarToken; - exports.resolveAsScalar = resolveAsScalar; - exports.setScalarValue = setScalarValue; + }; +} +var DEFAULT_ROOT_GRAPH_NAME = "root"; +var init_lifecycle = __esm(() => { + init_stream_channel(); + init_mux(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/cst-stringify.js -var require_cst_stringify = __commonJS((exports) => { - var stringify4 = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst); - function stringifyToken(token) { - switch (token.type) { - case "block-scalar": { - let res = ""; - for (const tok of token.props) - res += stringifyToken(tok); - return res + token.source; - } - case "block-map": - case "block-seq": { - let res = ""; - for (const item of token.items) - res += stringifyItem(item); - return res; - } - case "flow-collection": { - let res = token.start.source; - for (const item of token.items) - res += stringifyItem(item); - for (const st of token.end) - res += st.source; - return res; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/transformers/messages.js +function getMessageStreamKey(data) { + const record3 = data; + if (typeof record3.run_id === "string") + return `run:${record3.run_id}`; + if (data.event === "message-start" && typeof record3.id === "string") + return `message:${record3.id}`; + return "__default__"; +} +function createMessagesTransformer(path2, nodeFilter) { + const log = StreamChannel.local(); + const active = /* @__PURE__ */ new Map; + const ignored = /* @__PURE__ */ new Set; + return { + init: () => ({ messages: log.toAsyncIterable() }), + process(event) { + if (event.method !== "messages") + return true; + if (!hasPrefix(event.params.namespace, path2)) + return true; + if (event.params.namespace.length !== path2.length + 1) + return true; + if (nodeFilter !== undefined && event.params.node !== nodeFilter) + return true; + const data = event.params.data; + switch (data.event) { + case "message-start": { + const key = getMessageStreamKey(data); + if (data.role === "tool") { + ignored.add(key); + break; + } + const source = StreamChannel.local(); + const stream2 = Object.assign(new ChatModelStream(source.toAsyncIterable()), { + namespace: event.params.namespace, + node: event.params.node + }); + active.set(key, { + source, + stream: stream2 + }); + source.push(data); + log.push(stream2); + break; + } + case "content-block-start": + case "content-block-delta": + case "content-block-finish": + if (ignored.has(getMessageStreamKey(data))) + break; + active.get(getMessageStreamKey(data))?.source.push(data); + break; + case "message-finish": { + const key = getMessageStreamKey(data); + if (ignored.delete(key)) + break; + const stream2 = active.get(key); + if (stream2) { + stream2.source.push(data); + stream2.source.close(); + active.delete(key); + } + break; + } + case "error": + if (ignored.has(getMessageStreamKey(data))) + break; + active.get(getMessageStreamKey(data))?.source.push(data); + break; } - case "document": { - let res = stringifyItem(token); - if (token.end) - for (const st of token.end) - res += st.source; - return res; + return true; + }, + finalize() { + for (const [key, stream2] of active) { + stream2.source.push({ event: "message-finish" }); + stream2.source.close(); + active.delete(key); } - default: { - let res = token.source; - if ("end" in token && token.end) - for (const st of token.end) - res += st.source; - return res; + ignored.clear(); + log.close(); + }, + fail(err) { + for (const [key, stream2] of active) { + stream2.source.fail(err); + active.delete(key); } + ignored.clear(); + log.fail(err); } - } - function stringifyItem({ start, key, sep: sep2, value }) { - let res = ""; - for (const st of start) - res += st.source; - if (key) - res += stringifyToken(key); - if (sep2) - for (const st of sep2) - res += st.source; - if (value) - res += stringifyToken(value); - return res; - } - exports.stringify = stringify4; + }; +} +var init_messages2 = __esm(() => { + init_stream_channel(); + init_mux(); + init_stream2(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/cst-visit.js -var require_cst_visit = __commonJS((exports) => { - var BREAK = Symbol("break visit"); - var SKIP = Symbol("skip children"); - var REMOVE = Symbol("remove item"); - function visit(cst, visitor) { - if ("type" in cst && cst.type === "document") - cst = { start: cst.start, value: cst.value }; - _visit(Object.freeze([]), cst, visitor); - } - visit.BREAK = BREAK; - visit.SKIP = SKIP; - visit.REMOVE = REMOVE; - visit.itemAtPath = (cst, path2) => { - let item = cst; - for (const [field, index2] of path2) { - const tok = item?.[field]; - if (tok && "items" in tok) { - item = tok.items[index2]; - } else - return; - } - return item; - }; - visit.parentCollection = (cst, path2) => { - const parent = visit.itemAtPath(cst, path2.slice(0, -1)); - const field = path2[path2.length - 1][0]; - const coll = parent?.[field]; - if (coll && "items" in coll) - return coll; - throw new Error("Parent collection not found"); - }; - function _visit(path2, item, visitor) { - let ctrl = visitor(item, path2); - if (typeof ctrl === "symbol") - return ctrl; - for (const field of ["key", "value"]) { - const token = item[field]; - if (token && "items" in token) { - for (let i = 0;i < token.items.length; ++i) { - const ci = _visit(Object.freeze(path2.concat([[field, i]])), token.items[i], visitor); - if (typeof ci === "number") - i = ci - 1; - else if (ci === BREAK) - return BREAK; - else if (ci === REMOVE) { - token.items.splice(i, 1); - i -= 1; - } - } - if (typeof ctrl === "function" && field === "key") - ctrl = ctrl(item, path2); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/transformers/subgraphs.js +function filterSubgraphHandles(log, path2, startAt = 0) { + const targetDepth = path2.length + 1; + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + const { ns: ns3, stream: stream2 } = result.value; + if (ns3.length === targetDepth && hasPrefix(ns3, path2)) + return { + value: stream2, + done: false + }; } + } }; + } }; +} +function createSubgraphDiscoveryTransformer(mux, options) { + const { createStream } = options; + const seen = /* @__PURE__ */ new Set; + return { + __native: true, + init() { + return { + _discoveries: mux._discoveries, + subgraphs: filterSubgraphHandles(mux._discoveries, [], 0) + }; + }, + process(event) { + const ns3 = event.params.namespace; + if (ns3.length === 0) + return true; + const topNs = ns3.slice(0, 1); + const topKey = nsKey(topNs); + if (seen.has(topKey)) + return true; + seen.add(topKey); + const stream2 = createStream(topNs, mux._discoveries.size, mux._events.size); + mux.register(topNs, stream2); + mux._discoveries.push({ + ns: topNs, + stream: stream2 + }); + return true; } - return typeof ctrl === "function" ? ctrl(item, path2) : ctrl; - } - exports.visit = visit; + }; +} +var init_subgraphs = __esm(() => { + init_mux(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/cst.js -var require_cst = __commonJS((exports) => { - var cstScalar = require_cst_scalar(); - var cstStringify = require_cst_stringify(); - var cstVisit = require_cst_visit(); - var BOM = "\uFEFF"; - var DOCUMENT = "\x02"; - var FLOW_END = "\x18"; - var SCALAR = "\x1F"; - var isCollection = (token) => !!token && ("items" in token); - var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); - function prettyToken(token) { - switch (token) { - case BOM: - return ""; - case DOCUMENT: - return ""; - case FLOW_END: - return ""; - case SCALAR: - return ""; - default: - return JSON.stringify(token); - } - } - function tokenType(source) { - switch (source) { - case BOM: - return "byte-order-mark"; - case DOCUMENT: - return "doc-mode"; - case FLOW_END: - return "flow-error-end"; - case SCALAR: - return "scalar"; - case "---": - return "doc-start"; - case "...": - return "doc-end"; - case "": - case ` -`: - case `\r -`: - return "newline"; - case "-": - return "seq-item-ind"; - case "?": - return "explicit-key-ind"; - case ":": - return "map-value-ind"; - case "{": - return "flow-map-start"; - case "}": - return "flow-map-end"; - case "[": - return "flow-seq-start"; - case "]": - return "flow-seq-end"; - case ",": - return "comma"; - } - switch (source[0]) { - case " ": - case "\t": - return "space"; - case "#": - return "comment"; - case "%": - return "directive-line"; - case "*": - return "alias"; - case "&": - return "anchor"; - case "!": - return "tag"; - case "'": - return "single-quoted-scalar"; - case '"': - return "double-quoted-scalar"; - case "|": - case ">": - return "block-scalar-header"; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/transformers/values.js +function createValuesTransformer(path2) { + const valuesLog = StreamChannel.local(); + return { + init: () => ({ _valuesLog: valuesLog }), + process(event) { + if (event.method !== "values") + return true; + if (event.params.namespace.length !== path2.length) + return true; + if (!hasPrefix(event.params.namespace, path2)) + return true; + valuesLog.push(event.params.data); + return true; + }, + finalize() { + valuesLog.close(); + }, + fail(err) { + valuesLog.fail(err); } - return null; - } - exports.createScalarToken = cstScalar.createScalarToken; - exports.resolveAsScalar = cstScalar.resolveAsScalar; - exports.setScalarValue = cstScalar.setScalarValue; - exports.stringify = cstStringify.stringify; - exports.visit = cstVisit.visit; - exports.BOM = BOM; - exports.DOCUMENT = DOCUMENT; - exports.FLOW_END = FLOW_END; - exports.SCALAR = SCALAR; - exports.isCollection = isCollection; - exports.isScalar = isScalar; - exports.prettyToken = prettyToken; - exports.tokenType = tokenType; + }; +} +var init_values = __esm(() => { + init_stream_channel(); + init_mux(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/lexer.js -var require_lexer = __commonJS((exports) => { - var cst = require_cst(); - function isEmpty2(ch) { - switch (ch) { - case undefined: - case " ": - case ` -`: - case "\r": - case "\t": - return true; - default: - return false; - } - } - var hexDigits = new Set("0123456789ABCDEFabcdef"); - var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); - var flowIndicatorChars = new Set(",[]{}"); - var invalidAnchorChars = new Set(` ,[]{} -\r `); - var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/types.js +function isNativeTransformer(t) { + return "__native" in t && t.__native === true; +} +var init_types6 = () => {}; - class Lexer { - constructor() { - this.atEnd = false; - this.blockScalarIndent = -1; - this.blockScalarKeep = false; - this.buffer = ""; - this.flowKey = false; - this.flowLevel = 0; - this.indentNext = 0; - this.indentValue = 0; - this.lineEndPos = null; - this.next = null; - this.pos = 0; - } - *lex(source, incomplete = false) { - if (source) { - if (typeof source !== "string") - throw TypeError("source is not a string"); - this.buffer = this.buffer ? this.buffer + source : source; - this.lineEndPos = null; - } - this.atEnd = !incomplete; - let next = this.next ?? "stream"; - while (next && (incomplete || this.hasChars(1))) - next = yield* this.parseNext(next); - } - atLineEnd() { - let i = this.pos; - let ch = this.buffer[i]; - while (ch === " " || ch === "\t") - ch = this.buffer[++i]; - if (!ch || ch === "#" || ch === ` -`) - return true; - if (ch === "\r") - return this.buffer[i + 1] === ` -`; - return false; - } - charAt(n3) { - return this.buffer[this.pos + n3]; - } - continueScalar(offset) { - let ch = this.buffer[offset]; - if (this.indentNext > 0) { - let indent = 0; - while (ch === " ") - ch = this.buffer[++indent + offset]; - if (ch === "\r") { - const next = this.buffer[indent + offset + 1]; - if (next === ` -` || !next && !this.atEnd) - return offset + indent + 1; - } - return ch === ` -` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; - } - if (ch === "-" || ch === ".") { - const dt = this.buffer.substr(offset, 3); - if ((dt === "---" || dt === "...") && isEmpty2(this.buffer[offset + 3])) - return -1; - } - return offset; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/transformers/index.js +var init_transformers3 = __esm(() => { + init_lifecycle(); + init_messages2(); + init_subgraphs(); + init_values(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/run-stream.js +function createGraphRunStream(source, transformers = [], optionsOrAbortController) { + const { abortController } = optionsOrAbortController instanceof AbortController ? { abortController: optionsOrAbortController } : optionsOrAbortController ?? {}; + const mux = new StreamMux; + const lifecycleTransformer = createLifecycleTransformer(); + const lifecycleProjection = lifecycleTransformer.init(); + const lifecycleLog = lifecycleProjection._lifecycleLog; + const subgraphDiscoveryTransformer = createSubgraphDiscoveryTransformer(mux, { createStream: (path2, discoveryStart, eventStart) => { + const sub = new SubgraphRunStream(path2, mux, discoveryStart, eventStart); + sub[SET_SUBGRAPHS_ITERABLE](filterSubgraphHandles(mux._discoveries, path2, discoveryStart)); + sub[SET_LIFECYCLE_ITERABLE](filterLifecycleEntries(lifecycleLog, path2, lifecycleLog.size)); + return sub; + } }); + const subgraphsProjection = subgraphDiscoveryTransformer.init(); + mux.addTransformer(subgraphDiscoveryTransformer); + mux.addTransformer(lifecycleTransformer); + const valuesTransformer = createValuesTransformer([]); + const messagesTransformer = createMessagesTransformer([]); + mux.addTransformer(valuesTransformer); + mux.addTransformer(messagesTransformer); + const extensions = {}; + const nativeProjections = []; + for (const factory of transformers) { + const transformer = factory(); + mux.addTransformer(transformer); + const projection = transformer.init(); + if (isNativeTransformer(transformer)) + nativeProjections.push(projection); + else + Object.assign(extensions, projection); + if (typeof projection === "object" && projection !== null && !isNativeTransformer(transformer)) + mux.wireChannels(projection); + } + const root = new GraphRunStream([], mux, 0, 0, extensions, abortController); + for (const proj of nativeProjections) + Object.assign(root, proj); + const valuesProjection = valuesTransformer.init(); + root[SET_VALUES_LOG](valuesProjection._valuesLog); + const messagesProjection = messagesTransformer.init(); + root[SET_MESSAGES_ITERABLE](messagesProjection.messages); + root[SET_LIFECYCLE_ITERABLE](lifecycleProjection.lifecycle); + root[SET_SUBGRAPHS_ITERABLE](subgraphsProjection.subgraphs); + mux.register([], root); + pump(source, mux).catch((err) => {}); + return root; +} +var SET_VALUES_LOG, SET_MESSAGES_ITERABLE, SET_LIFECYCLE_ITERABLE, SET_SUBGRAPHS_ITERABLE, EMPTY_ASYNC_ITERABLE, GraphRunStream, SubgraphRunStream; +var init_run_stream = __esm(() => { + init_mux(); + init_lifecycle(); + init_messages2(); + init_subgraphs(); + init_values(); + init_transformers3(); + init_types6(); + SET_VALUES_LOG = Symbol("setValuesLog"); + SET_MESSAGES_ITERABLE = Symbol("setMessagesIterable"); + SET_LIFECYCLE_ITERABLE = Symbol("setLifecycleIterable"); + SET_SUBGRAPHS_ITERABLE = Symbol("setSubgraphsIterable"); + EMPTY_ASYNC_ITERABLE = { [Symbol.asyncIterator]() { + return { next: () => Promise.resolve({ + value: undefined, + done: true + }) }; + } }; + GraphRunStream = class { + path; + extensions; + _mux; + #eventStart; + #discoveryStart; + #abortController; + #resolveValuesFn; + #rejectValuesFn; + #valuesDone; + #valuesLog; + #messagesIterable; + #lifecycleIterable; + #subgraphsIterable; + constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + this.path = path2; + this._mux = mux; + this.#discoveryStart = discoveryStart; + this.#eventStart = eventStart; + this.extensions = extensions ?? {}; + this.#abortController = abortController ?? new AbortController; + this.#valuesDone = new Promise((resolve2, reject) => { + this.#resolveValuesFn = resolve2; + this.#rejectValuesFn = reject; + }); + this.#valuesDone.catch(() => {}); } - getLine() { - let end = this.lineEndPos; - if (typeof end !== "number" || end !== -1 && end < this.pos) { - end = this.buffer.indexOf(` -`, this.pos); - this.lineEndPos = end; - } - if (end === -1) - return this.atEnd ? this.buffer.substring(this.pos) : null; - if (this.buffer[end - 1] === "\r") - end -= 1; - return this.buffer.substring(this.pos, end); + [Symbol.asyncIterator]() { + return this._mux.subscribeEvents(this.path, this.#eventStart); } - hasChars(n3) { - return this.pos + n3 <= this.buffer.length; + get subgraphs() { + if (this.#subgraphsIterable) + return this.#subgraphsIterable; + return filterSubgraphHandles(this._mux._discoveries, this.path, this.#discoveryStart); } - setNext(state) { - this.buffer = this.buffer.substring(this.pos); - this.pos = 0; - this.lineEndPos = null; - this.next = state; - return null; + get values() { + const log = this.#valuesLog; + const done = this.#valuesDone; + const mux = this._mux; + const eventStart = this.#eventStart; + const path2 = this.path; + const iterable = log ? log.toAsyncIterable() : { [Symbol.asyncIterator]: () => { + const base = mux.subscribeEvents(path2, eventStart); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + if (result.value.method === "values" && result.value.params.namespace.length === path2.length) + return { + value: result.value.params.data, + done: false + }; + } + } }; + } }; + return { + [Symbol.asyncIterator]: () => iterable[Symbol.asyncIterator](), + then: done.then.bind(done) + }; } - peek(n3) { - return this.buffer.substr(this.pos, n3); + get messages() { + if (this.#messagesIterable) + return this.#messagesIterable; + const transformer = createMessagesTransformer(this.path); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + this.#messagesIterable = projection.messages; + return this.#messagesIterable; } - *parseNext(next) { - switch (next) { - case "stream": - return yield* this.parseStream(); - case "line-start": - return yield* this.parseLineStart(); - case "block-start": - return yield* this.parseBlockStart(); - case "doc": - return yield* this.parseDocument(); - case "flow": - return yield* this.parseFlowCollection(); - case "quoted-scalar": - return yield* this.parseQuotedScalar(); - case "block-scalar": - return yield* this.parseBlockScalar(); - case "plain-scalar": - return yield* this.parsePlainScalar(); - } + get lifecycle() { + return this.#lifecycleIterable ?? EMPTY_ASYNC_ITERABLE; } - *parseStream() { - let line = this.getLine(); - if (line === null) - return this.setNext("stream"); - if (line[0] === cst.BOM) { - yield* this.pushCount(1); - line = line.substring(1); - } - if (line[0] === "%") { - let dirEnd = line.length; - let cs = line.indexOf("#"); - while (cs !== -1) { - const ch = line[cs - 1]; - if (ch === " " || ch === "\t") { - dirEnd = cs - 1; - break; - } else { - cs = line.indexOf("#", cs + 1); - } - } - while (true) { - const ch = line[dirEnd - 1]; - if (ch === " " || ch === "\t") - dirEnd -= 1; - else - break; - } - const n3 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); - yield* this.pushCount(line.length - n3); - this.pushNewline(); - return "stream"; - } - if (this.atLineEnd()) { - const sp = yield* this.pushSpaces(true); - yield* this.pushCount(line.length - sp); - yield* this.pushNewline(); - return "stream"; - } - yield cst.DOCUMENT; - return yield* this.parseLineStart(); + messagesFrom(node) { + const transformer = createMessagesTransformer(this.path, node); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + return projection.messages; } - *parseLineStart() { - const ch = this.charAt(0); - if (!ch && !this.atEnd) - return this.setNext("line-start"); - if (ch === "-" || ch === ".") { - if (!this.atEnd && !this.hasChars(4)) - return this.setNext("line-start"); - const s = this.peek(3); - if ((s === "---" || s === "...") && isEmpty2(this.charAt(3))) { - yield* this.pushCount(3); - this.indentValue = 0; - this.indentNext = 0; - return s === "---" ? "doc" : "stream"; - } - } - this.indentValue = yield* this.pushSpaces(false); - if (this.indentNext > this.indentValue && !isEmpty2(this.charAt(1))) - this.indentNext = this.indentValue; - return yield* this.parseBlockStart(); + get output() { + return this.#valuesDone; } - *parseBlockStart() { - const [ch0, ch1] = this.peek(2); - if (!ch1 && !this.atEnd) - return this.setNext("block-start"); - if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty2(ch1)) { - const n3 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); - this.indentNext = this.indentValue + 1; - this.indentValue += n3; - return yield* this.parseBlockStart(); - } - return "doc"; + get interrupted() { + return this._mux.interrupted; } - *parseDocument() { - yield* this.pushSpaces(true); - const line = this.getLine(); - if (line === null) - return this.setNext("doc"); - let n3 = yield* this.pushIndicators(); - switch (line[n3]) { - case "#": - yield* this.pushCount(line.length - n3); - case undefined: - yield* this.pushNewline(); - return yield* this.parseLineStart(); - case "{": - case "[": - yield* this.pushCount(1); - this.flowKey = false; - this.flowLevel = 1; - return "flow"; - case "}": - case "]": - yield* this.pushCount(1); - return "doc"; - case "*": - yield* this.pushUntil(isNotAnchorChar); - return "doc"; - case '"': - case "'": - return yield* this.parseQuotedScalar(); - case "|": - case ">": - n3 += yield* this.parseBlockScalarHeader(); - n3 += yield* this.pushSpaces(true); - yield* this.pushCount(line.length - n3); - yield* this.pushNewline(); - return yield* this.parseBlockScalar(); - default: - return yield* this.parsePlainScalar(); - } + get interrupts() { + return this._mux.interrupts; } - *parseFlowCollection() { - let nl, sp; - let indent = -1; - do { - nl = yield* this.pushNewline(); - if (nl > 0) { - sp = yield* this.pushSpaces(false); - this.indentValue = indent = sp; - } else { - sp = 0; - } - sp += yield* this.pushSpaces(true); - } while (nl + sp > 0); - const line = this.getLine(); - if (line === null) - return this.setNext("flow"); - if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty2(line[3])) { - const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); - if (!atFlowEndMarker) { - this.flowLevel = 0; - yield cst.FLOW_END; - return yield* this.parseLineStart(); - } - } - let n3 = 0; - while (line[n3] === ",") { - n3 += yield* this.pushCount(1); - n3 += yield* this.pushSpaces(true); - this.flowKey = false; - } - n3 += yield* this.pushIndicators(); - switch (line[n3]) { - case undefined: - return "flow"; - case "#": - yield* this.pushCount(line.length - n3); - return "flow"; - case "{": - case "[": - yield* this.pushCount(1); - this.flowKey = false; - this.flowLevel += 1; - return "flow"; - case "}": - case "]": - yield* this.pushCount(1); - this.flowKey = true; - this.flowLevel -= 1; - return this.flowLevel ? "flow" : "doc"; - case "*": - yield* this.pushUntil(isNotAnchorChar); - return "flow"; - case '"': - case "'": - this.flowKey = true; - return yield* this.parseQuotedScalar(); - case ":": { - const next = this.charAt(1); - if (this.flowKey || isEmpty2(next) || next === ",") { - this.flowKey = false; - yield* this.pushCount(1); - yield* this.pushSpaces(true); - return "flow"; - } - } - default: - this.flowKey = false; - return yield* this.parsePlainScalar(); - } + abort(reason) { + this.#abortController.abort(reason); } - *parseQuotedScalar() { - const quote = this.charAt(0); - let end = this.buffer.indexOf(quote, this.pos + 1); - if (quote === "'") { - while (end !== -1 && this.buffer[end + 1] === "'") - end = this.buffer.indexOf("'", end + 2); - } else { - while (end !== -1) { - let n3 = 0; - while (this.buffer[end - 1 - n3] === "\\") - n3 += 1; - if (n3 % 2 === 0) - break; - end = this.buffer.indexOf('"', end + 1); - } - } - const qb = this.buffer.substring(0, end); - let nl = qb.indexOf(` -`, this.pos); - if (nl !== -1) { - while (nl !== -1) { - const cs = this.continueScalar(nl + 1); - if (cs === -1) - break; - nl = qb.indexOf(` -`, cs); - } - if (nl !== -1) { - end = nl - (qb[nl - 1] === "\r" ? 2 : 1); - } - } - if (end === -1) { - if (!this.atEnd) - return this.setNext("quoted-scalar"); - end = this.buffer.length; - } - yield* this.pushToIndex(end + 1, false); - return this.flowLevel ? "flow" : "doc"; + get signal() { + return this.#abortController.signal; } - *parseBlockScalarHeader() { - this.blockScalarIndent = -1; - this.blockScalarKeep = false; - let i = this.pos; - while (true) { - const ch = this.buffer[++i]; - if (ch === "+") - this.blockScalarKeep = true; - else if (ch > "0" && ch <= "9") - this.blockScalarIndent = Number(ch) - 1; - else if (ch !== "-") - break; - } - return yield* this.pushUntil((ch) => isEmpty2(ch) || ch === "#"); + [RESOLVE_VALUES](values) { + this.#resolveValuesFn?.(values); + this.#resolveValuesFn = undefined; } - *parseBlockScalar() { - let nl = this.pos - 1; - let indent = 0; - let ch; - loop: - for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) { - switch (ch) { - case " ": - indent += 1; - break; - case ` -`: - nl = i2; - indent = 0; - break; - case "\r": { - const next = this.buffer[i2 + 1]; - if (!next && !this.atEnd) - return this.setNext("block-scalar"); - if (next === ` -`) - break; - } - default: - break loop; - } - } - if (!ch && !this.atEnd) - return this.setNext("block-scalar"); - if (indent >= this.indentNext) { - if (this.blockScalarIndent === -1) - this.indentNext = indent; - else { - this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); - } - do { - const cs = this.continueScalar(nl + 1); - if (cs === -1) - break; - nl = this.buffer.indexOf(` -`, cs); - } while (nl !== -1); - if (nl === -1) { - if (!this.atEnd) - return this.setNext("block-scalar"); - nl = this.buffer.length; - } - } - let i = nl + 1; - ch = this.buffer[i]; - while (ch === " ") - ch = this.buffer[++i]; - if (ch === "\t") { - while (ch === "\t" || ch === " " || ch === "\r" || ch === ` -`) - ch = this.buffer[++i]; - nl = i - 1; - } else if (!this.blockScalarKeep) { - do { - let i2 = nl - 1; - let ch2 = this.buffer[i2]; - if (ch2 === "\r") - ch2 = this.buffer[--i2]; - const lastChar = i2; - while (ch2 === " ") - ch2 = this.buffer[--i2]; - if (ch2 === ` -` && i2 >= this.pos && i2 + 1 + indent > lastChar) - nl = i2; - else - break; - } while (true); - } - yield cst.SCALAR; - yield* this.pushToIndex(nl + 1, true); - return yield* this.parseLineStart(); + [REJECT_VALUES](err) { + this.#rejectValuesFn?.(err); + this.#rejectValuesFn = undefined; } - *parsePlainScalar() { - const inFlow = this.flowLevel > 0; - let end = this.pos - 1; - let i = this.pos - 1; - let ch; - while (ch = this.buffer[++i]) { - if (ch === ":") { - const next = this.buffer[i + 1]; - if (isEmpty2(next) || inFlow && flowIndicatorChars.has(next)) - break; - end = i; - } else if (isEmpty2(ch)) { - let next = this.buffer[i + 1]; - if (ch === "\r") { - if (next === ` -`) { - i += 1; - ch = ` -`; - next = this.buffer[i + 1]; - } else - end = i; - } - if (next === "#" || inFlow && flowIndicatorChars.has(next)) - break; - if (ch === ` -`) { - const cs = this.continueScalar(i + 1); - if (cs === -1) - break; - i = Math.max(i, cs - 2); - } - } else { - if (inFlow && flowIndicatorChars.has(ch)) - break; - end = i; - } - } - if (!ch && !this.atEnd) - return this.setNext("plain-scalar"); - yield cst.SCALAR; - yield* this.pushToIndex(end + 1, true); - return inFlow ? "flow" : "doc"; + [SET_VALUES_LOG](log) { + this.#valuesLog = log; } - *pushCount(n3) { - if (n3 > 0) { - yield this.buffer.substr(this.pos, n3); - this.pos += n3; - return n3; - } - return 0; + [SET_MESSAGES_ITERABLE](iterable) { + this.#messagesIterable = iterable; } - *pushToIndex(i, allowEmpty) { - const s = this.buffer.slice(this.pos, i); - if (s) { - yield s; - this.pos += s.length; - return s.length; - } else if (allowEmpty) - yield ""; - return 0; + [SET_LIFECYCLE_ITERABLE](iterable) { + this.#lifecycleIterable = iterable; } - *pushIndicators() { - switch (this.charAt(0)) { - case "!": - return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); - case "&": - return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); - case "-": - case "?": - case ":": { - const inFlow = this.flowLevel > 0; - const ch1 = this.charAt(1); - if (isEmpty2(ch1) || inFlow && flowIndicatorChars.has(ch1)) { - if (!inFlow) - this.indentNext = this.indentValue + 1; - else if (this.flowKey) - this.flowKey = false; - return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); - } - } - } - return 0; + [SET_SUBGRAPHS_ITERABLE](iterable) { + this.#subgraphsIterable = iterable; } - *pushTag() { - if (this.charAt(1) === "<") { - let i = this.pos + 2; - let ch = this.buffer[i]; - while (!isEmpty2(ch) && ch !== ">") - ch = this.buffer[++i]; - return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + }; + SubgraphRunStream = class extends GraphRunStream { + name; + index; + constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + super(path2, mux, discoveryStart, eventStart, extensions, abortController); + const lastSegment = path2[path2.length - 1] ?? ""; + const colonIdx = lastSegment.lastIndexOf(":"); + if (colonIdx >= 0) { + this.name = lastSegment.slice(0, colonIdx); + const suffix = lastSegment.slice(colonIdx + 1); + this.index = /^\d+$/.test(suffix) ? Number(suffix) : 0; } else { - let i = this.pos + 1; - let ch = this.buffer[i]; - while (ch) { - if (tagChars.has(ch)) - ch = this.buffer[++i]; - else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { - ch = this.buffer[i += 3]; - } else - break; - } - return yield* this.pushToIndex(i, false); - } - } - *pushNewline() { - const ch = this.buffer[this.pos]; - if (ch === ` -`) - return yield* this.pushCount(1); - else if (ch === "\r" && this.charAt(1) === ` -`) - return yield* this.pushCount(2); - else - return 0; - } - *pushSpaces(allowTabs) { - let i = this.pos - 1; - let ch; - do { - ch = this.buffer[++i]; - } while (ch === " " || allowTabs && ch === "\t"); - const n3 = i - this.pos; - if (n3 > 0) { - yield this.buffer.substr(this.pos, n3); - this.pos = i; + this.name = lastSegment; + this.index = 0; } - return n3; - } - *pushUntil(test) { - let i = this.pos; - let ch = this.buffer[i]; - while (!test(ch)) - ch = this.buffer[++i]; - return yield* this.pushToIndex(i, false); } - } - exports.Lexer = Lexer; + }; }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/line-counter.js -var require_line_counter = __commonJS((exports) => { - class LineCounter { - constructor() { - this.lineStarts = []; - this.addNewLine = (offset) => this.lineStarts.push(offset); - this.linePos = (offset) => { - let low = 0; - let high = this.lineStarts.length; - while (low < high) { - const mid = low + high >> 1; - if (this.lineStarts[mid] < offset) - low = mid + 1; - else - high = mid; - } - if (this.lineStarts[low] === offset) - return { line: low + 1, col: 1 }; - if (low === 0) - return { line: 0, col: offset }; - const start = this.lineStarts[low - 1]; - return { line: low, col: offset - start + 1 }; - }; - } - } - exports.LineCounter = LineCounter; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/stream/index.js +var init_stream4 = __esm(() => { + init_stream_channel(); + init_convert(); + init_mux(); + init_lifecycle(); + init_messages2(); + init_subgraphs(); + init_values(); + init_transformers3(); + init_types6(); + init_run_stream(); + init_stream2(); }); -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/parse/parser.js -var require_parser = __commonJS((exports) => { - var node_process = __require("process"); - var cst = require_cst(); - var lexer = require_lexer(); - function includesToken(list, type) { - for (let i = 0;i < list.length; ++i) - if (list[i].type === type) - return true; - return false; - } - function findNonEmptyIndex(list) { - for (let i = 0;i < list.length; ++i) { - switch (list[i].type) { - case "space": - case "comment": - case "newline": - break; - default: - return i; - } - } - return -1; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/hash.js +function assert4(a) { + if (!a) + throw new Error("Assert failed"); +} +function bswap642(a) { + const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); + scratchbuf.setBigUint64(0, a, true); + return scratchbuf.getBigUint64(0, false); +} +function bswap322(input) { + let a = input; + a = (a & n2(65535)) << n2(16) | (a & n2(4294901760)) >> n2(16); + a = (a & n2(16711935)) << n2(8) | (a & n2(4278255360)) >> n2(8); + return a; +} +function XXH_mult32to642(a, b) { + return (a & mask322) * (b & mask322) & mask642; +} +function rotl322(a, b) { + return (a << b | a >> n2(32) - b) & mask322; +} +function XXH3_accumulate_5122(acc, dataView, keyView) { + for (let i = 0;i < ACC_NB2; i += 1) { + const data_val = dataView.getBigUint64(i * 8, true); + const data_key = data_val ^ keyView.getBigUint64(i * 8, true); + acc[i ^ 1] += data_val; + acc[i] += XXH_mult32to642(data_key, data_key >> n2(32)); } - function isFlowToken(token) { - switch (token?.type) { - case "alias": - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": - case "flow-collection": - return true; - default: - return false; - } + return acc; +} +function XXH3_accumulate2(acc, dataView, keyView, nbStripes) { + for (let n3 = 0;n3 < nbStripes; n3 += 1) + XXH3_accumulate_5122(acc, view(dataView, n3 * STRIPE_LEN2), view(keyView, n3 * 8)); + return acc; +} +function XXH3_scrambleAcc2(acc, key) { + for (let i = 0;i < ACC_NB2; i += 1) { + const key64 = key.getBigUint64(i * 8, true); + let acc64 = acc[i]; + acc64 = xorshift642(acc64, n2(47)); + acc64 ^= key64; + acc64 *= PRIME32_12; + acc[i] = acc64 & mask642; } - function getPrevProps(parent) { - switch (parent.type) { - case "document": - return parent.start; - case "block-map": { - const it = parent.items[parent.items.length - 1]; - return it.sep ?? it.start; - } - case "block-seq": - return parent.items[parent.items.length - 1].start; - default: - return []; - } + return acc; +} +function XXH3_mix2Accs2(acc, key) { + return XXH3_mul128_fold642(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U642, true)); +} +function XXH3_mergeAccs2(acc, key, start) { + let result64 = start; + result64 += XXH3_mix2Accs2(acc.slice(0), view(key, 0 * _U322)); + result64 += XXH3_mix2Accs2(acc.slice(2), view(key, 4 * _U322)); + result64 += XXH3_mix2Accs2(acc.slice(4), view(key, 8 * _U322)); + result64 += XXH3_mix2Accs2(acc.slice(6), view(key, 12 * _U322)); + return XXH3_avalanche2(result64 & mask642); +} +function XXH3_hashLong2(input, data, secret, f_acc, f_scramble) { + let acc = input; + const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN2) / 8); + const block_len = STRIPE_LEN2 * nbStripesPerBlock; + const nb_blocks = Math.floor((data.byteLength - 1) / block_len); + for (let n3 = 0;n3 < nb_blocks; n3 += 1) { + acc = XXH3_accumulate2(acc, view(data, n3 * block_len), secret, nbStripesPerBlock); + acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN2)); } - function getFirstKeyStartProps(prev) { - if (prev.length === 0) - return []; - let i = prev.length; - loop: - while (--i >= 0) { - switch (prev[i].type) { - case "doc-start": - case "explicit-key-ind": - case "map-value-ind": - case "seq-item-ind": - case "newline": - break loop; - } - } - while (prev[++i]?.type === "space") {} - return prev.splice(i, prev.length); + { + const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN2); + acc = XXH3_accumulate2(acc, view(data, nb_blocks * block_len), secret, nbStripes); + acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN2), view(secret, secret.byteLength - STRIPE_LEN2 - 7)); } - function fixFlowSeqItems(fc) { - if (fc.start.type === "flow-seq-start") { - for (const it of fc.items) { - if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { - if (it.key) - it.value = it.key; - delete it.key; - if (isFlowToken(it.value)) { - if (it.value.end) - Array.prototype.push.apply(it.value.end, it.sep); - else - it.value.end = it.sep; - } else - Array.prototype.push.apply(it.start, it.sep); - delete it.sep; - } + return acc; +} +function XXH3_hashLong_128b2(data, secret) { + let acc = new BigUint64Array([ + PRIME32_32, + PRIME64_12, + PRIME64_22, + PRIME64_32, + PRIME64_42, + PRIME32_22, + PRIME64_52, + PRIME32_12 + ]); + assert4(data.byteLength > 128); + acc = XXH3_hashLong2(acc, data, secret, XXH3_accumulate_5122, XXH3_scrambleAcc2); + assert4(acc.length * 8 === 64); + { + const low64 = XXH3_mergeAccs2(acc, view(secret, 11), n2(data.byteLength) * PRIME64_12 & mask642); + return XXH3_mergeAccs2(acc, view(secret, secret.byteLength - STRIPE_LEN2 - 11), ~(n2(data.byteLength) * PRIME64_22) & mask642) << n2(64) | low64; + } +} +function XXH3_mul128_fold642(a, b) { + const lll = a * b & mask1282; + return lll & mask642 ^ lll >> n2(64); +} +function XXH3_mix16B2(dataView, keyView, seed) { + return XXH3_mul128_fold642((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask642, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask642); +} +function XXH3_mix32B2(acc, data1, data2, key, seed) { + let accl = acc & mask642; + let acch = acc >> n2(64) & mask642; + accl += XXH3_mix16B2(data1, key, seed); + accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); + accl &= mask642; + acch += XXH3_mix16B2(data2, view(key, 16), seed); + acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); + acch &= mask642; + return acch << n2(64) | accl; +} +function XXH3_avalanche2(input) { + let h64 = input; + h64 ^= h64 >> n2(37); + h64 *= PRIME_MX12; + h64 &= mask642; + h64 ^= h64 >> n2(32); + return h64; +} +function XXH3_avalanche642(input) { + let h64 = input; + h64 ^= h64 >> n2(33); + h64 *= PRIME64_22; + h64 &= mask642; + h64 ^= h64 >> n2(29); + h64 *= PRIME64_32; + h64 &= mask642; + h64 ^= h64 >> n2(32); + return h64; +} +function XXH3_len_1to3_128b2(data, key32, seed) { + const len = data.byteLength; + assert4(len > 0 && len <= 3); + const combined = n2(data.getUint8(len - 1)) | n2(len << 8) | n2(data.getUint8(0) << 16) | n2(data.getUint8(len >> 1) << 24); + const low = (combined ^ (n2(key32.getUint32(0, true)) ^ n2(key32.getUint32(4, true))) + seed) & mask642; + const bhigh = (n2(key32.getUint32(8, true)) ^ n2(key32.getUint32(12, true))) - seed; + return (XXH3_avalanche642((rotl322(bswap322(combined), n2(13)) ^ bhigh) & mask642) & mask642) << n2(64) | XXH3_avalanche642(low); +} +function xorshift642(b, shift) { + return b ^ b >> shift; +} +function XXH3_len_4to8_128b2(data, key32, seed) { + const len = data.byteLength; + assert4(len >= 4 && len <= 8); + { + const l1 = data.getUint32(0, true); + const l2 = data.getUint32(len - 4, true); + let m128 = ((n2(l1) | n2(l2) << n2(32)) ^ (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask642) * (PRIME64_12 + (n2(len) << n2(2))) & mask1282; + m128 += (m128 & mask642) << n2(65); + m128 &= mask1282; + m128 ^= m128 >> n2(67); + return xorshift642(xorshift642(m128 & mask642, n2(35)) * PRIME_MX22 & mask642, n2(28)) | XXH3_avalanche2(m128 >> n2(64)) << n2(64); + } +} +function XXH3_len_9to16_128b2(data, key64, seed) { + const len = data.byteLength; + assert4(len >= 9 && len <= 16); + { + const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask642; + const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask642; + const ll1 = data.getBigUint64(0, true); + let ll2 = data.getBigUint64(len - 8, true); + let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_12; + const m128_l = (m128 & mask642) + (n2(len - 1) << n2(54)); + m128 = m128 & (mask1282 ^ mask642) | m128_l; + ll2 ^= bitfliph; + m128 += ll2 + (ll2 & mask322) * (PRIME32_22 - n2(1)) << n2(64); + m128 &= mask1282; + m128 ^= bswap642(m128 >> n2(64)); + let h128 = (m128 & mask642) * PRIME64_22; + h128 += (m128 >> n2(64)) * PRIME64_22 << n2(64); + h128 &= mask1282; + return XXH3_avalanche2(h128 & mask642) | XXH3_avalanche2(h128 >> n2(64)) << n2(64); + } +} +function XXH3_len_0to16_128b2(data, seed) { + const len = data.byteLength; + assert4(len <= 16); + if (len > 8) + return XXH3_len_9to16_128b2(data, kkey2, seed); + if (len >= 4) + return XXH3_len_4to8_128b2(data, kkey2, seed); + if (len > 0) + return XXH3_len_1to3_128b2(data, kkey2, seed); + return XXH3_avalanche642(seed ^ kkey2.getBigUint64(64, true) ^ kkey2.getBigUint64(72, true)) | XXH3_avalanche642(seed ^ kkey2.getBigUint64(80, true) ^ kkey2.getBigUint64(88, true)) << n2(64); +} +function inv642(x) { + return ~x + n2(1) & mask642; +} +function XXH3_len_17to128_128b2(data, secret, seed) { + let acc = n2(data.byteLength) * PRIME64_12 & mask642; + let i = n2(data.byteLength - 1) / n2(32); + while (i >= 0) { + const ni = Number(i); + acc = XXH3_mix32B2(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); + i -= n2(1); + } + let h128l = acc + (acc >> n2(64)) & mask642; + h128l = XXH3_avalanche2(h128l); + let h128h = (acc & mask642) * PRIME64_12 + (acc >> n2(64)) * PRIME64_42 + (n2(data.byteLength) - seed & mask642) * PRIME64_22; + h128h &= mask642; + h128h = inv642(XXH3_avalanche2(h128h)); + return h128l | h128h << n2(64); +} +function XXH3_len_129to240_128b2(data, secret, seed) { + let acc = n2(data.byteLength) * PRIME64_12 & mask642; + for (let i = 32;i < 160; i += 32) + acc = XXH3_mix32B2(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); + acc = XXH3_avalanche2(acc & mask642) | XXH3_avalanche2(acc >> n2(64)) << n2(64); + for (let i = 160;i <= data.byteLength; i += 32) + acc = XXH3_mix32B2(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); + acc = XXH3_mix32B2(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv642(seed)); + let h128l = acc + (acc >> n2(64)) & mask642; + h128l = XXH3_avalanche2(h128l); + let h128h = (acc & mask642) * PRIME64_12 + (acc >> n2(64)) * PRIME64_42 + (n2(data.byteLength) - seed & mask642) * PRIME64_22; + h128h &= mask642; + h128h = inv642(XXH3_avalanche2(h128h)); + return h128l | h128h << n2(64); +} +function XXH3(input, seed = n2(0)) { + const encoder2 = new TextEncoder; + const data = view(typeof input === "string" ? encoder2.encode(input) : input); + const len = data.byteLength; + const hexDigest = (data2) => data2.toString(16).padStart(32, "0"); + if (len <= 16) + return hexDigest(XXH3_len_0to16_128b2(data, seed)); + if (len <= 128) + return hexDigest(XXH3_len_17to128_128b2(data, kkey2, seed)); + if (len <= 240) + return hexDigest(XXH3_len_129to240_128b2(data, kkey2, seed)); + return hexDigest(XXH3_hashLong_128b2(data, kkey2)); +} +function isXXH3(value) { + return /^[0-9a-f]{32}$/.test(value); +} +var n2 = (n3) => BigInt(n3), view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset), PRIME32_12, PRIME32_22, PRIME32_32, PRIME64_12, PRIME64_22, PRIME64_32, PRIME64_42, PRIME64_52, PRIME_MX12, PRIME_MX22, hexToUint8Array2 = (hex3) => { + const strLen = hex3.length; + if (strLen % 2 !== 0) + throw new Error("String should have an even number of characters"); + const maxLength = strLen / 2; + const bytes = new Uint8Array(maxLength); + let read = 0; + let write = 0; + while (write < maxLength) { + const slice = hex3.slice(read, read += 2); + bytes[write] = Number.parseInt(slice, 16); + write += 1; + } + return view(bytes); +}, kkey2, mask1282, mask642, mask322, STRIPE_LEN2 = 64, ACC_NB2, _U642 = 8, _U322 = 4; +var init_hash3 = __esm(() => { + PRIME32_12 = n2("0x9E3779B1"); + PRIME32_22 = n2("0x85EBCA77"); + PRIME32_32 = n2("0xC2B2AE3D"); + PRIME64_12 = n2("0x9E3779B185EBCA87"); + PRIME64_22 = n2("0xC2B2AE3D27D4EB4F"); + PRIME64_32 = n2("0x165667B19E3779F9"); + PRIME64_42 = n2("0x85EBCA77C2B2AE63"); + PRIME64_52 = n2("0x27D4EB2F165667C5"); + PRIME_MX12 = n2("0x165667919E3779F9"); + PRIME_MX22 = n2("0x9FB21C651E98DF25"); + kkey2 = hexToUint8Array2("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); + mask1282 = (n2(1) << n2(128)) - n2(1); + mask642 = (n2(1) << n2(64)) - n2(1); + mask322 = (n2(1) << n2(32)) - n2(1); + ACC_NB2 = STRIPE_LEN2 / 8; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/interrupt.js +function interrupt(value) { + const config3 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (!config3) + throw new Error("Called interrupt() outside the context of a graph."); + const conf = config3.configurable; + if (!conf) + throw new Error("No configurable found in config"); + if (!conf["__pregel_checkpointer"]) + throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const scratchpad = conf[CONFIG_KEY_SCRATCHPAD]; + scratchpad.interruptCounter += 1; + const idx = scratchpad.interruptCounter; + if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { + conf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]); + return scratchpad.resume[idx]; + } + if (scratchpad.nullResume !== undefined) { + if (scratchpad.resume.length !== idx) + throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); + const v = scratchpad.consumeNullResume(); + scratchpad.resume.push(v); + conf[CONFIG_KEY_SEND]?.([[RESUME, scratchpad.resume]]); + return v; + } + const ns3 = conf[CONFIG_KEY_CHECKPOINT_NS]?.split("|"); + throw new GraphInterrupt([{ + id: ns3 ? XXH3(ns3.join("|")) : undefined, + value + }]); +} +var init_interrupt = __esm(() => { + init_constants3(); + init_errors7(); + init_hash3(); + init_singletons(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/utils.js +function* prefixGenerator(generator, prefix) { + if (prefix === undefined) + yield* generator; + else + for (const value of generator) + yield [prefix, value]; +} +async function gatherIterator(i) { + const out = []; + for await (const item of await i) + out.push(item); + return out; +} +function gatherIteratorSync(i) { + const out = []; + for (const item of i) + out.push(item); + return out; +} +function patchConfigurable(config3, patch) { + if (!config3) + return { configurable: patch }; + else if (!("configurable" in config3)) + return { + ...config3, + configurable: patch + }; + else + return { + ...config3, + configurable: { + ...config3.configurable, + ...patch } + }; +} +function isAsyncGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; +} +function isGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; +} +var RunnableCallable; +var init_utils8 = __esm(() => { + init_config2(); + init_singletons(); + init_runnables(); + RunnableCallable = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : undefined; + this.trace = fields.trace ?? this.trace; + this.recurse = fields.recurse ?? this.recurse; } - } + async _tracedInvoke(input, config3, runManager) { + return new Promise((resolve2, reject) => { + const childConfig = patchConfig(config3, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { + try { + resolve2(await this.func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + let returnValue; + const config3 = ensureLangGraphConfig(options); + const mergedConfig = mergeConfigs(this.config, config3); + if (this.trace) + returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); + else + returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) + return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + return returnValue; + } + }; +}); - class Parser { - constructor(onNewLine) { - this.atNewLine = true; - this.atScalar = false; - this.indent = 0; - this.offset = 0; - this.onKeyLine = false; - this.stack = []; - this.source = ""; - this.type = ""; - this.lexer = new lexer.Lexer; - this.onNewLine = onNewLine; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/write.js +function _isSkipWrite(x) { + return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== undefined; +} +function _isPassthrough(x) { + return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== undefined; +} +function _isChannelWriteEntry(x) { + return x !== undefined && typeof x.channel === "string"; +} +function _isChannelWriteTupleEntry(x) { + return x !== undefined && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); +} +var PASSTHROUGH, IS_WRITER, ChannelWrite; +var init_write = __esm(() => { + init_constants3(); + init_errors7(); + init_utils8(); + init_runnables(); + PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; + IS_WRITER = Symbol("IS_WRITER"); + ChannelWrite = class ChannelWrite2 extends RunnableCallable { + writes; + constructor(writes, tags) { + const name = `ChannelWrite<${writes.map((packet) => { + if (_isSend(packet)) + return packet.node; + else if ("channel" in packet) + return packet.channel; + return "..."; + }).join(",")}>`; + super({ + writes, + name, + tags, + trace: false, + func: async (input, config3) => { + return this._write(input, config3 ?? {}); + } + }); + this.writes = writes; } - *parse(source, incomplete = false) { - if (this.onNewLine && this.offset === 0) - this.onNewLine(0); - for (const lexeme of this.lexer.lex(source, incomplete)) - yield* this.next(lexeme); - if (!incomplete) - yield* this.end(); + async _write(input, config3) { + const writes = this.writes.map((write) => { + if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) + return { + mapper: write.mapper, + value: input + }; + else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) + return { + channel: write.channel, + value: input, + skipNone: write.skipNone, + mapper: write.mapper + }; + else + return write; + }); + await ChannelWrite2.doWrite(config3, writes); + return input; } - *next(source) { - this.source = source; - if (node_process.env.LOG_TOKENS) - console.log("|", cst.prettyToken(source)); - if (this.atScalar) { - this.atScalar = false; - yield* this.step(); - this.offset += source.length; - return; - } - const type = cst.tokenType(source); - if (!type) { - const message = `Not a YAML token: ${source}`; - yield* this.pop({ type: "error", offset: this.offset, message, source }); - this.offset += source.length; - } else if (type === "scalar") { - this.atNewLine = false; - this.atScalar = true; - this.type = "scalar"; - } else { - this.type = type; - yield* this.step(); - switch (type) { - case "newline": - this.atNewLine = true; - this.indent = 0; - if (this.onNewLine) - this.onNewLine(this.offset + source.length); - break; - case "space": - if (this.atNewLine && source[0] === " ") - this.indent += source.length; - break; - case "explicit-key-ind": - case "map-value-ind": - case "seq-item-ind": - if (this.atNewLine) - this.indent += source.length; - break; - case "doc-mode": - case "flow-error-end": - return; - default: - this.atNewLine = false; + static async doWrite(config3, writes) { + for (const w of writes) { + if (_isChannelWriteEntry(w)) { + if (w.channel === "__pregel_tasks") + throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); + if (_isPassthrough(w.value)) + throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); + } + if (_isChannelWriteTupleEntry(w)) { + if (_isPassthrough(w.value)) + throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); } - this.offset += source.length; } + const writeEntries = []; + for (const w of writes) + if (_isSend(w)) + writeEntries.push([TASKS, w]); + else if (_isChannelWriteTupleEntry(w)) { + const mappedResult = await w.mapper.invoke(w.value, config3); + if (mappedResult != null && mappedResult.length > 0) + writeEntries.push(...mappedResult); + } else if (_isChannelWriteEntry(w)) { + const mappedValue = w.mapper !== undefined ? await w.mapper.invoke(w.value, config3) : w.value; + if (_isSkipWrite(mappedValue)) + continue; + if (w.skipNone && mappedValue === undefined) + continue; + writeEntries.push([w.channel, mappedValue]); + } else + throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); + const write = config3.configurable?.[CONFIG_KEY_SEND]; + write(writeEntries); } - *end() { - while (this.stack.length > 0) - yield* this.pop(); + static isWriter(runnable) { + return runnable instanceof ChannelWrite2 || IS_WRITER in runnable && !!runnable[IS_WRITER]; } - get sourceToken() { - const st = { - type: this.type, - offset: this.offset, - indent: this.indent, - source: this.source - }; - return st; + static registerWriter(runnable) { + return Object.defineProperty(runnable, IS_WRITER, { value: true }); } - *step() { - const top = this.peek(1); - if (this.type === "doc-end" && top?.type !== "doc-end") { - while (this.stack.length > 0) - yield* this.pop(); - this.stack.push({ - type: "doc-end", - offset: this.offset, - source: this.source - }); - return; - } - if (!top) - return yield* this.stream(); - switch (top.type) { - case "document": - return yield* this.document(top); - case "alias": - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": - return yield* this.scalar(top); - case "block-scalar": - return yield* this.blockScalar(top); - case "block-map": - return yield* this.blockMap(top); - case "block-seq": - return yield* this.blockSequence(top); - case "flow-collection": - return yield* this.flowCollection(top); - case "doc-end": - return yield* this.documentEnd(top); - } - yield* this.pop(); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/read.js +var ChannelRead, defaultRunnableBound, PregelNode; +var init_read = __esm(() => { + init_constants3(); + init_utils8(); + init_write(); + init_runnables(); + ChannelRead = class ChannelRead2 extends RunnableCallable { + lc_graph_name = "ChannelRead"; + channel; + fresh = false; + mapper; + constructor(channel, mapper, fresh = false) { + super({ + trace: false, + func: (_, config3) => ChannelRead2.doRead(config3, this.channel, this.fresh, this.mapper) + }); + this.fresh = fresh; + this.mapper = mapper; + this.channel = channel; + this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; } - peek(n3) { - return this.stack[this.stack.length - n3]; + static doRead(config3, channel, fresh, mapper) { + const read = config3.configurable?.[CONFIG_KEY_READ]; + if (!read) + throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); + if (mapper) + return mapper(read(channel, fresh)); + else + return read(channel, fresh); } - *pop(error51) { - const token = error51 ?? this.stack.pop(); - if (!token) { - const message = "Tried to pop an empty stack"; - yield { type: "error", offset: this.offset, source: "", message }; - } else if (this.stack.length === 0) { - yield token; - } else { - const top = this.peek(1); - if (token.type === "block-scalar") { - token.indent = "indent" in top ? top.indent : 0; - } else if (token.type === "flow-collection" && top.type === "document") { - token.indent = 0; - } - if (token.type === "flow-collection") - fixFlowSeqItems(token); - switch (top.type) { - case "document": - top.value = token; - break; - case "block-scalar": - top.props.push(token); - break; - case "block-map": { - const it = top.items[top.items.length - 1]; - if (it.value) { - top.items.push({ start: [], key: token, sep: [] }); - this.onKeyLine = true; - return; - } else if (it.sep) { - it.value = token; - } else { - Object.assign(it, { key: token, sep: [] }); - this.onKeyLine = !it.explicitKey; - return; - } - break; - } - case "block-seq": { - const it = top.items[top.items.length - 1]; - if (it.value) - top.items.push({ start: [], value: token }); - else - it.value = token; - break; - } - case "flow-collection": { - const it = top.items[top.items.length - 1]; - if (!it || it.value) - top.items.push({ start: [], key: token, sep: [] }); - else if (it.sep) - it.value = token; - else - Object.assign(it, { key: token, sep: [] }); - return; - } - default: - yield* this.pop(); - yield* this.pop(token); - } - if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { - const last = token.items[token.items.length - 1]; - if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { - if (top.type === "document") - top.end = last.start; - else - top.items.push({ start: last.start }); - token.items.splice(-1, 1); - } + }; + defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough; + PregelNode = class PregelNode2 extends RunnableBinding { + lc_graph_name = "PregelNode"; + channels; + triggers = []; + mapper; + writers = []; + bound = defaultRunnableBound; + kwargs = {}; + metadata = {}; + tags = []; + retryPolicy; + cachePolicy; + subgraphs; + ends; + constructor(fields) { + const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; + const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; + super({ + ...fields, + bound: fields.bound ?? defaultRunnableBound, + config: { + ...fields.config ? fields.config : {}, + tags: mergedTags } - } + }); + this.channels = channels; + this.triggers = triggers; + this.mapper = mapper; + this.writers = writers ?? this.writers; + this.bound = bound ?? this.bound; + this.kwargs = kwargs ?? this.kwargs; + this.metadata = metadata ?? this.metadata; + this.tags = mergedTags; + this.retryPolicy = retryPolicy; + this.cachePolicy = cachePolicy; + this.subgraphs = subgraphs; + this.ends = ends; } - *stream() { - switch (this.type) { - case "directive-line": - yield { type: "directive", offset: this.offset, source: this.source }; - return; - case "byte-order-mark": - case "space": - case "comment": - case "newline": - yield this.sourceToken; - return; - case "doc-mode": - case "doc-start": { - const doc2 = { - type: "document", - offset: this.offset, - start: [] - }; - if (this.type === "doc-start") - doc2.start.push(this.sourceToken); - this.stack.push(doc2); - return; - } + getWriters() { + const newWriters = [...this.writers]; + while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { + const endWriters = newWriters.slice(-2); + const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); + newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); + newWriters.pop(); } - yield { - type: "error", - offset: this.offset, - message: `Unexpected ${this.type} token in YAML stream`, - source: this.source - }; + return newWriters; } - *document(doc2) { - if (doc2.value) - return yield* this.lineEnd(doc2); - switch (this.type) { - case "doc-start": { - if (findNonEmptyIndex(doc2.start) !== -1) { - yield* this.pop(); - yield* this.step(); - } else - doc2.start.push(this.sourceToken); - return; - } - case "anchor": - case "tag": - case "space": - case "comment": - case "newline": - doc2.start.push(this.sourceToken); - return; - } - const bv = this.startBlockValue(doc2); - if (bv) - this.stack.push(bv); - else { - yield { - type: "error", - offset: this.offset, - message: `Unexpected ${this.type} token in YAML document`, - source: this.source - }; - } + getNode() { + const writers = this.getWriters(); + if (this.bound === defaultRunnableBound && writers.length === 0) + return; + else if (this.bound === defaultRunnableBound && writers.length === 1) + return writers[0]; + else if (this.bound === defaultRunnableBound) + return new RunnableSequence({ + first: writers[0], + middle: writers.slice(1, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else if (writers.length > 0) + return new RunnableSequence({ + first: this.bound, + middle: writers.slice(0, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else + return this.bound; } - *scalar(scalar) { - if (this.type === "map-value-ind") { - const prev = getPrevProps(this.peek(2)); - const start = getFirstKeyStartProps(prev); - let sep2; - if (scalar.end) { - sep2 = scalar.end; - sep2.push(this.sourceToken); - delete scalar.end; - } else - sep2 = [this.sourceToken]; - const map2 = { - type: "block-map", - offset: scalar.offset, - indent: scalar.indent, - items: [{ start, key: scalar, sep: sep2 }] - }; - this.onKeyLine = true; - this.stack[this.stack.length - 1] = map2; - } else - yield* this.lineEnd(scalar); + join(channels) { + if (!Array.isArray(channels)) + throw new Error("channels must be a list"); + if (typeof this.channels !== "object") + throw new Error("all channels must be named when using .join()"); + return new PregelNode2({ + channels: { + ...this.channels, + ...Object.fromEntries(channels.map((chan) => [chan, chan])) + }, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); } - *blockScalar(scalar) { - switch (this.type) { - case "space": - case "comment": - case "newline": - scalar.props.push(this.sourceToken); - return; - case "scalar": - scalar.source = this.source; - this.atNewLine = true; - this.indent = 0; - if (this.onNewLine) { - let nl = this.source.indexOf(` -`) + 1; - while (nl !== 0) { - this.onNewLine(this.offset + nl); - nl = this.source.indexOf(` -`, nl) + 1; - } - } - yield* this.pop(); - break; - default: - yield* this.pop(); - yield* this.step(); - } + pipe(coerceable) { + if (ChannelWrite.isWriter(coerceable)) + return new PregelNode2({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: [...this.writers, coerceable], + bound: this.bound, + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else if (this.bound === defaultRunnableBound) + return new PregelNode2({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: _coerceToRunnable(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else + return new PregelNode2({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound.pipe(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); } - *blockMap(map2) { - const it = map2.items[map2.items.length - 1]; - switch (this.type) { - case "newline": - this.onKeyLine = false; - if (it.value) { - const end = "end" in it.value ? it.value.end : undefined; - const last = Array.isArray(end) ? end[end.length - 1] : undefined; - if (last?.type === "comment") - end?.push(this.sourceToken); - else - map2.items.push({ start: [this.sourceToken] }); - } else if (it.sep) { - it.sep.push(this.sourceToken); - } else { - it.start.push(this.sourceToken); - } - return; - case "space": - case "comment": - if (it.value) { - map2.items.push({ start: [this.sourceToken] }); - } else if (it.sep) { - it.sep.push(this.sourceToken); - } else { - if (this.atIndentedComment(it.start, map2.indent)) { - const prev = map2.items[map2.items.length - 2]; - const end = prev?.value?.end; - if (Array.isArray(end)) { - Array.prototype.push.apply(end, it.start); - end.push(this.sourceToken); - map2.items.pop(); - return; - } - } - it.start.push(this.sourceToken); - } - return; + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js +function isRunnableSequence(x) { + return "steps" in x && Array.isArray(x.steps); +} +function isPregelLike(x) { + return "lg_is_pregel" in x && x.lg_is_pregel === true; +} +function findSubgraphPregel(candidate) { + const candidates = [candidate]; + for (const candidate2 of candidates) + if (isPregelLike(candidate2)) + return candidate2; + else if (isRunnableSequence(candidate2)) + candidates.push(...candidate2.steps); +} +var init_subgraph = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/io.js +function readChannel(channels, chan, catchErrors = true, returnException = false) { + try { + return channels[chan].get(); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) { + if (returnException) + return e; + else if (catchErrors) + return null; + } + throw e; + } +} +function readChannels(channels, select, skipEmpty = true) { + if (Array.isArray(select)) { + const values = {}; + for (const k of select) + try { + values[k] = readChannel(channels, k, !skipEmpty); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) + continue; } - if (this.indent >= map2.indent) { - const atMapIndent = !this.onKeyLine && this.indent === map2.indent; - const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; - let start = []; - if (atNextItem && it.sep && !it.value) { - const nl = []; - for (let i = 0;i < it.sep.length; ++i) { - const st = it.sep[i]; - switch (st.type) { - case "newline": - nl.push(i); - break; - case "space": - break; - case "comment": - if (st.indent > map2.indent) - nl.length = 0; - break; - default: - nl.length = 0; - } - } - if (nl.length >= 2) - start = it.sep.splice(nl[1]); - } - switch (this.type) { - case "anchor": - case "tag": - if (atNextItem || it.value) { - start.push(this.sourceToken); - map2.items.push({ start }); - this.onKeyLine = true; - } else if (it.sep) { - it.sep.push(this.sourceToken); - } else { - it.start.push(this.sourceToken); - } - return; - case "explicit-key-ind": - if (!it.sep && !it.explicitKey) { - it.start.push(this.sourceToken); - it.explicitKey = true; - } else if (atNextItem || it.value) { - start.push(this.sourceToken); - map2.items.push({ start, explicitKey: true }); - } else { - this.stack.push({ - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start: [this.sourceToken], explicitKey: true }] - }); - } - this.onKeyLine = true; - return; - case "map-value-ind": - if (it.explicitKey) { - if (!it.sep) { - if (includesToken(it.start, "newline")) { - Object.assign(it, { key: null, sep: [this.sourceToken] }); - } else { - const start2 = getFirstKeyStartProps(it.start); - this.stack.push({ - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start: start2, key: null, sep: [this.sourceToken] }] - }); - } - } else if (it.value) { - map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); - } else if (includesToken(it.sep, "map-value-ind")) { - this.stack.push({ - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start, key: null, sep: [this.sourceToken] }] - }); - } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { - const start2 = getFirstKeyStartProps(it.start); - const key = it.key; - const sep2 = it.sep; - sep2.push(this.sourceToken); - delete it.key; - delete it.sep; - this.stack.push({ - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start: start2, key, sep: sep2 }] - }); - } else if (start.length > 0) { - it.sep = it.sep.concat(start, this.sourceToken); - } else { - it.sep.push(this.sourceToken); - } - } else { - if (!it.sep) { - Object.assign(it, { key: null, sep: [this.sourceToken] }); - } else if (it.value || atNextItem) { - map2.items.push({ start, key: null, sep: [this.sourceToken] }); - } else if (includesToken(it.sep, "map-value-ind")) { - this.stack.push({ - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start: [], key: null, sep: [this.sourceToken] }] - }); - } else { - it.sep.push(this.sourceToken); - } - } - this.onKeyLine = true; - return; - case "alias": - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": { - const fs = this.flowScalar(this.type); - if (atNextItem || it.value) { - map2.items.push({ start, key: fs, sep: [] }); - this.onKeyLine = true; - } else if (it.sep) { - this.stack.push(fs); - } else { - Object.assign(it, { key: fs, sep: [] }); - this.onKeyLine = true; - } - return; - } - default: { - const bv = this.startBlockValue(map2); - if (bv) { - if (bv.type === "block-seq") { - if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { - yield* this.pop({ - type: "error", - offset: this.offset, - message: "Unexpected block-seq-ind on same line with key", - source: this.source - }); - return; - } - } else if (atMapIndent) { - map2.items.push({ start }); - } - this.stack.push(bv); - return; - } - } - } - } - yield* this.pop(); - yield* this.step(); - } - *blockSequence(seq) { - const it = seq.items[seq.items.length - 1]; - switch (this.type) { - case "newline": - if (it.value) { - const end = "end" in it.value ? it.value.end : undefined; - const last = Array.isArray(end) ? end[end.length - 1] : undefined; - if (last?.type === "comment") - end?.push(this.sourceToken); - else - seq.items.push({ start: [this.sourceToken] }); - } else - it.start.push(this.sourceToken); - return; - case "space": - case "comment": - if (it.value) - seq.items.push({ start: [this.sourceToken] }); - else { - if (this.atIndentedComment(it.start, seq.indent)) { - const prev = seq.items[seq.items.length - 2]; - const end = prev?.value?.end; - if (Array.isArray(end)) { - Array.prototype.push.apply(end, it.start); - end.push(this.sourceToken); - seq.items.pop(); - return; - } - } - it.start.push(this.sourceToken); - } - return; - case "anchor": - case "tag": - if (it.value || this.indent <= seq.indent) - break; - it.start.push(this.sourceToken); - return; - case "seq-item-ind": - if (this.indent !== seq.indent) - break; - if (it.value || includesToken(it.start, "seq-item-ind")) - seq.items.push({ start: [this.sourceToken] }); - else - it.start.push(this.sourceToken); - return; - } - if (this.indent > seq.indent) { - const bv = this.startBlockValue(seq); - if (bv) { - this.stack.push(bv); - return; - } - } - yield* this.pop(); - yield* this.step(); - } - *flowCollection(fc) { - const it = fc.items[fc.items.length - 1]; - if (this.type === "flow-error-end") { - let top; - do { - yield* this.pop(); - top = this.peek(1); - } while (top?.type === "flow-collection"); - } else if (fc.end.length === 0) { - switch (this.type) { - case "comma": - case "explicit-key-ind": - if (!it || it.sep) - fc.items.push({ start: [this.sourceToken] }); - else - it.start.push(this.sourceToken); - return; - case "map-value-ind": - if (!it || it.value) - fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); - else if (it.sep) - it.sep.push(this.sourceToken); - else - Object.assign(it, { key: null, sep: [this.sourceToken] }); - return; - case "space": - case "comment": - case "newline": - case "anchor": - case "tag": - if (!it || it.value) - fc.items.push({ start: [this.sourceToken] }); - else if (it.sep) - it.sep.push(this.sourceToken); - else - it.start.push(this.sourceToken); - return; - case "alias": - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": { - const fs = this.flowScalar(this.type); - if (!it || it.value) - fc.items.push({ start: [], key: fs, sep: [] }); - else if (it.sep) - this.stack.push(fs); - else - Object.assign(it, { key: fs, sep: [] }); - return; - } - case "flow-map-end": - case "flow-seq-end": - fc.end.push(this.sourceToken); - return; - } - const bv = this.startBlockValue(fc); - if (bv) - this.stack.push(bv); - else { - yield* this.pop(); - yield* this.step(); - } - } else { - const parent = this.peek(2); - if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { - yield* this.pop(); - yield* this.step(); - } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { - const prev = getPrevProps(parent); - const start = getFirstKeyStartProps(prev); - fixFlowSeqItems(fc); - const sep2 = fc.end.splice(1, fc.end.length); - sep2.push(this.sourceToken); - const map2 = { - type: "block-map", - offset: fc.offset, - indent: fc.indent, - items: [{ start, key: fc, sep: sep2 }] - }; - this.onKeyLine = true; - this.stack[this.stack.length - 1] = map2; - } else { - yield* this.lineEnd(fc); - } - } - } - flowScalar(type) { - if (this.onNewLine) { - let nl = this.source.indexOf(` -`) + 1; - while (nl !== 0) { - this.onNewLine(this.offset + nl); - nl = this.source.indexOf(` -`, nl) + 1; - } - } - return { - type, - offset: this.offset, - indent: this.indent, - source: this.source - }; - } - startBlockValue(parent) { - switch (this.type) { - case "alias": - case "scalar": - case "single-quoted-scalar": - case "double-quoted-scalar": - return this.flowScalar(this.type); - case "block-scalar-header": - return { - type: "block-scalar", - offset: this.offset, - indent: this.indent, - props: [this.sourceToken], - source: "" - }; - case "flow-map-start": - case "flow-seq-start": - return { - type: "flow-collection", - offset: this.offset, - indent: this.indent, - start: this.sourceToken, - items: [], - end: [] - }; - case "seq-item-ind": - return { - type: "block-seq", - offset: this.offset, - indent: this.indent, - items: [{ start: [this.sourceToken] }] - }; - case "explicit-key-ind": { - this.onKeyLine = true; - const prev = getPrevProps(parent); - const start = getFirstKeyStartProps(prev); - start.push(this.sourceToken); - return { - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start, explicitKey: true }] - }; - } - case "map-value-ind": { - this.onKeyLine = true; - const prev = getPrevProps(parent); - const start = getFirstKeyStartProps(prev); - return { - type: "block-map", - offset: this.offset, - indent: this.indent, - items: [{ start, key: null, sep: [this.sourceToken] }] - }; - } - } - return null; - } - atIndentedComment(start, indent) { - if (this.type !== "comment") - return false; - if (this.indent <= indent) - return false; - return start.every((st) => st.type === "newline" || st.type === "space"); - } - *documentEnd(docEnd) { - if (this.type !== "doc-mode") { - if (docEnd.end) - docEnd.end.push(this.sourceToken); - else - docEnd.end = [this.sourceToken]; - if (this.type === "newline") - yield* this.pop(); - } - } - *lineEnd(token) { - switch (this.type) { - case "comma": - case "doc-start": - case "doc-end": - case "flow-seq-end": - case "flow-map-end": - case "map-value-ind": - yield* this.pop(); - yield* this.step(); - break; - case "newline": - this.onKeyLine = false; - case "space": - case "comment": - default: - if (token.end) - token.end.push(this.sourceToken); - else - token.end = [this.sourceToken]; - if (this.type === "newline") - yield* this.pop(); - } - } - } - exports.Parser = Parser; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/public-api.js -var require_public_api = __commonJS((exports) => { - var composer = require_composer(); - var Document2 = require_Document(); - var errors4 = require_errors(); - var log = require_log(); - var identity = require_identity(); - var lineCounter = require_line_counter(); - var parser = require_parser(); - function parseOptions(options) { - const prettyErrors = options.prettyErrors !== false; - const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null; - return { lineCounter: lineCounter$1, prettyErrors }; - } - function parseAllDocuments(source, options = {}) { - const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); - const parser$1 = new parser.Parser(lineCounter2?.addNewLine); - const composer$1 = new composer.Composer(options); - const docs = Array.from(composer$1.compose(parser$1.parse(source))); - if (prettyErrors && lineCounter2) - for (const doc2 of docs) { - doc2.errors.forEach(errors4.prettifyError(source, lineCounter2)); - doc2.warnings.forEach(errors4.prettifyError(source, lineCounter2)); - } - if (docs.length > 0) - return docs; - return Object.assign([], { empty: true }, composer$1.streamInfo()); + return values; + } else + return readChannel(channels, select); +} +function* mapCommand(cmd, pendingWrites) { + if (cmd.graph === Command.PARENT) + throw new InvalidUpdateError("There is no parent graph."); + if (cmd.goto) { + let sends; + if (Array.isArray(cmd.goto)) + sends = cmd.goto; + else + sends = [cmd.goto]; + for (const send of sends) + if (_isSend(send)) + yield [ + NULL_TASK_ID, + TASKS, + send + ]; + else if (typeof send === "string") + yield [ + NULL_TASK_ID, + `branch:to:${send}`, + "__start__" + ]; + else + throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); } - function parseDocument(source, options = {}) { - const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); - const parser$1 = new parser.Parser(lineCounter2?.addNewLine); - const composer$1 = new composer.Composer(options); - let doc2 = null; - for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { - if (!doc2) - doc2 = _doc; - else if (doc2.options.logLevel !== "silent") { - doc2.errors.push(new errors4.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); - break; + if (cmd.resume) + if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) + for (const [tid, resume] of Object.entries(cmd.resume)) { + const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === "__resume__").map((w) => w[2]).slice(0, 1) ?? []; + existing.push(resume); + yield [ + tid, + RESUME, + existing + ]; } - } - if (prettyErrors && lineCounter2) { - doc2.errors.forEach(errors4.prettifyError(source, lineCounter2)); - doc2.warnings.forEach(errors4.prettifyError(source, lineCounter2)); - } - return doc2; + else + yield [ + NULL_TASK_ID, + RESUME, + cmd.resume + ]; + if (cmd.update) { + if (typeof cmd.update !== "object" || !cmd.update) + throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); + if (Array.isArray(cmd.update)) + for (const [k, v] of cmd.update) + yield [ + NULL_TASK_ID, + k, + v + ]; + else + for (const [k, v] of Object.entries(cmd.update)) + yield [ + NULL_TASK_ID, + k, + v + ]; } - function parse11(src, reviver2, options) { - let _reviver2 = undefined; - if (typeof reviver2 === "function") { - _reviver2 = reviver2; - } else if (options === undefined && reviver2 && typeof reviver2 === "object") { - options = reviver2; - } - const doc2 = parseDocument(src, options); - if (!doc2) - return null; - doc2.warnings.forEach((warning) => log.warn(doc2.options.logLevel, warning)); - if (doc2.errors.length > 0) { - if (doc2.options.logLevel !== "silent") - throw doc2.errors[0]; +} +function* mapInput(inputChannels, chunk) { + if (chunk !== undefined && chunk !== null) + if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { + for (const k in chunk) + if (inputChannels.includes(k)) + yield [k, chunk[k]]; + } else if (Array.isArray(inputChannels)) + throw new Error(`Input chunk must be an object when "inputChannels" is an array`); + else + yield [inputChannels, chunk]; +} +function* mapOutputValues(outputChannels, pendingWrites, channels) { + if (Array.isArray(outputChannels)) { + if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) + yield readChannels(channels, outputChannels); + } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) + yield readChannel(channels, outputChannels); +} +function* mapOutputUpdates(outputChannels, tasks, cached3) { + const outputTasks = tasks.filter(([task, ww]) => { + return (task.config === undefined || !task.config.tags?.includes("langsmith:hidden")) && ww[0][0] !== "__error__" && ww[0][0] !== "__interrupt__"; + }); + if (!outputTasks.length) + return; + let updated; + if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === "__return__"))) + updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); + else if (!Array.isArray(outputChannels)) + updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); + else + updated = outputTasks.flatMap(([task]) => { + const { writes } = task; + const counts = {}; + for (const [chan] of writes) + if (outputChannels.includes(chan)) + counts[chan] = (counts[chan] || 0) + 1; + if (Object.values(counts).some((count) => count > 1)) + return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); else - doc2.errors = []; - } - return doc2.toJS(Object.assign({ reviver: _reviver2 }, options)); - } - function stringify4(value, replacer, options) { - let _replacer = null; - if (typeof replacer === "function" || Array.isArray(replacer)) { - _replacer = replacer; - } else if (options === undefined && replacer) { - options = replacer; - } - if (typeof options === "string") - options = options.length; - if (typeof options === "number") { - const indent = Math.round(options); - options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; - } - if (value === undefined) { - const { keepUndefined } = options ?? replacer ?? {}; - if (!keepUndefined) - return; - } - if (identity.isDocument(value) && !_replacer) - return value.toString(options); - return new Document2.Document(value, _replacer, options).toString(options); + return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; + }); + const grouped = {}; + for (const [node, value] of updated) { + if (!(node in grouped)) + grouped[node] = []; + grouped[node].push(value); } - exports.parse = parse11; - exports.parseAllDocuments = parseAllDocuments; - exports.parseDocument = parseDocument; - exports.stringify = stringify4; -}); - -// ../../node_modules/.pnpm/yaml@2.8.4/node_modules/yaml/dist/index.js -var require_dist3 = __commonJS((exports) => { - var composer = require_composer(); - var Document2 = require_Document(); - var Schema = require_Schema(); - var errors4 = require_errors(); - var Alias = require_Alias(); - var identity = require_identity(); - var Pair = require_Pair(); - var Scalar = require_Scalar(); - var YAMLMap = require_YAMLMap(); - var YAMLSeq = require_YAMLSeq(); - var cst = require_cst(); - var lexer = require_lexer(); - var lineCounter = require_line_counter(); - var parser = require_parser(); - var publicApi = require_public_api(); - var visit = require_visit(); - exports.Composer = composer.Composer; - exports.Document = Document2.Document; - exports.Schema = Schema.Schema; - exports.YAMLError = errors4.YAMLError; - exports.YAMLParseError = errors4.YAMLParseError; - exports.YAMLWarning = errors4.YAMLWarning; - exports.Alias = Alias.Alias; - exports.isAlias = identity.isAlias; - exports.isCollection = identity.isCollection; - exports.isDocument = identity.isDocument; - exports.isMap = identity.isMap; - exports.isNode = identity.isNode; - exports.isPair = identity.isPair; - exports.isScalar = identity.isScalar; - exports.isSeq = identity.isSeq; - exports.Pair = Pair.Pair; - exports.Scalar = Scalar.Scalar; - exports.YAMLMap = YAMLMap.YAMLMap; - exports.YAMLSeq = YAMLSeq.YAMLSeq; - exports.CST = cst; - exports.Lexer = lexer.Lexer; - exports.LineCounter = lineCounter.LineCounter; - exports.Parser = parser.Parser; - exports.parse = publicApi.parse; - exports.parseAllDocuments = publicApi.parseAllDocuments; - exports.parseDocument = publicApi.parseDocument; - exports.stringify = publicApi.stringify; - exports.visit = visit.visit; - exports.visitAsync = visit.visitAsync; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/singletons/fetch.js -var DEFAULT_FETCH_IMPLEMENTATION2 = (...args) => fetch(...args), LANGSMITH_FETCH_IMPLEMENTATION_KEY2, _getFetchImplementation2 = () => { - return globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY2] ?? DEFAULT_FETCH_IMPLEMENTATION2; -}; -var init_fetch2 = __esm(() => { - LANGSMITH_FETCH_IMPLEMENTATION_KEY2 = Symbol.for("lg:fetch_implementation"); + const flattened = {}; + for (const node in grouped) + if (grouped[node].length === 1) { + const [write] = grouped[node]; + flattened[node] = write; + } else + flattened[node] = grouped[node]; + if (cached3) + flattened["__metadata__"] = { cached: cached3 }; + yield flattened; +} +var init_io = __esm(() => { + init_constants3(); + init_errors7(); + init_hash3(); }); -// ../../node_modules/.pnpm/is-network-error@1.3.2/node_modules/is-network-error/index.js -function isNetworkError3(error51) { - const isValid2 = error51 && isError3(error51) && error51.name === "TypeError" && typeof error51.message === "string"; - if (!isValid2) { - return false; - } - const { message, stack } = error51; - if (message === "Load failed" || message.startsWith("Load failed (") && message.endsWith(")")) { - return stack === undefined || "__sentry_captured__" in error51; - } - if (message.startsWith("error sending request for url")) { - return true; - } - if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) { - return true; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/utils/index.js +function getNullChannelVersion(currentVersions) { + const startVersion = typeof currentVersions[START]; + if (startVersion === "number") + return 0; + if (startVersion === "string") + return ""; + for (const key in currentVersions) { + if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) + continue; + const versionType = typeof currentVersions[key]; + if (versionType === "number") + return 0; + if (versionType === "string") + return ""; + break; } - return errorMessages3.has(message); } -var objectToString4, isError3 = (value) => objectToString4.call(value) === "[object Error]", errorMessages3; -var init_is_network_error3 = __esm(() => { - objectToString4 = Object.prototype.toString; - errorMessages3 = new Set([ - "network error", - "NetworkError when attempting to fetch resource.", - "The Internet connection appears to be offline.", - "Network request failed", - "fetch failed", - "terminated", - " A network error occurred.", - "Network connection lost" - ]); -}); - -// ../../node_modules/.pnpm/p-retry@7.1.1/node_modules/p-retry/index.js -function validateRetries3(retries) { - if (typeof retries === "number") { - if (retries < 0) { - throw new TypeError("Expected `retries` to be a non-negative number."); - } - if (Number.isNaN(retries)) { - throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); +function getNewChannelVersions(previousVersions, currentVersions) { + if (Object.keys(previousVersions).length > 0) { + const nullVersion = getNullChannelVersion(currentVersions); + return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); + } else + return currentVersions; +} +function _coerceToDict3(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function patchConfigurable2(config3, patch) { + if (config3 === null) + return { configurable: patch }; + else if (config3?.configurable === undefined) + return { + ...config3, + configurable: patch + }; + else + return { + ...config3, + configurable: { + ...config3.configurable, + ...patch + } + }; +} +function patchCheckpointMap(config3, metadata) { + const parents = metadata?.parents ?? {}; + if (Object.keys(parents).length > 0) + return patchConfigurable2(config3, { [CONFIG_KEY_CHECKPOINT_MAP]: { + ...parents, + [config3.configurable?.checkpoint_ns ?? ""]: config3.configurable?.checkpoint_id + } }); + else + return config3; +} +function combineAbortSignals(...x) { + const signals = [...new Set(x.filter(Boolean))]; + if (signals.length === 0) + return { + signal: undefined, + dispose: undefined + }; + if (signals.length === 1) + return { + signal: signals[0], + dispose: undefined + }; + const combinedController = new AbortController; + const listener = () => { + const reason = signals.find((s) => s.aborted)?.reason; + combinedController.abort(reason); + signals.forEach((s) => s.removeEventListener("abort", listener)); + }; + signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); + const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); + if (hasAlreadyAbortedSignal) + combinedController.abort(hasAlreadyAbortedSignal.reason); + return { + signal: combinedController.signal, + dispose: () => { + signals.forEach((s) => s.removeEventListener("abort", listener)); } - } else if (retries !== undefined) { - throw new TypeError("Expected `retries` to be a number or Infinity."); - } + }; } -function validateNumberOption3(name, value, { min = 0, allowInfinity = false } = {}) { - if (value === undefined) { +var combineCallbacks = (callback1, callback2) => { + if (!callback1 && !callback2) return; - } - if (typeof value !== "number" || Number.isNaN(value)) { - throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); - } - if (!allowInfinity && !Number.isFinite(value)) { - throw new TypeError(`Expected \`${name}\` to be a finite number.`); - } - if (value < min) { - throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`); - } -} -function calculateDelay3(retriesConsumed, options) { - const attempt = Math.max(1, retriesConsumed + 1); - const random = options.randomize ? Math.random() + 1 : 1; - let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); - timeout = Math.min(timeout, options.maxTimeout); - return timeout; + if (!callback1) + return callback2; + if (!callback2) + return callback1; + if (Array.isArray(callback1) && Array.isArray(callback2)) + return [...callback1, ...callback2]; + if (Array.isArray(callback1)) + return [...callback1, callback2]; + if (Array.isArray(callback2)) + return [callback1, ...callback2]; + return [callback1, callback2]; +}; +var init_utils9 = __esm(() => { + init_constants3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/types.js +function isCall(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; } -function calculateRemainingTime3(start, max) { - if (!Number.isFinite(max)) { - return max; +var Call = class { + func; + name; + input; + retry; + cache; + callbacks; + __lg_type = "call"; + constructor({ func, name, input, retry, cache: cache2, callbacks }) { + this.func = func; + this.name = name; + this.input = input; + this.retry = retry; + this.cache = cache2; + this.callbacks = callbacks; } - return max - (performance.now() - start); +}; +var init_types7 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/call.js +function getRunnableForFunc(name, func) { + return new RunnableSequence({ + name, + first: new RunnableCallable({ + func: (input) => func(...input), + name, + trace: false, + recurse: false + }), + last: new ChannelWrite([{ + channel: RETURN, + value: PASSTHROUGH + }], [TAG_HIDDEN]) + }); } -async function onAttemptFailure3({ error: error51, attemptNumber, retriesConsumed, startTime, options }) { - const normalizedError = error51 instanceof Error ? error51 : new TypeError(`Non-error was thrown: "${error51}". You should only throw errors.`); - if (normalizedError instanceof AbortError3) { - throw normalizedError.originalError; - } - const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; - const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; - const context2 = Object.freeze({ - error: normalizedError, - attemptNumber, - retriesLeft, - retriesConsumed +function getRunnableForEntrypoint(name, func) { + return new RunnableCallable({ + func: (input, config3) => { + return func(input, config3); + }, + name, + trace: false, + recurse: false }); - await options.onFailedAttempt(context2); - if (calculateRemainingTime3(startTime, maxRetryTime) <= 0) { - throw normalizedError; - } - const consumeRetry = await options.shouldConsumeRetry(context2); - const remainingTime = calculateRemainingTime3(startTime, maxRetryTime); - if (remainingTime <= 0 || retriesLeft <= 0) { - throw normalizedError; - } - if (normalizedError instanceof TypeError && !isNetworkError3(normalizedError)) { - if (consumeRetry) { - throw normalizedError; - } - options.signal?.throwIfAborted(); - return false; - } - if (!await options.shouldRetry(context2)) { - throw normalizedError; - } - if (!consumeRetry) { - options.signal?.throwIfAborted(); - return false; - } - const delayTime = calculateDelay3(retriesConsumed, options); - const finalDelay = Math.min(delayTime, remainingTime); - options.signal?.throwIfAborted(); - if (finalDelay > 0) { - await new Promise((resolve2, reject) => { - const onAbort = () => { - clearTimeout(timeoutToken); - options.signal?.removeEventListener("abort", onAbort); - reject(options.signal.reason); - }; - const timeoutToken = setTimeout(() => { - options.signal?.removeEventListener("abort", onAbort); - resolve2(); - }, finalDelay); - if (options.unref) { - timeoutToken.unref?.(); - } - options.signal?.addEventListener("abort", onAbort, { once: true }); +} +function call({ func, name, cache: cache2, retry }, ...args) { + const config3 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (typeof config3.configurable?.["__pregel_call"] === "function") + return config3.configurable[CONFIG_KEY_CALL](func, name, args, { + retry, + cache: cache2, + callbacks: config3.callbacks }); - } - options.signal?.throwIfAborted(); - return true; + throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); } -async function pRetry3(input, options = {}) { - options = { ...options }; - validateRetries3(options.retries); - if (Object.hasOwn(options, "forever")) { - throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); - } - options.retries ??= 10; - options.factor ??= 2; - options.minTimeout ??= 1000; - options.maxTimeout ??= Number.POSITIVE_INFINITY; - options.maxRetryTime ??= Number.POSITIVE_INFINITY; - options.randomize ??= false; - options.onFailedAttempt ??= () => {}; - options.shouldRetry ??= () => true; - options.shouldConsumeRetry ??= () => true; - validateNumberOption3("factor", options.factor, { min: 0, allowInfinity: false }); - validateNumberOption3("minTimeout", options.minTimeout, { min: 0, allowInfinity: false }); - validateNumberOption3("maxTimeout", options.maxTimeout, { min: 0, allowInfinity: true }); - validateNumberOption3("maxRetryTime", options.maxRetryTime, { min: 0, allowInfinity: true }); - if (!(options.factor > 0)) { - options.factor = 1; +var init_call = __esm(() => { + init_constants3(); + init_utils8(); + init_write(); + init_singletons(); + init_runnables(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/algo.js +function triggersNextStep(updatedChannels, triggerToNodes) { + if (triggerToNodes == null) + return false; + for (const chan of updatedChannels) + if (triggerToNodes[chan]) + return true; + return false; +} +function maxChannelMapVersion(channelVersions) { + let maxVersion; + for (const chan in channelVersions) { + if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) + continue; + if (maxVersion == null) + maxVersion = channelVersions[chan]; + else + maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); } - options.signal?.throwIfAborted(); - let attemptNumber = 0; - let retriesConsumed = 0; - const startTime = performance.now(); - while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { - attemptNumber++; - try { - options.signal?.throwIfAborted(); - const result = await input(attemptNumber); - options.signal?.throwIfAborted(); - return result; - } catch (error51) { - if (await onAttemptFailure3({ - error: error51, - attemptNumber, - retriesConsumed, - startTime, - options - })) { - retriesConsumed++; + return maxVersion; +} +function shouldInterrupt(checkpoint, interruptNodes, tasks) { + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + const seen = checkpoint.versions_seen["__interrupt__"] ?? {}; + let anyChannelUpdated = false; + if ((checkpoint.channel_versions["__start__"] ?? nullVersion) > (seen["__start__"] ?? nullVersion)) + anyChannelUpdated = true; + else + for (const chan in checkpoint.channel_versions) { + if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) + continue; + if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { + anyChannelUpdated = true; + break; } } - } - throw new Error("Retry attempts exhausted without throwing an error."); + const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); + return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; } -var AbortError3; -var init_p_retry3 = __esm(() => { - init_is_network_error3(); - AbortError3 = class AbortError3 extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({ message } = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; +function _localRead(checkpoint, channels, task, select, fresh = false) { + let updated = /* @__PURE__ */ new Set; + if (!Array.isArray(select)) { + for (const [c] of task.writes) + if (c === select) { + updated = new Set([c]); + break; } - this.name = "AbortError"; - this.message = message; + updated = updated || /* @__PURE__ */ new Set; + } else + updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); + let values; + if (fresh && updated.size > 0) { + const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); + const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1); + const newChannels = emptyChannels(localChannels, newCheckpoint); + _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], undefined, undefined); + values = readChannels({ + ...channels, + ...newChannels + }, select); + } else + values = readChannels(channels, select); + return values; +} +function _localWrite(commit, processes, writes) { + for (const [chan, value] of writes) + if (["__pregel_push", "__pregel_tasks"].includes(chan) && value != null) { + if (!_isSend(value)) + throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); + if (!(value.node in processes)) + throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); } - }; -}); - -// ../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js -var require_eventemitter32 = __commonJS((exports, module) => { - var has = Object.prototype.hasOwnProperty; - var prefix = "~"; - function Events() {} - if (Object.create) { - Events.prototype = Object.create(null); - if (!new Events().__proto__) - prefix = false; - } - function EE(fn, context2, once) { - this.fn = fn; - this.context = context2; - this.once = once || false; - } - function addListener(emitter, event, fn, context2, once) { - if (typeof fn !== "function") { - throw new TypeError("The listener must be a function"); + commit(writes); +} +function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { + tasks.sort((a, b) => { + const aPath = a.path?.slice(0, 3) || []; + const bPath = b.path?.slice(0, 3) || []; + for (let i = 0;i < Math.min(aPath.length, bPath.length); i += 1) { + if (aPath[i] < bPath[i]) + return -1; + if (aPath[i] > bPath[i]) + return 1; } - var listener = new EE(fn, context2 || emitter, once), evt = prefix ? prefix + event : event; - if (!emitter._events[evt]) - emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) - emitter._events[evt].push(listener); - else - emitter._events[evt] = [emitter._events[evt], listener]; - return emitter; - } - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) - emitter._events = new Events; - else - delete emitter._events[evt]; - } - function EventEmitter() { - this._events = new Events; - this._eventsCount = 0; + return aPath.length - bPath.length; + }); + const bumpStep = tasks.some((task) => task.triggers.length > 0); + const onlyChannels = getOnlyChannels(channels); + for (const task of tasks) { + checkpoint.versions_seen[task.name] ??= {}; + for (const chan of task.triggers) + if (chan in checkpoint.channel_versions) + checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; } - EventEmitter.prototype.eventNames = function eventNames() { - var names = [], events, name; - if (this._eventsCount === 0) - return names; - for (name in events = this._events) { - if (has.call(events, name)) - names.push(prefix ? name.slice(1) : name); - } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); + let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); + const channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan))); + let usedNewVersion = false; + for (const chan of channelsToConsume) + if (chan in onlyChannels && onlyChannels[chan].consume()) { + if (getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + usedNewVersion = true; + } } - return names; - }; - EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event, handlers = this._events[evt]; - if (!handlers) - return []; - if (handlers.fn) - return [handlers.fn]; - for (var i = 0, l = handlers.length, ee = new Array(l);i < l; i++) { - ee[i] = handlers[i].fn; - } - return ee; - }; - EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event, listeners = this._events[evt]; - if (!listeners) - return 0; - if (listeners.fn) - return 1; - return listeners.length; - }; - EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) - return false; - var listeners = this._events[evt], len = arguments.length, args, i; - if (listeners.fn) { - if (listeners.once) - this.removeListener(event, listeners.fn, undefined, true); - switch (len) { - case 1: - return listeners.fn.call(listeners.context), true; - case 2: - return listeners.fn.call(listeners.context, a1), true; - case 3: - return listeners.fn.call(listeners.context, a1, a2), true; - case 4: - return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: - return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: - return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + const pendingWritesByChannel = {}; + for (const task of tasks) + for (const [chan, val] of task.writes) + if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { + pendingWritesByChannel[chan] ??= []; + pendingWritesByChannel[chan].push(val); } - for (i = 1, args = new Array(len - 1);i < len; i++) { - args[i - 1] = arguments[i]; + if (maxVersion != null && getNextVersion != null) + maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; + const updatedChannels = /* @__PURE__ */ new Set; + for (const [chan, vals] of Object.entries(pendingWritesByChannel)) + if (chan in onlyChannels) { + const channel = onlyChannels[chan]; + let updated; + try { + updated = channel.update(vals); + } catch (e) { + if (e.name === InvalidUpdateError.unminifiable_name) { + const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); + wrappedError.lc_error_code = e.lc_error_code; + throw wrappedError; + } else + throw e; } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length, j; - for (i = 0;i < length; i++) { - if (listeners[i].once) - this.removeListener(event, listeners[i].fn, undefined, true); - switch (len) { - case 1: - listeners[i].fn.call(listeners[i].context); - break; - case 2: - listeners[i].fn.call(listeners[i].context, a1); - break; - case 3: - listeners[i].fn.call(listeners[i].context, a1, a2); - break; - case 4: - listeners[i].fn.call(listeners[i].context, a1, a2, a3); - break; - default: - if (!args) - for (j = 1, args = new Array(len - 1);j < len; j++) { - args[j - 1] = arguments[j]; - } - listeners[i].fn.apply(listeners[i].context, args); - } + if (updated && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); } } - return true; - }; - EventEmitter.prototype.on = function on(event, fn, context2) { - return addListener(this, event, fn, context2, false); - }; - EventEmitter.prototype.once = function once(event, fn, context2) { - return addListener(this, event, fn, context2, true); - }; - EventEmitter.prototype.removeListener = function removeListener(event, fn, context2, once) { - var evt = prefix ? prefix + event : event; - if (!this._events[evt]) - return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - var listeners = this._events[evt]; - if (listeners.fn) { - if (listeners.fn === fn && (!once || listeners.once) && (!context2 || listeners.context === context2)) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length;i < length; i++) { - if (listeners[i].fn !== fn || once && !listeners[i].once || context2 && listeners[i].context !== context2) { - events.push(listeners[i]); + if (bumpStep) + for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) + continue; + const channel = onlyChannels[chan]; + if (channel.isAvailable() && !updatedChannels.has(chan)) { + if (channel.update([]) && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); } } - if (events.length) - this._events[evt] = events.length === 1 ? events[0] : events; - else - clearEvent(this, evt); } - return this; - }; - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) - clearEvent(this, evt); - } else { - this._events = new Events; - this._eventsCount = 0; + if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) + for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) + continue; + const channel = onlyChannels[chan]; + if (channel.finish() && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); + } } - return this; - }; - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - EventEmitter.prefixed = prefix; - EventEmitter.EventEmitter = EventEmitter; - if (typeof module !== "undefined") { - module.exports = EventEmitter; + return updatedChannels; +} +function* candidateNodes(checkpoint, processes, extra) { + if (extra.updatedChannels != null && extra.triggerToNodes != null) { + const triggeredNodes = /* @__PURE__ */ new Set; + for (const channel of extra.updatedChannels) { + const nodeIds = extra.triggerToNodes[channel]; + for (const id of nodeIds ?? []) + triggeredNodes.add(id); + } + yield* [...triggeredNodes].sort(); + return; } -}); - -// ../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs -var import__3; -var init_eventemitter3 = __esm(() => { - import__3 = __toESM(require_eventemitter32(), 1); -}); - -// ../../node_modules/.pnpm/p-timeout@7.0.1/node_modules/p-timeout/index.js -function pTimeout(promise2, options) { - const { - milliseconds, - fallback, - message, - customTimers = { setTimeout, clearTimeout }, - signal - } = options; - let timer; - let abortHandler; - const wrappedPromise = new Promise((resolve2, reject) => { - if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) { - throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``); + if ((() => { + for (const chan in checkpoint.channel_versions) + if (checkpoint.channel_versions[chan] !== null) + return false; + return true; + })()) + return; + for (const name in processes) { + if (!Object.prototype.hasOwnProperty.call(processes, name)) + continue; + yield name; + } +} +function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config3, forExecution, extra) { + const tasks = {}; + const tasksChannel = channels[TASKS]; + if (tasksChannel?.isAvailable()) { + const len = tasksChannel.get().length; + for (let i = 0;i < len; i += 1) { + const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config3, forExecution, extra); + if (task !== undefined) + tasks[task.id] = task; } - if (signal?.aborted) { - reject(getAbortedReason(signal)); + } + for (const name of candidateNodes(checkpoint, processes, extra)) { + const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config3, forExecution, extra); + if (task !== undefined) + tasks[task.id] = task; + } + return tasks; +} +function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config3, forExecution, extra) { + const { step, checkpointer, manager } = extra; + const configurable = config3.configurable ?? {}; + const parentNamespace = configurable.checkpoint_ns ?? ""; + if (taskPath[0] === "__pregel_push" && isCall(taskPath[taskPath.length - 1])) { + const call2 = taskPath[taskPath.length - 1]; + const proc = getRunnableForFunc(call2.name, call2.func); + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? call2.name : `${parentNamespace}|${call2.name}`; + const id = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + call2.name, + PUSH, + taskPath[1], + taskPath[2] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${id}`; + const outputTaskPath = [...taskPath.slice(0, 3), true]; + const metadata = { + langgraph_step: step, + langgraph_node: call2.name, + langgraph_triggers: triggers, + langgraph_path: outputTaskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId: id, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; + return { + name: call2.name, + input: call2.input, + proc, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + store: extra.store ?? config3.store + }), { + runName: call2.name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: id, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: call2.name, + writes, + triggers, + path: outputTaskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId: id, + currentTaskInput: call2.input, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: call2.retry, + cache_key: call2.cache ? { + key: XXH3((call2.cache.keyFunc ?? JSON.stringify)([call2.input])), + ns: [CACHE_NS_WRITES, call2.name ?? "__dynamic__"], + ttl: call2.cache.ttl + } : undefined, + id, + path: outputTaskPath, + writers: [] + }; + } else + return { + id, + name: call2.name, + interrupts: [], + path: outputTaskPath + }; + } else if (taskPath[0] === "__pregel_push") { + const index2 = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); + if (!channels["__pregel_tasks"]?.isAvailable()) + return; + const sends = channels[TASKS].get(); + if (index2 < 0 || index2 >= sends.length) + return; + const packet = _isSendInterface(sends[index2]) && !_isSend(sends[index2]) ? new Send(sends[index2].node, sends[index2].args) : sends[index2]; + if (!_isSendInterface(packet)) { + console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); return; } - if (signal) { - abortHandler = () => { - reject(getAbortedReason(signal)); + if (!(packet.node in processes)) { + console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); + return; + } + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}|${packet.node}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + packet.node, + PUSH, + index2.toString() + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: packet.node, + langgraph_triggers: triggers, + langgraph_path: taskPath.slice(0, 3), + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const proc = processes[packet.node]; + const node = proc.getNode(); + if (node !== undefined) { + if (proc.metadata !== undefined) + metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; + return { + name: packet.node, + input: packet.args, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + tags: proc.tags, + store: extra.store ?? config3.store + }), { + runName: packet.node, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: packet.node, + writes, + triggers, + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: packet.args, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + packet.node + ], + ttl: proc.cachePolicy.ttl + } : undefined, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else + return { + id: taskId, + name: packet.node, + interrupts: [], + path: taskPath }; - signal.addEventListener("abort", abortHandler, { once: true }); + } else if (taskPath[0] === "__pregel_pull") { + const name = taskPath[1].toString(); + const proc = processes[name]; + if (proc === undefined) + return; + if (pendingWrites?.length) { + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + name + ]), checkpoint.id); + if (pendingWrites.some((w) => w[0] === taskId && w[1] !== "__error__")) + return; } - promise2.then(resolve2, reject); - if (milliseconds === Number.POSITIVE_INFINITY) { + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + if (nullVersion === undefined) return; + const seen = checkpoint.versions_seen[name] ?? {}; + const trigger = proc.triggers.find((chan) => { + if (!channels[chan].isAvailable()) + return false; + return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); + }); + if (trigger !== undefined) { + const val = _procInput(proc, channels, forExecution); + if (val === undefined) + return; + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + [trigger] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: name, + langgraph_triggers: [trigger], + langgraph_path: taskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const node = proc.getNode(); + if (node !== undefined) { + if (proc.metadata !== undefined) + metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; + return { + name, + input: val, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + tags: proc.tags, + store: extra.store ?? config3.store + }), { + runName: name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { + writes.push(...items); + }, processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name, + writes, + triggers: [trigger], + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: val, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers: [trigger], + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + name + ], + ttl: proc.cachePolicy.ttl + } : undefined, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else + return { + id: taskId, + name, + interrupts: [], + path: taskPath + }; } - const timeoutError = new TimeoutError; - timer = customTimers.setTimeout.call(undefined, () => { - if (fallback) { + } +} +function _procInput(proc, channels, forExecution) { + let val; + if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { + val = {}; + for (const [k, chan] of Object.entries(proc.channels)) + if (proc.triggers.includes(chan)) try { - resolve2(fallback()); - } catch (error51) { - reject(error51); + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) + return; + else + throw e; } - return; + else if (chan in channels) + try { + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) + continue; + else + throw e; + } + } else if (Array.isArray(proc.channels)) { + let successfulRead = false; + for (const chan of proc.channels) + try { + val = readChannel(channels, chan, false); + successfulRead = true; + break; + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) + continue; + else + throw e; } - if (typeof promise2.cancel === "function") { - promise2.cancel(); + if (!successfulRead) + return; + } else + throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); + if (forExecution && proc.mapper !== undefined) + val = proc.mapper(val); + return val; +} +function sanitizeUntrackedValuesInSend(packet, channels) { + if (typeof packet.args !== "object" || packet.args === null) + return packet; + const sanitizedArg = {}; + for (const [key, value] of Object.entries(packet.args)) { + const channel = channels[key]; + if (!channel || channel.lc_graph_name !== "UntrackedValue") + sanitizedArg[key] = value; + } + return new Send(packet.node, sanitizedArg); +} +function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { + const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__")?.[2]; + const scratchpad = { + callCounter: 0, + interruptCounter: -1, + resume: (() => { + const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === "__resume__").flatMap(([_writeTaskId, _chan, resume]) => resume); + if (resumeMap != null && namespaceHash in resumeMap) { + const mappedResume = resumeMap[namespaceHash]; + result.push(mappedResume); } - if (message === false) { - resolve2(); - } else if (message instanceof Error) { - reject(message); - } else { - timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`; - reject(timeoutError); + return result; + })(), + nullResume, + subgraphCounter: 0, + currentTaskInput, + consumeNullResume: () => { + if (scratchpad.nullResume) { + delete scratchpad.nullResume; + pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__"), 1); + return nullResume; } - }, milliseconds); - }); - const cancelablePromise = wrappedPromise.finally(() => { - cancelablePromise.clear(); - if (abortHandler && signal) { - signal.removeEventListener("abort", abortHandler); } - }); - cancelablePromise.clear = () => { - customTimers.clearTimeout.call(undefined, timer); - timer = undefined; }; - return cancelablePromise; + return scratchpad; } -var TimeoutError, getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError"); -var init_p_timeout = __esm(() => { - TimeoutError = class TimeoutError extends Error { - name = "TimeoutError"; - constructor(message, options) { - super(message, options); - Error.captureStackTrace?.(this, TimeoutError); - } - }; +var increment = (current) => { + return current !== undefined ? current + 1 : 1; +}, IGNORE; +var init_algo = __esm(() => { + init_constants3(); + init_errors7(); + init_base15(); + init_hash3(); + init_io(); + init_types7(); + init_utils9(); + init_call(); + init_dist3(); + init_runnables(); + IGNORE = new Set([ + NO_WRITES, + PUSH, + RESUME, + INTERRUPT, + RETURN, + ERROR2 + ]); }); -// ../../node_modules/.pnpm/p-queue@9.2.0/node_modules/p-queue/dist/lower-bound.js -function lowerBound(array2, value, comparator) { - let first = 0; - let count = array2.length; - while (count > 0) { - const step = Math.trunc(count / 2); - let it = first + step; - if (comparator(array2[it], value) <= 0) { - first = ++it; - count -= step + 1; - } else { - count = step; - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/debug.js +function* mapDebugTasks(tasks) { + for (const { id, name, input, config: config3, triggers, writes } of tasks) { + if (config3?.tags?.includes("langsmith:hidden")) + continue; + yield { + id, + name, + input, + triggers, + interrupts: writes.filter(([writeId, n3]) => { + return writeId === id && n3 === "__interrupt__"; + }).map(([, v]) => { + return v; + }) + }; } - return first; } - -// ../../node_modules/.pnpm/p-queue@9.2.0/node_modules/p-queue/dist/priority-queue.js -class PriorityQueue { - #queue = []; - #head = 0; - enqueue(run2, options) { - const { priority = 0, id } = options ?? {}; - const { size } = this; - const element = { - priority, +function isMultipleChannelWrite(value) { + if (typeof value !== "object" || value === null) + return false; + return "$writes" in value && Array.isArray(value.$writes); +} +function mapTaskResultWrites(writes) { + const result = {}; + for (const [channel, value] of writes) { + const strChannel = String(channel); + if (strChannel in result) { + const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; + channelWrites.push(value); + result[strChannel] = { $writes: channelWrites }; + } else + result[strChannel] = value; + } + return result; +} +function* mapDebugTaskResults(tasks, streamChannels) { + for (const [{ id, name, config: config3 }, writes] of tasks) { + if (config3?.tags?.includes("langsmith:hidden")) + continue; + yield { id, - run: run2 + name, + result: mapTaskResultWrites(writes.filter(([channel]) => { + return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; + })), + interrupts: writes.filter((w) => w[0] === INTERRUPT).map((w) => w[1]) }; - if (size === 0) { - this.#queue.length = 0; - this.#head = 0; - this.#queue.push(element); - return; - } - if (this.#queue.at(-1).priority >= priority) { - this.#queue.push(element); - return; - } - this.#compact(); - const index2 = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority); - this.#queue.splice(index2, 0, element); } - setPriority(id, priority) { - const index2 = this.#queue.findIndex((element, index3) => index3 >= this.#head && element.id === id); - if (index2 === -1) { - throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`); - } - const [item] = this.#queue.splice(index2, 1); - this.enqueue(item.run, { priority, id }); +} +function* mapDebugCheckpoint(config3, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { + function formatConfig(config4) { + const pyConfig = {}; + if (config4.callbacks != null) + pyConfig.callbacks = config4.callbacks; + if (config4.configurable != null) + pyConfig.configurable = config4.configurable; + if (config4.maxConcurrency != null) + pyConfig.max_concurrency = config4.maxConcurrency; + if (config4.metadata != null) + pyConfig.metadata = config4.metadata; + if (config4.recursionLimit != null) + pyConfig.recursion_limit = config4.recursionLimit; + if (config4.runId != null) + pyConfig.run_id = config4.runId; + if (config4.runName != null) + pyConfig.run_name = config4.runName; + if (config4.tags != null) + pyConfig.tags = config4.tags; + return pyConfig; } - remove(idOrRun) { - const index2 = this.#queue.findIndex((element, index3) => { - if (index3 < this.#head) { - return false; - } - if (typeof idOrRun === "string") { - return element.id === idOrRun; + const parentNs = config3.configurable?.checkpoint_ns; + const taskStates = {}; + for (const task of tasks) { + if (!((task.subgraphs?.length) ? task.subgraphs : [task.proc]).find(findSubgraphPregel)) + continue; + let taskNs = `${task.name}:${task.id}`; + if (parentNs) + taskNs = `${parentNs}|${taskNs}`; + taskStates[task.id] = { configurable: { + thread_id: config3.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + } + yield { + config: formatConfig(config3), + values: readChannels(channels, streamChannels), + metadata, + next: tasks.map((task) => task.name), + tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), + parentConfig: parentConfig ? formatConfig(parentConfig) : undefined + }; +} +function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { + return tasks.map((task) => { + const error90 = pendingWrites.find(([id, n3]) => id === task.id && n3 === "__error__")?.[2]; + const interrupts = pendingWrites.filter(([id, n3]) => id === task.id && n3 === "__interrupt__").map(([, , v]) => v); + const result = (() => { + if (error90 || interrupts.length || !pendingWrites.length) + return; + const idx = pendingWrites.findIndex(([tid, n3]) => tid === task.id && n3 === "__return__"); + if (idx >= 0) + return pendingWrites[idx][2]; + if (typeof outputKeys === "string") + return pendingWrites.find(([tid, n3]) => tid === task.id && n3 === outputKeys)?.[2]; + if (Array.isArray(outputKeys)) { + const results = pendingWrites.filter(([tid, n3]) => tid === task.id && outputKeys.includes(n3)).map(([, n3, v]) => [n3, v]); + if (!results.length) + return; + return mapTaskResultWrites(results); } - return element.run === idOrRun; - }); - if (index2 !== -1) { - this.#queue.splice(index2, 1); + })(); + if (error90) + return { + id: task.id, + name: task.name, + path: task.path, + error: error90, + interrupts, + result + }; + const taskState = states?.[task.id]; + return { + id: task.id, + name: task.name, + path: task.path, + interrupts, + ...taskState !== undefined ? { state: taskState } : {}, + result + }; + }); +} +function printStepCheckpoint(step, channels, whitelist) { + console.log([ + `${wrap2(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, + `\x1B[1m State at the end of step ${step}:\x1B[0m +`, + JSON.stringify(readChannels(channels, whitelist), null, 2) + ].join("")); +} +function printStepTasks(step, nextTasks) { + const nTasks = nextTasks.length; + console.log([ + `${wrap2(COLORS_MAP.blue, `[${step}:tasks]`)}`, + `\x1B[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1B[0m +`, + nextTasks.map((task) => `- ${wrap2(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join(` +`) + ].join("")); +} +function printStepWrites(step, writes, whitelist) { + const byChannel = {}; + for (const [channel, value] of writes) + if (whitelist.includes(channel)) { + if (!byChannel[channel]) + byChannel[channel] = []; + byChannel[channel].push(value); } - } - dequeue() { - if (this.#head === this.#queue.length) { - return; + console.log([ + `${wrap2(COLORS_MAP.blue, `[${step}:writes]`)}`, + `\x1B[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1B[0m +`, + Object.entries(byChannel).map(([name, vals]) => `- ${wrap2(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join(` +`) + ].join("")); +} +var COLORS_MAP, wrap2 = (color2, text) => `${color2.start}${text}${color2.end}`; +var init_debug = __esm(() => { + init_constants3(); + init_io(); + init_subgraph(); + COLORS_MAP = { + blue: { + start: "\x1B[34m", + end: "\x1B[0m" + }, + green: { + start: "\x1B[32m", + end: "\x1B[0m" + }, + yellow: { + start: "\x1B[33;1m", + end: "\x1B[0m" } - const item = this.#queue[this.#head]; - this.#head++; - if (this.#head === this.#queue.length) { - this.#queue.length = 0; - this.#head = 0; - } else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) { - this.#compact(); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/stream.js +function _stringifyAsDict(obj) { + return JSON.stringify(obj, function(key, value) { + const rawValue2 = this[key]; + if (rawValue2 != null && typeof rawValue2 === "object" && "toDict" in rawValue2 && typeof rawValue2.toDict === "function") { + const { type, data } = rawValue2.toDict(); + return { + ...data, + type + }; } - return item?.run; + return value; + }); +} +function _serializeError(error90) { + if (error90 instanceof Error) + return { + error: error90.name, + message: error90.message + }; + return { + error: "Error", + message: JSON.stringify(error90) + }; +} +function _isRunnableConfig(config3) { + if (typeof config3 !== "object" || config3 == null) + return false; + return "configurable" in config3 && typeof config3.configurable === "object" && config3.configurable != null; +} +function _extractCheckpointFromConfig(config3) { + if (!_isRunnableConfig(config3) || !config3.configurable.thread_id) + return null; + return { + thread_id: config3.configurable.thread_id, + checkpoint_ns: config3.configurable.checkpoint_ns || "", + checkpoint_id: config3.configurable.checkpoint_id || null, + checkpoint_map: config3.configurable.checkpoint_map || null + }; +} +function _serializeConfig(config3) { + if (_isRunnableConfig(config3)) { + const configurable = Object.fromEntries(Object.entries(config3.configurable).filter(([key]) => !key.startsWith("__"))); + const newConfig = { + ...config3, + configurable + }; + delete newConfig.callbacks; + return newConfig; } - filter(options) { - const result = []; - for (let index2 = this.#head;index2 < this.#queue.length; index2++) { - const element = this.#queue[index2]; - if (element.priority === options.priority) { - result.push(element.run); + return config3; +} +function _serializeCheckpoint(payload) { + const result = { + ...payload, + checkpoint: _extractCheckpointFromConfig(payload.config), + parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), + config: _serializeConfig(payload.config), + parent_config: _serializeConfig(payload.parentConfig), + tasks: payload.tasks.map((task) => { + if (_isRunnableConfig(task.state)) { + const checkpoint = _extractCheckpointFromConfig(task.state); + if (checkpoint != null) { + const cloneTask = { + ...task, + checkpoint + }; + delete cloneTask.state; + return cloneTask; + } } - } - return result; - } - get size() { - return this.#queue.length - this.#head; - } - #compact() { - if (this.#head === 0) { - return; - } - this.#queue.splice(0, this.#head); - this.#head = 0; - } + return task; + }) + }; + delete result.parentConfig; + return result; } -var compactionThreshold = 100; -var init_priority_queue = () => {}; +function toEventStream(stream2) { + const encoder2 = new TextEncoder; + return new ReadableStream({ async start(controller) { + const enqueueChunk = (sse) => { + controller.enqueue(encoder2.encode(`event: ${sse.event} +data: ${_stringifyAsDict(sse.data)} -// ../../node_modules/.pnpm/p-queue@9.2.0/node_modules/p-queue/dist/index.js -var PQueue2; -var init_dist6 = __esm(() => { - init_eventemitter3(); - init_p_timeout(); - init_priority_queue(); - PQueue2 = class PQueue2 extends import__3.default { - #carryoverIntervalCount; - #isIntervalIgnored; - #intervalCount = 0; - #intervalCap; - #rateLimitedInInterval = false; - #rateLimitFlushScheduled = false; - #interval; - #intervalEnd = 0; - #lastExecutionTime = 0; - #intervalId; - #timeoutId; - #strict; - #strictTicks = []; - #strictTicksStartIndex = 0; - #queue; - #queueClass; - #pending = 0; - #concurrency; - #isPaused; - #idAssigner = 1n; - #runningTasks = new Map; - #queueAbortListenerCleanupFunctions = new Set; - timeout; - constructor(options) { - super(); - options = { - carryoverIntervalCount: false, - intervalCap: Number.POSITIVE_INFINITY, - interval: 0, - concurrency: Number.POSITIVE_INFINITY, - autoStart: true, - queueClass: PriorityQueue, - strict: false, - ...options - }; - if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`); - } - if (options.strict && options.interval === 0) { - throw new TypeError("The `strict` option requires a non-zero `interval`"); - } - if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) { - throw new TypeError("The `strict` option requires a finite `intervalCap`"); - } - this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false; - this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0; - this.#intervalCap = options.intervalCap; - this.#interval = options.interval; - this.#strict = options.strict; - this.#queue = new options.queueClass; - this.#queueClass = options.queueClass; - this.concurrency = options.concurrency; - if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) { - throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${options.timeout}\` (${typeof options.timeout})`); - } - this.timeout = options.timeout; - this.#isPaused = options.autoStart === false; - this.#setupRateLimitTracking(); - } - #cleanupStrictTicks(now) { - while (this.#strictTicksStartIndex < this.#strictTicks.length) { - const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; - if (oldestTick !== undefined && now - oldestTick >= this.#interval) { - this.#strictTicksStartIndex++; - } else { - break; +`)); + }; + try { + for await (const payload of stream2) { + const [ns3, mode, chunk] = payload; + let data = chunk; + if (mode === "debug") { + const debugChunk = chunk; + if (debugChunk.type === "checkpoint") + data = { + ...debugChunk, + payload: _serializeCheckpoint(debugChunk.payload) + }; } + if (mode === "checkpoints") + data = _serializeCheckpoint(chunk); + enqueueChunk({ + event: ns3?.length ? `${mode}|${ns3.join("|")}` : mode, + data + }); } - const shouldCompact = this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2 || this.#strictTicksStartIndex === this.#strictTicks.length; - if (shouldCompact) { - this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex); - this.#strictTicksStartIndex = 0; - } - } - #consumeIntervalSlot(now) { - if (this.#strict) { - this.#strictTicks.push(now); - } else { - this.#intervalCount++; - } + } catch (error90) { + enqueueChunk({ + event: "error", + data: _serializeError(error90) + }); } - #rollbackIntervalSlot() { - if (this.#strict) { - if (this.#strictTicks.length > this.#strictTicksStartIndex) { - this.#strictTicks.pop(); + controller.close(); + } }); +} +var IterableReadableStreamWithAbortSignal, IterableReadableWritableStream, StreamToolsHandler; +var init_stream5 = __esm(() => { + init_constants3(); + init_stream(); + init_base2(); + IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { + _abortController; + _innerReader; + constructor(readableStream, abortController) { + const reader = readableStream.getReader(); + const ac = abortController ?? new AbortController; + super({ start(controller) { + return pump2(); + function pump2() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump2(); + }); } - } else if (this.#intervalCount > 0) { - this.#intervalCount--; - } - } - #getActiveTicksCount() { - return this.#strictTicks.length - this.#strictTicksStartIndex; + } }); + this._abortController = ac; + this._innerReader = reader; } - get #doesIntervalAllowAnother() { - if (this.#isIntervalIgnored) { - return true; - } - if (this.#strict) { - return this.#getActiveTicksCount() < this.#intervalCap; - } - return this.#intervalCount < this.#intervalCap; + async cancel(reason) { + this._abortController.abort(reason); + this._innerReader.releaseLock(); } - get #doesConcurrentAllowAnother() { - return this.#pending < this.#concurrency; + get signal() { + return this._abortController.signal; } - #next() { - this.#pending--; - if (this.#pending === 0) { - this.emit("pendingZero"); - } - this.#tryToStartAnother(); - this.emit("next"); + }; + IterableReadableWritableStream = class extends IterableReadableStream { + modes; + controller; + passthroughFn; + _closed = false; + get closed() { + return this._closed; } - #onResumeInterval() { - this.#timeoutId = undefined; - this.#onInterval(); - this.#initializeIntervalIfNeeded(); + constructor(params) { + let streamControllerPromiseResolver; + const streamControllerPromise = new Promise((resolve2) => { + streamControllerPromiseResolver = resolve2; + }); + super({ start: (controller) => { + streamControllerPromiseResolver(controller); + } }); + streamControllerPromise.then((controller) => { + this.controller = controller; + }); + this.passthroughFn = params.passthroughFn; + this.modes = params.modes; } - #isIntervalPausedAt(now) { - if (this.#strict) { - this.#cleanupStrictTicks(now); - const activeTicksCount = this.#getActiveTicksCount(); - if (activeTicksCount >= this.#intervalCap) { - const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; - const delay = this.#interval - (now - oldestTick); - this.#createIntervalTimeout(delay); - return true; - } - return false; - } - if (this.#intervalId === undefined) { - const delay = this.#intervalEnd - now; - if (delay < 0) { - if (this.#lastExecutionTime > 0) { - const timeSinceLastExecution = now - this.#lastExecutionTime; - if (timeSinceLastExecution < this.#interval) { - this.#createIntervalTimeout(this.#interval - timeSinceLastExecution); - return true; - } - } - this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; - } else { - this.#createIntervalTimeout(delay); - return true; - } - } - return false; + push(chunk) { + this.passthroughFn?.(chunk); + this.controller.enqueue(chunk); } - #createIntervalTimeout(delay) { - if (this.#timeoutId !== undefined) { - return; + close() { + try { + this.controller.close(); + } catch {} finally { + this._closed = true; } - this.#timeoutId = setTimeout(() => { - this.#onResumeInterval(); - }, delay); } - #clearIntervalTimer() { - if (this.#intervalId) { - clearInterval(this.#intervalId); - this.#intervalId = undefined; - } + error(e) { + this.controller.error(e); } - #clearTimeoutTimer() { - if (this.#timeoutId) { - clearTimeout(this.#timeoutId); - this.#timeoutId = undefined; - } + }; + StreamToolsHandler = class extends BaseCallbackHandler { + name = "StreamToolsHandler"; + streamFn; + runs = {}; + constructor(streamFn) { + super(); + this.streamFn = streamFn; } - #tryToStartAnother() { - if (this.#queue.size === 0) { - this.#clearIntervalTimer(); - this.emit("empty"); - if (this.#pending === 0) { - this.#clearTimeoutTimer(); - if (this.#strict && this.#strictTicksStartIndex > 0) { - const now = Date.now(); - this.#cleanupStrictTicks(now); - } - this.emit("idle"); - } - return false; - } - let taskStarted = false; - if (!this.#isPaused) { - const now = Date.now(); - const canInitializeInterval = !this.#isIntervalPausedAt(now); - if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) { - const job = this.#queue.dequeue(); - if (!this.#isIntervalIgnored) { - this.#consumeIntervalSlot(now); - this.#scheduleRateLimitUpdate(); - } - this.emit("active"); - job(); - if (canInitializeInterval) { - this.#initializeIntervalIfNeeded(); - } - taskStarted = true; + handleToolStart(_tool, input, runId, _parentRunId, tags, metadata, runName, toolCallId) { + if (!metadata || tags && tags.includes("langsmith:hidden")) + return; + const ns3 = metadata.langgraph_checkpoint_ns?.split("|") ?? []; + const info = { + ns: ns3, + toolCallId, + toolName: runName ?? "unknown", + input + }; + this.runs[runId] = info; + this.streamFn([ + ns3, + "tools", + { + event: "on_tool_start", + toolCallId: info.toolCallId, + name: info.toolName, + input } - } - return taskStarted; + ]); } - #initializeIntervalIfNeeded() { - if (this.#isIntervalIgnored || this.#intervalId !== undefined) { - return; - } - if (this.#strict) { + handleToolEvent(chunk, runId) { + const info = this.runs[runId]; + if (!info) return; - } - this.#intervalId = setInterval(() => { - this.#onInterval(); - }, this.#interval); - this.#intervalEnd = Date.now() + this.#interval; - } - #onInterval() { - if (!this.#strict) { - if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) { - this.#clearIntervalTimer(); + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_event", + toolCallId: info.toolCallId, + name: info.toolName, + data: chunk } - this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; - } - this.#processQueue(); - this.#scheduleRateLimitUpdate(); - } - #processQueue() { - while (this.#tryToStartAnother()) {} - } - get concurrency() { - return this.#concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this.#concurrency = newConcurrency; - this.#processQueue(); - } - setPriority(id, priority) { - if (typeof priority !== "number" || !Number.isFinite(priority)) { - throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`); - } - this.#queue.setPriority(id, priority); + ]); } - async add(function_, options = {}) { - options = { - timeout: this.timeout, - ...options, - id: options.id ?? (this.#idAssigner++).toString() - }; - return new Promise((resolve2, reject) => { - const taskSymbol = Symbol(`task-${options.id}`); - let cleanupQueueAbortHandler = () => { - return; - }; - const run2 = async () => { - cleanupQueueAbortHandler(); - this.#pending++; - this.#runningTasks.set(taskSymbol, { - id: options.id, - priority: options.priority ?? 0, - startTime: Date.now(), - timeout: options.timeout - }); - let eventListener; - try { - try { - options.signal?.throwIfAborted(); - } catch (error51) { - this.#rollbackIntervalConsumption(); - this.#runningTasks.delete(taskSymbol); - throw error51; - } - this.#lastExecutionTime = Date.now(); - let operation = function_({ signal: options.signal }); - if (options.timeout) { - operation = pTimeout(Promise.resolve(operation), { - milliseconds: options.timeout, - message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)` - }); - } - if (options.signal) { - const { signal } = options; - operation = Promise.race([operation, new Promise((_resolve, reject2) => { - eventListener = () => { - reject2(signal.reason); - }; - signal.addEventListener("abort", eventListener, { once: true }); - })]); - } - const result = await operation; - resolve2(result); - this.emit("completed", result); - } catch (error51) { - reject(error51); - this.emit("error", error51); - } finally { - if (eventListener) { - options.signal?.removeEventListener("abort", eventListener); - } - this.#runningTasks.delete(taskSymbol); - queueMicrotask(() => { - this.#next(); - }); - } - }; - this.#queue.enqueue(run2, options); - const removeQueuedTask = () => { - if (this.#queue instanceof PriorityQueue) { - this.#queue.remove(run2); - return; - } - this.#queue.remove?.(options.id); - }; - if (options.signal) { - const { signal } = options; - const queueAbortHandler = () => { - cleanupQueueAbortHandler(); - removeQueuedTask(); - reject(signal.reason); - this.#tryToStartAnother(); - this.emit("next"); - }; - cleanupQueueAbortHandler = () => { - signal.removeEventListener("abort", queueAbortHandler); - this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler); - }; - if (signal.aborted) { - queueAbortHandler(); - return; - } - signal.addEventListener("abort", queueAbortHandler, { once: true }); - this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler); + handleToolEnd(output, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) + return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_end", + toolCallId: info.toolCallId, + name: info.toolName, + output } - this.emit("add"); - this.#tryToStartAnother(); - }); - } - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); + ]); } - start() { - if (!this.#isPaused) { - return this; - } - this.#isPaused = false; - this.#processQueue(); - return this; + handleToolError(err, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) + return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_error", + toolCallId: info.toolCallId, + name: info.toolName, + error: err + } + ]); } - pause() { - this.#isPaused = true; + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/loop.js +function createDuplexStream(...streams) { + return new IterableReadableWritableStream({ + passthroughFn: (value) => { + for (const stream2 of streams) + if (stream2.modes.has(value[1])) + stream2.push(value); + }, + modes: new Set(streams.flatMap((s) => Array.from(s.modes))) + }); +} +var INPUT_DONE, INPUT_RESUMING, DEFAULT_LOOP_LIMIT = 25, AsyncBatchedCache, PregelLoop = class PregelLoop2 { + input; + output; + config; + checkpointer; + checkpointerGetNextVersion; + channels; + checkpoint; + checkpointIdSaved; + checkpointConfig; + checkpointMetadata; + checkpointNamespace; + checkpointPendingWrites = []; + checkpointPreviousVersions; + step; + stop; + durability; + outputKeys; + streamKeys; + nodes; + skipDoneTasks; + prevCheckpointConfig; + updatedChannels; + status = "pending"; + tasks = {}; + stream; + checkpointerPromises = /* @__PURE__ */ new Set; + isNested; + _checkpointerChainedPromise = Promise.resolve(); + _trackCheckpointerPromise(promise3) { + const tracked = promise3.then((value) => { + this.checkpointerPromises.delete(tracked); + return value; + }, (error90) => { + throw error90; + }); + this.checkpointerPromises.add(tracked); + } + store; + cache; + manager; + interruptAfter; + interruptBefore; + toInterrupt = []; + debug = false; + triggerToNodes; + get isResuming() { + let hasChannelVersions = false; + if ("__start__" in this.checkpoint.channel_versions) + hasChannelVersions = true; + else + for (const chan in this.checkpoint.channel_versions) + if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { + hasChannelVersions = true; + break; + } + const configIsResuming = this.config.configurable?.["__pregel_resuming"] !== undefined && this.config.configurable?.["__pregel_resuming"]; + const inputIsNullOrUndefined = this.input === null || this.input === undefined; + const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; + const inputIsResuming = this.input === INPUT_RESUMING; + const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== undefined && this.checkpointMetadata?.run_id !== undefined && this.config.metadata.run_id === this.checkpointMetadata?.run_id; + return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); + } + constructor(params) { + this.input = params.input; + this.checkpointer = params.checkpointer; + if (this.checkpointer !== undefined) + this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); + else + this.checkpointerGetNextVersion = increment; + this.checkpoint = params.checkpoint; + this.checkpointMetadata = params.checkpointMetadata; + this.checkpointPreviousVersions = params.checkpointPreviousVersions; + this.channels = params.channels; + this.checkpointPendingWrites = params.checkpointPendingWrites; + this.step = params.step; + this.stop = params.stop; + this.config = params.config; + this.checkpointConfig = params.checkpointConfig; + this.isNested = params.isNested; + this.manager = params.manager; + this.outputKeys = params.outputKeys; + this.streamKeys = params.streamKeys; + this.nodes = params.nodes; + this.skipDoneTasks = params.skipDoneTasks; + this.store = params.store; + this.cache = params.cache ? new AsyncBatchedCache(params.cache) : undefined; + this.stream = params.stream; + this.checkpointNamespace = params.checkpointNamespace; + this.prevCheckpointConfig = params.prevCheckpointConfig; + this.interruptAfter = params.interruptAfter; + this.interruptBefore = params.interruptBefore; + this.durability = params.durability; + this.debug = params.debug; + this.triggerToNodes = params.triggerToNodes; + } + static async initialize(params) { + let { config: config3, stream: stream2 } = params; + if (stream2 !== undefined && config3.configurable?.["__pregel_stream"] !== undefined) + stream2 = createDuplexStream(stream2, config3.configurable[CONFIG_KEY_STREAM]); + const skipDoneTasks = config3.configurable ? !("checkpoint_id" in config3.configurable) : true; + const scratchpad = config3.configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (config3.configurable && scratchpad) { + if (scratchpad.subgraphCounter > 0) + config3 = patchConfigurable2(config3, { [CONFIG_KEY_CHECKPOINT_NS]: [config3.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join("|") }); + scratchpad.subgraphCounter += 1; } - clear() { - for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) { - cleanupQueueAbortHandler(); + const isNested = CONFIG_KEY_READ in (config3.configurable ?? {}); + if (!isNested && config3.configurable?.checkpoint_ns !== undefined && config3.configurable?.checkpoint_ns !== "") + config3 = patchConfigurable2(config3, { + checkpoint_ns: "", + checkpoint_id: undefined + }); + let checkpointConfig = config3; + if (config3.configurable?.["checkpoint_map"] !== undefined && config3.configurable?.["checkpoint_map"]?.[config3.configurable?.checkpoint_ns]) + checkpointConfig = patchConfigurable2(config3, { checkpoint_id: config3.configurable[CONFIG_KEY_CHECKPOINT_MAP][config3.configurable?.checkpoint_ns] }); + const checkpointNamespace = config3.configurable?.checkpoint_ns?.split("|") ?? []; + const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { + config: config3, + checkpoint: emptyCheckpoint(), + metadata: { + source: "input", + step: -2, + parents: {} + }, + pendingWrites: [] + }; + checkpointConfig = { + ...config3, + ...saved.config, + configurable: { + checkpoint_ns: "", + ...config3.configurable, + ...saved.config.configurable } - this.#queue = new this.#queueClass; - this.#clearIntervalTimer(); - this.#updateRateLimitState(); - this.emit("empty"); - if (this.#pending === 0) { - this.#clearTimeoutTimer(); - this.emit("idle"); + }; + const prevCheckpointConfig = saved.parentConfig; + const checkpoint = copyCheckpoint(saved.checkpoint); + const checkpointMetadata = { ...saved.metadata }; + const checkpointPendingWrites = saved.pendingWrites ?? []; + const channels = emptyChannels(params.channelSpecs, checkpoint); + const step = (checkpointMetadata.step ?? 0) + 1; + const stop = step + (config3.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; + const checkpointPreviousVersions = { ...checkpoint.channel_versions }; + const store = params.store ? new AsyncBatchedStore(params.store) : undefined; + if (store) + await store.start(); + return new PregelLoop2({ + input: params.input, + config: config3, + checkpointer: params.checkpointer, + checkpoint, + checkpointMetadata, + checkpointConfig, + prevCheckpointConfig, + checkpointNamespace, + channels, + isNested, + manager: params.manager, + skipDoneTasks, + step, + stop, + checkpointPreviousVersions, + checkpointPendingWrites, + outputKeys: params.outputKeys ?? [], + streamKeys: params.streamKeys ?? [], + nodes: params.nodes, + stream: stream2, + store, + cache: params.cache, + interruptAfter: params.interruptAfter, + interruptBefore: params.interruptBefore, + durability: params.durability, + debug: params.debug, + triggerToNodes: params.triggerToNodes + }); + } + _checkpointerPutAfterPrevious(input) { + this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { + return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); + }); + this._trackCheckpointerPromise(this._checkpointerChainedPromise); + } + putWrites(taskId, writes) { + let writesCopy = writes; + if (writesCopy.length === 0) + return; + if (writesCopy.every(([key]) => (key in WRITES_IDX_MAP))) + writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); + let hasUntrackedChannels = false; + for (const key in this.channels) + if (Object.prototype.hasOwnProperty.call(this.channels, key)) { + if (this.channels[key].lc_graph_name === "UntrackedValue") { + hasUntrackedChannels = true; + break; + } } - this.emit("next"); - } - async onEmpty() { - if (this.#queue.size === 0) { + let writesToSave = writesCopy; + if (hasUntrackedChannels) + writesToSave = writesCopy.filter(([c]) => { + const channel = this.channels[c]; + return !channel || channel.lc_graph_name !== "UntrackedValue"; + }).map(([c, v]) => { + if (c === "__pregel_tasks" && _isSend(v)) + return [c, sanitizeUntrackedValuesInSend(v, this.channels)]; + return [c, v]; + }); + this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); + for (const [c, v] of writesToSave) + this.checkpointPendingWrites.push([ + taskId, + c, + v + ]); + const config3 = patchConfigurable2(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + if (this.durability !== "exit" && this.checkpointer != null) + this._trackCheckpointerPromise(this.checkpointer.putWrites(config3, writesToSave, taskId)); + if (this.tasks) + this._outputWrites(taskId, writesCopy); + if (!writes.length || !this.cache || !this.tasks) + return; + const task = this.tasks[taskId]; + if (task == null || task.cache_key == null) + return; + if (writes[0][0] === "__error__" || writes[0][0] === "__interrupt__") + return; + this.cache.set([{ + key: [task.cache_key.ns, task.cache_key.key], + value: task.writes, + ttl: task.cache_key.ttl + }]); + } + _outputWrites(taskId, writes, cached3 = false) { + const task = this.tasks[taskId]; + if (task !== undefined) { + if (task.config !== undefined && (task.config.tags ?? []).includes("langsmith:hidden")) return; + if (writes.length > 0) { + if (writes[0][0] === "__interrupt__") { + if (task.path?.[0] === "__pregel_push" && task.path?.[task.path.length - 1] === true) + return; + const interruptWrites = writes.filter((w) => w[0] === INTERRUPT).flatMap((w) => w[1]); + this._emit([["updates", { [INTERRUPT]: interruptWrites }], ["values", { [INTERRUPT]: interruptWrites }]]); + } else if (writes[0][0] !== "__error__") + this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached3), "updates"))); } - await this.#onEvent("empty"); + if (!cached3) + this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); } - async onSizeLessThan(limit) { - if (this.#queue.size < limit) { - return; + } + async _matchCachedWrites() { + if (!this.cache) + return []; + const matched = []; + const serializeKey = ([ns3, key]) => { + return `ns:${ns3.join(",")}|key:${key}`; + }; + const keys = []; + const keyMap = {}; + for (const task of Object.values(this.tasks)) + if (task.cache_key != null && !task.writes.length) { + keys.push([task.cache_key.ns, task.cache_key.key]); + keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; } - await this.#onEvent("next", () => this.#queue.size < limit); - } - async onIdle() { - if (this.#pending === 0 && this.#queue.size === 0) { - return; + if (keys.length === 0) + return []; + const cache2 = await this.cache.get(keys); + for (const { key, value } of cache2) { + const task = keyMap[serializeKey(key)]; + if (task != null) { + task.writes.push(...value); + matched.push({ + task, + result: value + }); } - await this.#onEvent("idle"); } - async onPendingZero() { - if (this.#pending === 0) { - return; + return matched; + } + async tick(params) { + if (this.store && !this.store.isRunning) + await this.store?.start(); + const { inputKeys = [] } = params; + if (this.status !== "pending") + throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); + if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) + await this._first(inputKeys); + else if (this.toInterrupt.length > 0) { + this.status = "interrupt_before"; + throw new GraphInterrupt; + } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { + const writes = Object.values(this.tasks).flatMap((t) => t.writes); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); + this.checkpointPendingWrites = []; + await this._putCheckpoint({ source: "loop" }); + this._emitValuesWithCheckpointMeta(valuesOutput); + if (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { + this.status = "interrupt_after"; + throw new GraphInterrupt; } - await this.#onEvent("pendingZero"); + if (this.config.configurable?.["__pregel_resuming"] !== undefined) + delete this.config.configurable?.[CONFIG_KEY_RESUMING]; + } else + return false; + if (this.step > this.stop) { + this.status = "out_of_steps"; + return false; } - async onRateLimit() { - if (this.isRateLimited) { - return; - } - await this.#onEvent("rateLimit"); + this.tasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { + step: this.step, + checkpointer: this.checkpointer, + isResuming: this.isResuming, + manager: this.manager, + store: this.store, + stream: this.stream, + triggerToNodes: this.triggerToNodes, + updatedChannels: this.updatedChannels + }); + if (this.checkpointer) + this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); + if (Object.values(this.tasks).length === 0) { + this.status = "done"; + return false; } - async onRateLimitCleared() { - if (!this.isRateLimited) { - return; + if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__interrupt__" || k === "__resume__") + continue; + const task = Object.values(this.tasks).find((t) => t.id === tid); + if (task) + task.writes.push([k, v]); } - await this.#onEvent("rateLimitCleared"); - } - onError() { - return new Promise((_resolve, reject) => { - const handleError = (error51) => { - this.off("error", handleError); - reject(error51); - }; - this.on("error", handleError); - }); - } - async#onEvent(event, filter) { - return new Promise((resolve2) => { - const listener = () => { - if (filter && !filter()) { - return; - } - this.off(event, listener); - resolve2(); - }; - this.on(event, listener); - }); + for (const task of Object.values(this.tasks)) + if (task.writes.length > 0) + this._outputWrites(task.id, task.writes, true); } - get size() { - return this.#queue.size; + if (Object.values(this.tasks).every((task) => task.writes.length > 0)) + return this.tick({ inputKeys }); + if (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { + this.status = "interrupt_before"; + throw new GraphInterrupt; } - sizeBy(options) { - return this.#queue.filter(options).length; + const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), "tasks")); + this._emit(debugOutput); + return true; + } + async finishAndHandleError(error90) { + if (this.durability === "exit" && (!this.isNested || typeof error90 !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(":")))) { + this._putCheckpoint(this.checkpointMetadata); + this._flushPendingWrites(); } - get pending() { - return this.#pending; + const suppress = this._suppressInterrupt(error90); + if (suppress || error90 === undefined) + this.output = readChannels(this.channels, this.outputKeys); + if (suppress) { + if (this.tasks !== undefined && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + this._emitValuesWithCheckpointMeta(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); + } + if (isGraphInterrupt(error90) && !error90.interrupts.length) + this._emit([["updates", { [INTERRUPT]: [] }], ["values", { [INTERRUPT]: [] }]]); } - get isPaused() { - return this.#isPaused; + return suppress; + } + async acceptPush(task, writeIdx, call2) { + if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { + this.toInterrupt.push(task); + return; } - #setupRateLimitTracking() { - if (this.#isIntervalIgnored) { - return; - } - this.on("add", () => { - if (this.#queue.size > 0) { - this.#scheduleRateLimitUpdate(); - } - }); - this.on("next", () => { - this.#scheduleRateLimitUpdate(); - }); + const pushed = _prepareSingleTask([ + PUSH, + task.path ?? [], + writeIdx, + task.id, + call2 + ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { + step: this.step, + checkpointer: this.checkpointer, + manager: this.manager, + store: this.store, + stream: this.stream + }); + if (!pushed) + return; + if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { + this.toInterrupt.push(pushed); + return; } - #scheduleRateLimitUpdate() { - if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) { - return; + this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); + if (this.debug) + printStepTasks(this.step, [pushed]); + this.tasks[pushed.id] = pushed; + if (this.skipDoneTasks) + this._matchWrites({ [pushed.id]: pushed }); + const tasks = await this._matchCachedWrites(); + for (const { task: task2 } of tasks) + this._outputWrites(task2.id, task2.writes, true); + return pushed; + } + _suppressInterrupt(e) { + return isGraphInterrupt(e) && !this.isNested; + } + async _first(inputKeys) { + const { configurable } = this.config; + const scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (scratchpad && scratchpad.nullResume !== undefined) + this.putWrites(NULL_TASK_ID, [[RESUME, scratchpad.nullResume]]); + if (isCommand(this.input)) { + const hasResume = this.input.resume != null; + if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { + this.config.configurable ??= {}; + this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; } - this.#rateLimitFlushScheduled = true; - queueMicrotask(() => { - this.#rateLimitFlushScheduled = false; - this.#updateRateLimitState(); - }); - } - #rollbackIntervalConsumption() { - if (this.#isIntervalIgnored) { - return; + if (hasResume && this.checkpointer == null) + throw new Error("Cannot use Command(resume=...) without checkpointer"); + const writes = {}; + for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { + writes[tid] ??= []; + writes[tid].push([key, value]); } - this.#rollbackIntervalSlot(); - this.#scheduleRateLimitUpdate(); + if (Object.keys(writes).length === 0) + throw new EmptyInputError("Received empty Command input"); + for (const [tid, ws] of Object.entries(writes)) + this.putWrites(tid, ws); } - #updateRateLimitState() { - const previous = this.#rateLimitedInInterval; - if (this.#isIntervalIgnored || this.#queue.size === 0) { - if (previous) { - this.#rateLimitedInInterval = false; - this.emit("rateLimitCleared"); + const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites(this.checkpoint, this.channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], this.checkpointerGetNextVersion, this.triggerToNodes); + const isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0; + if (this.isResuming || isCommandUpdateOrGoto) { + for (const channelName in this.channels) { + if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) + continue; + if (this.checkpoint.channel_versions[channelName] !== undefined) { + const version6 = this.checkpoint.channel_versions[channelName]; + this.checkpoint.versions_seen[INTERRUPT] = { + ...this.checkpoint.versions_seen[INTERRUPT], + [channelName]: version6 + }; } - return; - } - let count; - if (this.#strict) { - const now = Date.now(); - this.#cleanupStrictTicks(now); - count = this.#getActiveTicksCount(); - } else { - count = this.#intervalCount; } - const shouldBeRateLimited = count >= this.#intervalCap; - if (shouldBeRateLimited !== previous) { - this.#rateLimitedInInterval = shouldBeRateLimited; - this.emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared"); + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); + if (this.isResuming) + this.input = INPUT_RESUMING; + else if (isCommandUpdateOrGoto) { + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; } + this._emitValuesWithCheckpointMeta(valuesOutput); + } else { + const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); + if (inputWrites.length > 0) { + const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ + name: INPUT, + writes: inputWrites, + triggers: [] + }]), this.checkpointerGetNextVersion, this.triggerToNodes); + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; + } else if (!("__pregel_resuming" in (this.config.configurable ?? {}))) + throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); + else + this.input = INPUT_DONE; } - get isRateLimited() { - return this.#rateLimitedInInterval; - } - get isSaturated() { - return this.#pending === this.#concurrency && this.#queue.size > 0 || this.isRateLimited && this.#queue.size > 0; - } - get runningTasks() { - return [...this.#runningTasks.values()].map((task2) => ({ ...task2 })); - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/async_caller.js -function isResponse(x) { - if (x == null || typeof x !== "object") - return false; - return "status" in x && "statusText" in x && "text" in x; -} -var STATUS_NO_RETRY2, HTTPError, AsyncCaller3 = class { - maxConcurrency; - maxRetries; - queue; - onFailedResponseHook; - customFetch; - constructor(params) { - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 4; - if ("default" in PQueue2) - this.queue = new PQueue2.default({ concurrency: this.maxConcurrency }); - else - this.queue = new PQueue2({ concurrency: this.maxConcurrency }); - this.onFailedResponseHook = params?.onFailedResponseHook; - this.customFetch = params.fetch; + if (!this.isNested) + this.config = patchConfigurable2(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming }); } - call(callable, ...args) { - const { onFailedResponseHook } = this; - return this.queue.add(() => pRetry3(() => callable(...args).catch(async (error51) => { - if (error51 instanceof Error) - throw error51; - else if (isResponse(error51)) - throw await HTTPError.fromResponse(error51, { includeResponse: !!onFailedResponseHook }); - else - throw new Error(error51); - }), { - async onFailedAttempt({ error: error51 }) { - const errorMessage = error51.message ?? ""; - if (errorMessage.startsWith("Cancel") || errorMessage.startsWith("TimeoutError") || errorMessage.startsWith("AbortError")) - throw error51; - if (error51?.code === "ECONNABORTED") - throw error51; - if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("fetch failed") || errorMessage.includes("Failed to fetch") || errorMessage.includes("NetworkError")) { - const connectionError = /* @__PURE__ */ new Error(`Unable to connect to LangGraph server. Please ensure the server is running and accessible. Original error: ${errorMessage}`); - connectionError.name = "ConnectionError"; - throw connectionError; - } - if (error51 instanceof HTTPError) { - if (STATUS_NO_RETRY2.includes(error51.status)) - throw error51; - if (onFailedResponseHook && error51.response) - await onFailedResponseHook(error51.response); - } - }, - retries: this.maxRetries, - randomize: true - }), { throwOnTimeout: true }); - } - callWithOptions(options, callable, ...args) { - if (options.signal) - return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(/* @__PURE__ */ new Error("AbortError")); - }); - })]); - return this.call(callable, ...args); - } - fetch(...args) { - const fetchFn = this.customFetch ?? _getFetchImplementation2(); - return this.call(() => fetchFn(...args).then((res) => res.ok ? res : Promise.reject(res))); - } -}; -var init_async_caller3 = __esm(() => { - init_fetch2(); - init_p_retry3(); - init_dist6(); - STATUS_NO_RETRY2 = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 408, - 409, - 422 - ]; - HTTPError = class HTTPError2 extends Error { - status; - text; - response; - constructor(status, message, response) { - super(`HTTP ${status}: ${message}`); - this.status = status; - this.text = message; - this.response = response; - } - static async fromResponse(response, options) { - try { - return new HTTPError2(response.status, await response.text(), options?.includeResponse ? response : undefined); - } catch { - return new HTTPError2(response.status, response.statusText, options?.includeResponse ? response : undefined); + _emit(values) { + for (const entry of values) { + const [mode, payload, meta3] = entry; + if (this.stream.modes.has(mode)) + this.stream.push([ + this.checkpointNamespace, + mode, + payload, + meta3 + ]); + if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { + const step = mode === "checkpoints" ? this.step - 1 : this.step; + const timestamp = (/* @__PURE__ */ new Date()).toISOString(); + const type = (() => { + if (mode === "checkpoints") + return "checkpoint"; + else if (typeof payload === "object" && payload != null && "result" in payload) + return "task_result"; + else + return "task"; + })(); + this.stream.push([ + this.checkpointNamespace, + "debug", + { + step, + type, + timestamp, + payload + } + ]); } } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/env.js -function getEnvironmentVariable3(name) { - try { - return typeof process !== "undefined" ? process.env?.[name] : undefined; - } catch { - return; } -} -var init_env4 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/signals.js -function mergeSignals(...signals) { - const nonZeroSignals = signals.filter((signal) => signal != null); - if (nonZeroSignals.length === 0) - return; - if (nonZeroSignals.length === 1) - return nonZeroSignals[0]; - const controller = new AbortController; - for (const signal of signals) { - if (signal?.aborted) { - controller.abort(signal.reason); - return controller.signal; + _currentCheckpointMeta() { + if (!this.checkpointMetadata || !this.checkpoint?.id) + return; + const parent_id = this.prevCheckpointConfig?.configurable?.checkpoint_id; + return { checkpoint: { + id: this.checkpoint.id, + ...parent_id ? { parent_id } : {}, + step: this.checkpointMetadata.step, + source: this.checkpointMetadata.source + } }; + } + _emitValuesWithCheckpointMeta(entries) { + const meta3 = this._currentCheckpointMeta(); + if (!meta3) { + this._emit(entries); + return; } - signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true }); + this._emit(entries.map(([mode, payload]) => mode === "values" ? [ + mode, + payload, + meta3 + ] : [mode, payload])); } - return controller.signal; -} -var init_signals = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/sse.js -function BytesLineDecoder() { - let buffer = []; - let trailingCr = false; - return new TransformStream({ - start() { - buffer = []; - trailingCr = false; - }, - transform(chunk, controller) { - let text = chunk; - if (trailingCr) { - text = joinArrays([[CR], text]); - trailingCr = false; - } - if (text.length > 0 && text.at(-1) === CR) { - trailingCr = true; - text = text.subarray(0, -1); - } - if (!text.length) - return; - const trailingNewline = TRAILING_NEWLINE.includes(text.at(-1)); - const lastIdx = text.length - 1; - const { lines } = text.reduce((acc, cur, idx) => { - if (acc.from > idx) - return acc; - if (cur === CR || cur === LF) { - acc.lines.push(text.subarray(acc.from, idx)); - if (cur === CR && text[idx + 1] === LF) - acc.from = idx + 2; - else - acc.from = idx + 1; - } - if (idx === lastIdx && acc.from <= lastIdx) - acc.lines.push(text.subarray(acc.from)); - return acc; - }, { - lines: [], - from: 0 + _putCheckpoint(inputMetadata) { + const exiting = this.checkpointMetadata === inputMetadata; + const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); + const storeCheckpoint = (checkpoint) => { + this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : undefined; + this.checkpointConfig = patchConfigurable2(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); + const channelVersions = { ...this.checkpoint.channel_versions }; + const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); + this.checkpointPreviousVersions = channelVersions; + this._checkpointerPutAfterPrevious({ + config: { ...this.checkpointConfig }, + checkpoint: copyCheckpoint(checkpoint), + metadata: { ...this.checkpointMetadata }, + newVersions }); - if (lines.length === 1 && !trailingNewline) { - buffer.push(lines[0]); - return; - } - if (buffer.length) { - buffer.push(lines[0]); - lines[0] = joinArrays(buffer); - buffer = []; - } - if (!trailingNewline) { - if (lines.length) - buffer = [lines.pop()]; - } - for (const line of lines) - controller.enqueue(line); - }, - flush(controller) { - if (buffer.length) - controller.enqueue(joinArrays(buffer)); + this.checkpointConfig = { + ...this.checkpointConfig, + configurable: { + ...this.checkpointConfig.configurable, + checkpoint_id: this.checkpoint.id + } + }; + }; + if (!exiting) + this.checkpointMetadata = { + ...inputMetadata, + step: this.step, + parents: this.config.configurable?.["checkpoint_map"] ?? {} + }; + this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : undefined, this.step, exiting ? { id: this.checkpoint.id } : undefined); + if (doCheckpoint) + storeCheckpoint(this.checkpoint); + if (!exiting) + this.step += 1; + } + _flushPendingWrites() { + if (this.checkpointer == null) + return; + if (this.checkpointPendingWrites.length === 0) + return; + const config3 = patchConfigurable2(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + const byTask = {}; + for (const [tid, key, value] of this.checkpointPendingWrites) { + byTask[tid] ??= []; + byTask[tid].push([key, value]); } - }); -} -function SSEDecoder() { - let event = ""; - let data = []; - let lastEventId = ""; - let retry = null; - const decoder = new TextDecoder; - return new TransformStream({ - transform(chunk, controller) { - if (!chunk.length) { - if (!event && !data.length && !lastEventId && retry == null) - return; - const sse = { - id: lastEventId || undefined, - event, - data: data.length ? decodeArraysToJson(decoder, data) : null - }; - event = ""; - data = []; - retry = null; - controller.enqueue(sse); - return; - } - if (chunk[0] === COLON) - return; - const sepIdx = chunk.indexOf(COLON); - if (sepIdx === -1) - return; - const fieldName = decoder.decode(chunk.subarray(0, sepIdx)); - let value = chunk.subarray(sepIdx + 1); - if (value[0] === SPACE) - value = value.subarray(1); - if (fieldName === "event") - event = decoder.decode(value); - else if (fieldName === "data") - data.push(value); - else if (fieldName === "id") { - if (value.indexOf(NULL) === -1) - lastEventId = decoder.decode(value); - } else if (fieldName === "retry") { - const retryNum = Number.parseInt(decoder.decode(value), 10); - if (!Number.isNaN(retryNum)) - retry = retryNum; - } - }, - flush(controller) { - if (event) - controller.enqueue({ - id: lastEventId || undefined, - event, - data: data.length ? decodeArraysToJson(decoder, data) : null - }); + for (const [tid, ws] of Object.entries(byTask)) + this._trackCheckpointerPromise(this.checkpointer.putWrites(config3, ws, tid)); + } + _matchWrites(tasks) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__interrupt__" || k === "__resume__") + continue; + const task = Object.values(tasks).find((t) => t.id === tid); + if (task) + task.writes.push([k, v]); } - }); -} -function joinArrays(data) { - const totalLength = data.reduce((acc, curr) => acc + curr.length, 0); - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const c of data) { - merged.set(c, offset); - offset += c.length; + for (const task of Object.values(tasks)) + if (task.writes.length > 0) + this._outputWrites(task.id, task.writes, true); } - return merged; -} -function decodeArraysToJson(decoder, data) { - return JSON.parse(decoder.decode(joinArrays(data))); -} -var CR = 13, LF = 10, NULL = 0, COLON = 58, SPACE = 32, TRAILING_NEWLINE; -var init_sse = __esm(() => { - TRAILING_NEWLINE = [CR, LF]; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/error.js -var isError4 = (error51) => { - if ("isError" in Error && typeof Error.isError === "function") - return Error.isError(error51); - const stringTag = Object.prototype.toString.call(error51); - return stringTag === "[object Error]" || stringTag === "[object DOMException]" || stringTag === "[object DOMError]" || stringTag === "[object Exception]"; -}, getCauseError = (error51) => { - const { cause } = error51; - if (typeof cause !== "object" || cause == null) - return null; - if (!isError4(cause)) - return null; - return cause; -}, isNetworkError4 = (error51) => { - if (!isError4(error51)) - return false; - if (error51.name !== "TypeError" || typeof error51.message !== "string") - return false; - const msg = error51.message.toLowerCase(); - const causeMsg = getCauseError(error51)?.message?.toLowerCase() ?? ""; - return msg.includes("fetch") || msg.includes("network") || msg.includes("connection") || msg.includes("error sending request") || msg.includes("load failed") || msg.includes("terminated") || causeMsg.includes("other side closed") || causeMsg.includes("socket"); }; -var init_error3 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/utils/stream.js -async function* streamWithRetry(makeRequest, options = {}) { - const maxRetries = options.maxRetries ?? 5; - let attempt = 0; - let lastEventId; - let reconnectPath; - while (true) { - let shouldRetry = false; - let lastError; - let reader; - try { - if (options.signal?.aborted) - return; - const { response, stream: stream2 } = await makeRequest(reconnectPath ? { - lastEventId, - reconnectPath - } : undefined); - const locationHeader = response.headers.get("location"); - if (locationHeader) - reconnectPath = locationHeader; - const contentType = response.headers.get("content-type")?.split(";")[0]; - if (contentType && !contentType.includes("text/event-stream")) - throw new Error(`Expected response header Content-Type to contain 'text/event-stream', got '${contentType}'`); - reader = stream2.getReader(); - try { - while (true) { - if (options.signal?.aborted) { - await reader.cancel(); - return; - } - const { done, value } = await reader.read(); - if (done) - break; - if (value.id) - lastEventId = value.id; - yield value; - } - break; - } catch (error51) { - if (reconnectPath && !options.signal?.aborted) - shouldRetry = true; - else - throw error51; - } finally { - if (reader) - try { - reader.releaseLock(); - } catch {} - } - } catch (error51) { - lastError = error51; - if (isNetworkError4(error51) && reconnectPath && !options.signal?.aborted) - shouldRetry = true; - else - throw error51; +var init_loop = __esm(() => { + init_constants3(); + init_errors7(); + init_base15(); + init_utils8(); + init_hash3(); + init_io(); + init_utils9(); + init_algo(); + init_debug(); + init_stream5(); + init_dist3(); + INPUT_DONE = Symbol.for("INPUT_DONE"); + INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); + AsyncBatchedCache = class extends BaseCache2 { + cache; + queue = Promise.resolve(); + constructor(cache2) { + super(); + this.cache = cache2; } - if (shouldRetry) { - attempt += 1; - if (attempt > maxRetries) - throw new MaxReconnectAttemptsError(maxRetries, lastError); - options.onReconnect?.({ - attempt, - lastEventId, - cause: lastError + async get(keys) { + return this.enqueueOperation("get", keys); + } + async set(pairs) { + return this.enqueueOperation("set", pairs); + } + async clear(namespaces) { + return this.enqueueOperation("clear", namespaces); + } + async stop() { + await this.queue; + } + enqueueOperation(type, ...args) { + const newPromise = this.queue.then(() => { + return this.cache[type](...args); }); - const delay = Math.min(1000 * 2 ** (attempt - 1), 5000) + Math.random() * 1000; - await new Promise((resolve2) => { - setTimeout(resolve2, delay); + this.queue = newPromise.then(() => { + return; + }, () => { + return; }); - continue; - } - break; - } -} -var MaxReconnectAttemptsError; -var init_stream7 = __esm(() => { - init_error3(); - MaxReconnectAttemptsError = class extends Error { - constructor(maxAttempts, cause) { - super(`Exceeded maximum SSE reconnection attempts (${maxAttempts})`); - this.name = "MaxReconnectAttemptsError"; - this.cause = cause; + return newPromise; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/base.js -function* iterateHeaders(headers) { - let iter; - let shouldClear = false; - if (headers instanceof Headers) { - const entries = []; - headers.forEach((value, name) => { - entries.push([name, value]); - }); - iter = entries; - } else if (Array.isArray(headers)) - iter = headers; - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (const item of iter) { - const name = item[0]; - if (typeof name !== "string") - throw new TypeError(`Expected header name to be a string, got ${typeof name}`); - const values = Array.isArray(item[1]) ? item[1] : [item[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } - } -} -function mergeHeaders(...headerObjects) { - const outputHeaders = new Headers; - for (const headers of headerObjects) { - if (!headers) - continue; - for (const [name, value] of iterateHeaders(headers)) - if (value === null) - outputHeaders.delete(name); - else - outputHeaders.append(name, value); - } - const headerEntries = []; - outputHeaders.forEach((value, name) => { - headerEntries.push([name, value]); - }); - return Object.fromEntries(headerEntries); -} -function getApiKey(apiKey) { - if (apiKey === null) - return; - if (apiKey) - return apiKey; - for (const prefix of [ - "LANGGRAPH", - "LANGSMITH", - "LANGCHAIN" - ]) { - const envKey = getEnvironmentVariable3(`${prefix}_API_KEY`); - if (envKey) - return envKey.trim().replace(/^["']|["']$/g, ""); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/messages.js +function isChatGenerationChunk2(x) { + return isBaseMessage(x?.message); } -function getRunMetadataFromResponse(response) { - const contentLocation = response.headers.get("Content-Location"); - if (!contentLocation) +function normalizeStreamMetadata(metadata, tags, name) { + if (!metadata) return; - const match2 = REGEX_RUN_METADATA.exec(contentLocation); - if (!match2?.groups?.run_id) + const streamNamespace = metadata.langgraph_checkpoint_ns; + const checkpointNs = metadata.checkpoint_ns; + const namespace = streamNamespace ?? checkpointNs; + if (!namespace) return; - return { - run_id: match2.groups.run_id, - thread_id: match2.groups.thread_id || undefined - }; + return [namespace.split("|"), { + tags, + name, + ...metadata + }]; } -var BaseClient = class { - asyncCaller; - timeoutMs; - apiUrl; - defaultHeaders; - onRequest; - streamProtocol; - constructor(config2) { - const callerOptions = { - maxRetries: 4, - maxConcurrency: 4, - ...config2?.callerOptions - }; - let defaultApiUrl = "http://localhost:8123"; - if (!config2?.apiUrl && typeof globalThis === "object" && globalThis != null) { - const fetchSmb = Symbol.for("langgraph_api:fetch"); - const urlSmb = Symbol.for("langgraph_api:url"); - const global2 = globalThis; - if (global2[fetchSmb]) - callerOptions.fetch ??= global2[fetchSmb]; - if (global2[urlSmb]) - defaultApiUrl = global2[urlSmb]; - } - this.asyncCaller = new AsyncCaller3(callerOptions); - this.timeoutMs = config2?.timeoutMs; - this.apiUrl = config2?.apiUrl?.replace(/\/$/, "") || defaultApiUrl; - this.defaultHeaders = config2?.defaultHeaders || {}; - this.onRequest = config2?.onRequest; - this.streamProtocol = config2?.streamProtocol ?? "legacy"; - const apiKey = getApiKey(config2?.apiKey); - if (apiKey) - this.defaultHeaders["x-api-key"] = apiKey; - } - prepareFetchOptions(path2, options) { - const mutatedOptions = { - ...options, - headers: mergeHeaders(this.defaultHeaders, options?.headers) - }; - if (mutatedOptions.json) { - mutatedOptions.body = JSON.stringify(mutatedOptions.json); - mutatedOptions.headers = mergeHeaders(mutatedOptions.headers, { "content-type": "application/json" }); - delete mutatedOptions.json; +var StreamMessagesHandler; +var init_messages3 = __esm(() => { + init_constants3(); + init_base2(); + init_messages(); + StreamMessagesHandler = class extends BaseCallbackHandler { + name = "StreamMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + emittedChatModelRunIds = {}; + stableMessageIdMap = {}; + lc_prefer_streaming = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; } - if (mutatedOptions.withResponse) - delete mutatedOptions.withResponse; - let timeoutSignal = null; - if (typeof options?.timeoutMs !== "undefined") { - if (options.timeoutMs != null) - timeoutSignal = AbortSignal.timeout(options.timeoutMs); - } else if (this.timeoutMs != null) - timeoutSignal = AbortSignal.timeout(this.timeoutMs); - mutatedOptions.signal = mergeSignals(timeoutSignal, mutatedOptions.signal); - const targetUrl = new URL(`${this.apiUrl}${path2}`); - if (mutatedOptions.params) { - for (const [key, value] of Object.entries(mutatedOptions.params)) { - if (value == null) - continue; - const strValue = typeof value === "string" || typeof value === "number" ? value.toString() : JSON.stringify(value); - targetUrl.searchParams.append(key, strValue); + _emit(meta3, message, runId, dedupe = false) { + if (dedupe && message.id !== undefined && this.seen[message.id] !== undefined) + return; + let messageId = message.id; + if (runId != null) + if (isToolMessage(message)) + messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) + messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; + } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; } - delete mutatedOptions.params; + if (message.id != null) + this.seen[message.id] = message; + this.streamFn([ + meta3[0], + "messages", + [message, meta3[1]] + ]); } - return [targetUrl, mutatedOptions]; - } - async fetch(path2, options) { - const [url2, init] = this.prepareFetchOptions(path2, options); - let finalInit = init; - if (this.onRequest) - finalInit = await this.onRequest(url2, init); - const response = await this.asyncCaller.fetch(url2.toString(), finalInit); - const body = (() => { - if (response.status === 202 || response.status === 204) + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) + this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); + } + handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { + const chunk = fields?.chunk; + this.emittedChatModelRunIds[runId] = true; + if (this.metadatas[runId] !== undefined) + if (isChatGenerationChunk2(chunk)) + this._emit(this.metadatas[runId], chunk.message, runId); + else + this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); + } + handleLLMEnd(output, runId) { + if (this.metadatas[runId] === undefined) return; - return response.json(); - })(); - if (options?.withResponse) - return [await body, response]; - return body; - } - async* streamWithRetry(config2) { - const makeRequest = async (reconnectParams) => { - const requestEndpoint = reconnectParams?.reconnectPath || config2.endpoint; - const isReconnect = !!reconnectParams?.reconnectPath; - const method = isReconnect ? "GET" : config2.method || "GET"; - const requestHeaders = isReconnect && reconnectParams?.lastEventId ? { - ...config2.headers, - "Last-Event-ID": reconnectParams.lastEventId - } : config2.headers; - let [url2, init] = this.prepareFetchOptions(requestEndpoint, { - method, - timeoutMs: null, - signal: config2.signal, - headers: requestHeaders, - params: config2.params, - json: isReconnect ? undefined : config2.json - }); - if (this.onRequest != null) - init = await this.onRequest(url2, init); - const response = await this.asyncCaller.fetch(url2.toString(), init); - if (!response.body) - throw new Error("Expected response body from stream endpoint"); - if (!isReconnect && config2.onInitialResponse) - await config2.onInitialResponse(response); - return { - response, - stream: response.body.pipeThrough(BytesLineDecoder()).pipeThrough(SSEDecoder()) - }; - }; - yield* streamWithRetry(makeRequest, { - maxRetries: config2.maxRetries ?? 5, - signal: config2.signal, - onReconnect: config2.onReconnect - }); - } -}, REGEX_RUN_METADATA; -var init_base16 = __esm(() => { - init_async_caller3(); - init_env4(); - init_signals(); - init_sse(); - init_stream7(); - REGEX_RUN_METADATA = /(\/threads\/(?.+))?\/runs\/(?.+)/; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/multi-cursor-buffer.js -var MultiCursorBuffer; -var init_multi_cursor_buffer = __esm(() => { - MultiCursorBuffer = class { - #items = []; - #wakeups = /* @__PURE__ */ new Set; - #closed = false; - push(item) { - this.#items.push(item); - for (const cb of this.#wakeups) - cb(); - this.#wakeups.clear(); + if (!this.emittedChatModelRunIds[runId]) { + const chatGeneration = output.generations?.[0]?.[0]; + if (isBaseMessage(chatGeneration?.message)) + this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); + delete this.emittedChatModelRunIds[runId]; + } + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; } - close() { - this.#closed = true; - for (const cb of this.#wakeups) - cb(); - this.#wakeups.clear(); + handleLLMError(_err, runId) { + delete this.metadatas[runId]; } - get length() { - return this.#items.length; + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = normalizeStreamMetadata(metadata, tags, name); + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) + if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) + this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) + if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) + this.seen[item.id] = item; + } + } + } } - [Symbol.asyncIterator]() { - let cursor = 0; - return { - next: async () => { - while (true) { - if (cursor < this.#items.length) - return { - done: false, - value: this.#items[cursor++] - }; - if (this.#closed) - return { - done: true, - value: undefined - }; - await new Promise((resolve2) => { - this.#wakeups.add(resolve2); - }); - } - }, - return: async () => ({ - done: true, - value: undefined - }) - }; + handleChainEnd(outputs, runId) { + const metadata = this.metadatas[runId]; + delete this.metadatas[runId]; + if (metadata !== undefined) { + if (isBaseMessage(outputs)) + this._emit(metadata, outputs, runId, true); + else if (Array.isArray(outputs)) { + for (const value of outputs) + if (isBaseMessage(value)) + this._emit(metadata, value, runId, true); + } else if (outputs != null && typeof outputs === "object") { + for (const value of Object.values(outputs)) + if (isBaseMessage(value)) + this._emit(metadata, value, runId, true); + else if (Array.isArray(value)) { + for (const item of value) + if (isBaseMessage(item)) + this._emit(metadata, item, runId, true); + } + } + } + } + handleChainError(_err, runId) { + delete this.metadatas[runId]; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/messages.js -function applyCoreContentDelta(target, delta) { - if (target.type !== delta.type) - return structuredClone(delta); - switch (delta.type) { +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/messages-v2.js +function getResponseMetadata(message) { + if ("response_metadata" in message && typeof message.response_metadata === "object" && message.response_metadata != null) + return message.response_metadata; +} +function getUsageMetadata(message) { + if ("usage_metadata" in message && typeof message.usage_metadata === "object" && message.usage_metadata != null) + return message.usage_metadata; +} +function startBlockFor(block) { + switch (block.type) { case "text": return { - ...target, - ...delta, - text: `${"text" in target ? target.text : ""}${delta.text}` + type: "text", + text: "" }; case "reasoning": return { - ...target, - ...delta, - reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` + type: "reasoning", + reasoning: "" }; + case "tool_call": case "tool_call_chunk": - case "server_tool_call_chunk": { - const merged = { - ...target, - ...delta - }; - if (delta.id == null && "id" in target && target.id != null) - merged.id = target.id; - if (delta.name == null && "name" in target && target.name != null) - merged.name = target.name; - merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; - return merged; - } - default: - return { - ...target, - ...delta - }; - } -} -function coreContentBlockFromDelta(delta, current) { - switch (delta.type) { - case "text-delta": - return { - type: "text", - text: delta.text - }; - case "reasoning-delta": return { - type: "reasoning", - reasoning: delta.reasoning - }; - case "data-delta": { - const merged = { - ...current ?? {}, - data: delta.data + type: "tool_call_chunk", + ...block.id != null ? { id: block.id } : {}, + ...block.name != null ? { name: block.name } : {}, + args: "" }; - if (delta.encoding) - merged.encoding = delta.encoding; - return merged; - } - case "block-delta": - return delta.fields; + default: + return block; } } -function applyCoreEventDelta(current, event) { - if (event.content) - return current ? applyCoreContentDelta(current, event.content) : event.content; - switch (event.delta.type) { - case "text-delta": - if (current?.type === "text") - return { - ...current, - text: `${"text" in current ? current.text : ""}${event.delta.text}` - }; - return coreContentBlockFromDelta(event.delta, current); - case "reasoning-delta": - if (current?.type === "reasoning") - return { - ...current, - reasoning: `${"reasoning" in current ? current.reasoning : ""}${event.delta.reasoning}` - }; - return coreContentBlockFromDelta(event.delta, current); - case "data-delta": { - const merged = { ...current ?? {} }; - merged.data = `${merged.data ?? ""}${event.delta.data}`; - if (event.delta.encoding) - merged.encoding = event.delta.encoding; - return merged; +function deltaFor(block) { + switch (block.type) { + case "text": { + const text = typeof block.text === "string" ? block.text : ""; + return text.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "text-delta", + text + } + } : undefined; } - case "block-delta": - return { - ...current ?? {}, - ...event.delta.fields - }; - } -} -function normalizeUsage2(usage) { - if (!usage) - return; - return { - ...usage, - input_tokens: usage.input_tokens ?? 0, - output_tokens: usage.output_tokens ?? 0, - total_tokens: usage.total_tokens ?? 0 - }; -} -function toStreamingMessageHandle(message) { - return new Proxy(message, { - get(target, prop) { - if (prop === "then") - return; - const value = Reflect.get(target, prop, target); - return typeof value === "function" ? value.bind(target) : value; - }, - has(target, prop) { - if (prop === "then") - return false; - return prop in target; + case "reasoning": { + const reasoning = typeof block.reasoning === "string" ? block.reasoning : ""; + return reasoning.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "reasoning-delta", + reasoning + } + } : undefined; } - }); -} -function cloneBlock(block) { - return structuredClone(block); -} -function blockFromDelta(delta, current) { - return coreContentBlockFromDelta(delta, current); -} -function applyContentDelta(target, delta) { - if (target.type !== delta.type) - return cloneBlock(delta); - switch (delta.type) { - case "text": - return { - ...target, - ...delta, - text: `${"text" in target ? target.text : ""}${delta.text}` - }; - case "reasoning": - return { - ...target, - ...delta, - reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` - }; case "tool_call_chunk": - case "server_tool_call_chunk": { - const merged = { - ...target, - ...delta - }; - if (delta.id == null && "id" in target && target.id != null) - merged.id = target.id; - if (delta.name == null && "name" in target && target.name != null) - merged.name = target.name; - merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; - return merged; - } - default: return { - ...target, - ...delta + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "block-delta", + fields: { + ...block, + type: "tool_call_chunk" + } + } }; + default: + return; } } -function messageKeyFor(event) { - const { namespace, node, data } = event.params; - const namespaceKey = namespace.join("/"); - const messageId = data.event === "message-start" ? data.id ?? "" : ""; - return `${namespaceKey}::${node ?? ""}::${messageId}`; -} -function toChatModelStreamEvent(event) { - return event.params.data; -} -function blockIndexKey(activeKey, protocolIndex, blockType) { - return `${activeKey}::${protocolIndex}::${blockType}`; -} -function areCompatibleBlockTypes(currentType, nextType) { - const toolCallTypes = new Set([ - "tool_call", - "tool_call_chunk", - "tool_use", - "input_json_delta" - ]); - const serverToolCallTypes = new Set(["server_tool_call", "server_tool_call_chunk"]); - return toolCallTypes.has(currentType) && toolCallTypes.has(nextType) || serverToolCallTypes.has(currentType) && serverToolCallTypes.has(nextType); -} -var PUSH_TEXT, PUSH_REASONING, PUSH_EVENT, UPDATE_CONTEXT, FINISH, ERROR4, StreamingMessage, MessageAssembler = class { - activeMessages = /* @__PURE__ */ new Map; - activeByNamespaceNode = /* @__PURE__ */ new Map; - blockIndexByProtocolIndexAndType = /* @__PURE__ */ new Map; - consume(event) { - const data = event.params.data; - const namespaceNodeKey = `${event.params.namespace.join("/")}::${event.params.node ?? ""}`; - if (data.event === "message-start") { - const key = messageKeyFor(event); - this.activeByNamespaceNode.set(namespaceNodeKey, key); - const message2 = { - id: data.id, - namespace: [...event.params.namespace], - node: event.params.node, - metadata: data.metadata, - blocks: [] - }; - this.activeMessages.set(key, message2); - return { - kind: "message-start", - key, - message: message2, - event - }; +var StreamProtocolMessagesHandler; +var init_messages_v2 = __esm(() => { + init_constants3(); + init_base2(); + init_messages(); + StreamProtocolMessagesHandler = class extends BaseCallbackHandler { + name = "StreamProtocolMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + streamedRunIds = /* @__PURE__ */ new Set; + stableMessageIdMap = {}; + lc_prefer_chat_model_stream_events = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; } - const activeKey = this.activeByNamespaceNode.get(namespaceNodeKey); - if (!activeKey) { - const syntheticKey = `${namespaceNodeKey}::`; - this.activeByNamespaceNode.set(namespaceNodeKey, syntheticKey); - const synthetic = { - id: data.id, - namespace: [...event.params.namespace], - node: event.params.node, - blocks: [] - }; - this.activeMessages.set(syntheticKey, synthetic); - return this.consume(event); - } - const message = this.activeMessages.get(activeKey); - if (!message) - throw new Error(`No active message state found for key ${activeKey}`); - if (data.event === "usage") { - message.usage = data.usage; - return { - kind: "usage", - key: activeKey, - message, - event - }; - } - switch (data.event) { - case "content-block-start": - message.blocks[data.index] = cloneBlock(data.content); - this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, data.index, data.content.type), data.index); - return { - kind: "content-block-start", - key: activeKey, - message, - index: data.index, - block: data.content, - event - }; - case "content-block-delta": { - const deltaEvent = data; - const deltaBlock = deltaEvent.content ?? (deltaEvent.delta != null ? blockFromDelta(deltaEvent.delta, message.blocks[data.index]) : undefined); - if (deltaBlock == null) - throw new Error("Received content-block-delta without content"); - const targetIndex = this.resolveBlockIndex(activeKey, message.blocks, data.index, deltaBlock.type); - const current = message.blocks[targetIndex]; - message.blocks[targetIndex] = deltaEvent.content != null ? current == null ? cloneBlock(deltaEvent.content) : applyContentDelta(current, deltaEvent.content) : applyCoreEventDelta(current, data); - return { - kind: "content-block-delta", - key: activeKey, - message, - index: targetIndex, - block: deltaBlock, - event - }; - } - case "content-block-finish": { - const targetIndex = this.resolveFinishBlockIndex(activeKey, data.index, data.content.type); - message.blocks[targetIndex] = cloneBlock(data.content); - return { - kind: "content-block-finish", - key: activeKey, - message, - index: targetIndex, - block: data.content, - event - }; + normalizeMessageId(message, runId) { + let messageId = message.id; + if (runId != null) + if (ToolMessage.isInstance(message)) + messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) + messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; + } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; } - case "message-finish": - message.usage = data.usage; - message.finishMetadata = data.responseMetadata; - this.activeMessages.delete(activeKey); - this.activeByNamespaceNode.delete(namespaceNodeKey); - this.clearBlockIndexAliases(activeKey); - return { - kind: "message-finish", - key: activeKey, - message: structuredClone(message), - event - }; - case "error": - message.error = { - message: data.message, - code: data.code - }; - this.activeMessages.delete(activeKey); - this.activeByNamespaceNode.delete(namespaceNodeKey); - this.clearBlockIndexAliases(activeKey); - return { - kind: "message-error", - key: activeKey, - message: structuredClone(message), - event - }; + if (message.id != null) + this.seen[message.id] = message; + return message.id; } - } - resolveBlockIndex(activeKey, blocks2, protocolIndex, blockType) { - const current = blocks2[protocolIndex]; - if (current == null || current.type === blockType || areCompatibleBlockTypes(current.type, blockType)) { - this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, protocolIndex, blockType), protocolIndex); - return protocolIndex; + emit(meta3, data, runId) { + const metadata = runId != null ? { + ...meta3[1], + run_id: runId + } : meta3[1]; + this.streamFn([ + meta3[0], + "messages", + [data, metadata] + ]); } - const key = blockIndexKey(activeKey, protocolIndex, blockType); - const existing = this.blockIndexByProtocolIndexAndType.get(key); - if (existing != null) - return existing; - const nextIndex = blocks2.length; - this.blockIndexByProtocolIndexAndType.set(key, nextIndex); - return nextIndex; - } - resolveFinishBlockIndex(activeKey, protocolIndex, blockType) { - const key = blockIndexKey(activeKey, protocolIndex, blockType); - const existing = this.blockIndexByProtocolIndexAndType.get(key); - if (existing != null) - return existing; - this.blockIndexByProtocolIndexAndType.set(key, protocolIndex); - return protocolIndex; - } - clearBlockIndexAliases(activeKey) { - const prefix = `${activeKey}::`; - for (const key of this.blockIndexByProtocolIndexAndType.keys()) - if (key.startsWith(prefix)) - this.blockIndexByProtocolIndexAndType.delete(key); - } -}, StreamingMessageAssembler = class { - #assembler = new MessageAssembler; - #activeStreaming = /* @__PURE__ */ new Map; - consume(event) { - const update = this.#assembler.consume(event); - if (update == null) - return; - switch (update.kind) { - case "message-start": { - const streaming = new StreamingMessage(update.message); - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - this.#activeStreaming.set(update.key, streaming); - return streaming; - } - case "content-block-start": { - const streaming = this.#activeStreaming.get(update.key); - if (streaming) { - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - } - if (streaming && update.block.type === "text" && "text" in update.block && update.block.text) - streaming[PUSH_TEXT](update.block.text); - if (streaming && update.block.type === "reasoning" && "reasoning" in update.block && update.block.reasoning) - streaming[PUSH_REASONING](update.block.reasoning); + emitFinalMessage(meta3, message, runId, dedupe = false) { + const existingId = message.id ?? (runId != null ? this.stableMessageIdMap[runId] : undefined); + if (dedupe && existingId != null && this.seen[existingId] !== undefined) return; - } - case "content-block-delta": { - const streaming = this.#activeStreaming.get(update.key); - if (!streaming) - return; - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - if (update.block.type === "text" && "text" in update.block) - streaming[PUSH_TEXT](update.block.text); - if (update.block.type === "reasoning" && "reasoning" in update.block) - streaming[PUSH_REASONING](update.block.reasoning); + const messageId = this.normalizeMessageId(message, runId); + const role = message.type === "human" ? "human" : message.type === "system" ? "system" : message.type === "tool" ? "tool" : "ai"; + const toolCallId = role === "tool" && ToolMessage.isInstance(message) ? message.tool_call_id : undefined; + this.emit(meta3, { + event: "message-start", + ...messageId != null ? { id: messageId } : {}, + ...role !== "ai" ? { role } : {}, + ...typeof toolCallId === "string" ? { tool_call_id: toolCallId } : {} + }, runId); + (Array.isArray(message.content) ? message.content : typeof message.content === "string" && message.content.length > 0 ? [{ + type: "text", + text: message.content + }] : []).forEach((block, offset) => { + const index2 = typeof block.index === "number" ? block.index : offset; + this.emit(meta3, { + event: "content-block-start", + index: index2, + content: startBlockFor(block) + }, runId); + const delta = deltaFor({ + ...block, + index: index2 + }); + if (delta != null) + this.emit(meta3, delta, runId); + this.emit(meta3, { + event: "content-block-finish", + index: index2, + content: block + }, runId); + }); + this.emit(meta3, { + event: "message-finish", + ...getUsageMetadata(message) != null ? { usage: getUsageMetadata(message) } : {}, + ...getResponseMetadata(message) != null ? { responseMetadata: getResponseMetadata(message) } : {} + }, runId); + } + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + } + handleLLMNewToken() {} + handleChatModelStreamEvent(event, runId) { + const meta3 = this.metadatas[runId]; + if (meta3 === undefined) return; + let forwarded = event; + if (event.event === "message-start") { + this.streamedRunIds.add(runId); + const id = event.id ?? `run-${runId}`; + this.seen[id] = true; + this.stableMessageIdMap[runId] ??= id; + if (event.id == null) + forwarded = { + ...event, + id + }; } - case "content-block-finish": { - const streaming = this.#activeStreaming.get(update.key); - if (streaming) { - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - } + this.emit(meta3, forwarded, runId); + } + handleLLMEnd(output, runId) { + const meta3 = this.metadatas[runId]; + if (meta3 === undefined) return; - } - case "usage": { - const streaming = this.#activeStreaming.get(update.key); - if (streaming) { - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + const chatGeneration = output.generations?.[0]?.[0]; + const message = BaseMessage.isInstance(chatGeneration?.message) ? chatGeneration.message : undefined; + if (message != null) + if (this.streamedRunIds.has(runId)) { + const messageId = this.normalizeMessageId(message, runId); + if (messageId != null) + this.seen[messageId] = message; + } else + this.emitFinalMessage(meta3, message, runId, true); + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleLLMError(_err, runId) { + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) + if ((BaseMessage.isInstance(value) || BaseMessageChunk.isInstance(value)) && value.id !== undefined) + this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) + if ((BaseMessage.isInstance(item) || BaseMessageChunk.isInstance(item)) && item.id !== undefined) + this.seen[item.id] = item; + } } - return; } - case "message-finish": { - const streaming = this.#activeStreaming.get(update.key); - if (streaming) { - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - streaming[FINISH](); - this.#activeStreaming.delete(update.key); - } + } + handleChainEnd(outputs, runId) { + const meta3 = this.metadatas[runId]; + delete this.metadatas[runId]; + if (meta3 === undefined) return; - } - case "message-error": { - const streaming = this.#activeStreaming.get(update.key); - if (streaming) { - streaming[UPDATE_CONTEXT](update.event); - streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); - streaming[ERROR4](); - this.#activeStreaming.delete(update.key); + const emitMessage = (value) => { + if (BaseMessage.isInstance(value) && !ToolMessage.isInstance(value)) + this.emitFinalMessage(meta3, value, runId, true); + }; + if (BaseMessage.isInstance(outputs)) + emitMessage(outputs); + else if (Array.isArray(outputs)) + for (const value of outputs) + emitMessage(value); + else if (outputs != null && typeof outputs === "object") + for (const value of Object.values(outputs)) + if (Array.isArray(value)) + for (const item of value) + emitMessage(item); + else + emitMessage(value); + delete this.stableMessageIdMap[runId]; + } + handleChainError(_err, runId) { + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/retry.js +async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { + const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; + let interval = resolvedRetryPolicy !== undefined ? resolvedRetryPolicy.initialInterval ?? 500 : 0; + let attempts = 0; + let error90; + let result; + let config3 = pregelTask.config ?? {}; + if (configurable) + config3 = patchConfigurable2(config3, configurable); + config3 = { + ...config3, + signal + }; + const firstAttemptTime = Date.now(); + if (config3.executionInfo != null) + config3.executionInfo = { + ...config3.executionInfo, + nodeFirstAttemptTime: firstAttemptTime + }; + while (true) { + if (signal?.aborted) + break; + pregelTask.writes.splice(0, pregelTask.writes.length); + error90 = undefined; + try { + result = await pregelTask.proc.invoke(pregelTask.input, config3); + break; + } catch (e) { + error90 = e; + error90.pregelTaskId = pregelTask.id; + if (isParentCommand(error90)) { + const ns3 = config3?.configurable?.checkpoint_ns; + const cmd = error90.command; + if (cmd.graph === ns3) { + for (const writer of pregelTask.writers) + await writer.invoke(cmd, config3); + error90 = undefined; + break; + } else if (cmd.graph === Command.PARENT) { + const parentNs = getParentCheckpointNamespace(ns3); + error90.command = new Command({ + ...error90.command, + graph: parentNs + }); } - return; } + if (isGraphBubbleUp(error90)) + break; + if (resolvedRetryPolicy === undefined) + break; + attempts += 1; + if (attempts >= (resolvedRetryPolicy.maxAttempts ?? 3)) + break; + if (!(resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER)(error90)) + break; + interval = Math.min(resolvedRetryPolicy.maxInterval ?? 128000, interval * (resolvedRetryPolicy.backoffFactor ?? 2)); + const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1000) : interval; + await new Promise((resolve2) => setTimeout(resolve2, intervalWithJitter)); + const errorName = error90.name ?? error90.constructor.unminifiable_name ?? error90.constructor.name; + if (resolvedRetryPolicy?.logWarning ?? true) + console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error90}`); + config3 = patchConfigurable2(config3, { [CONFIG_KEY_RESUMING]: true }); + if (config3.executionInfo != null) + config3.executionInfo = { + ...config3.executionInfo, + nodeAttempt: attempts + 1, + nodeFirstAttemptTime: firstAttemptTime + }; } } + return { + task: pregelTask, + result, + error: error90, + signalAborted: signal?.aborted + }; +} +var DEFAULT_STATUS_NO_RETRY, DEFAULT_RETRY_ON_HANDLER = (error90) => { + if (error90.message.startsWith("Cancel") || error90.message.startsWith("AbortError") || error90.name === "AbortError") + return false; + if (error90.name === "GraphValueError") + return false; + if (error90?.code === "ECONNABORTED") + return false; + const status = error90?.response?.status ?? error90?.status; + if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) + return false; + if (error90?.error?.code === "insufficient_quota") + return false; + return true; }; -var init_messages5 = __esm(() => { - init_multi_cursor_buffer(); - init_messages(); - PUSH_TEXT = Symbol("pushText"); - PUSH_REASONING = Symbol("pushReasoning"); - PUSH_EVENT = Symbol("pushEvent"); - UPDATE_CONTEXT = Symbol("updateContext"); - FINISH = Symbol("finish"); - ERROR4 = Symbol("error"); - StreamingMessage = class { - id; - namespace; - node; - metadata; - assembled; - #events = new MultiCursorBuffer; - #textChunks = []; - #reasoningChunks = []; - #textWaiters = []; - #reasoningWaiters = []; - #textDone = false; - #reasoningDone = false; - #resolveText; - #resolveReasoning; - #textPromise; - #reasoningPromise; - constructor(assembled) { - this.id = assembled.id; - this.assembled = assembled; - this.namespace = assembled.namespace; - this.node = assembled.node; - this.metadata = assembled.metadata; - this.#textPromise = new Promise((r) => { - this.#resolveText = r; - }); - this.#reasoningPromise = new Promise((r) => { - this.#resolveReasoning = r; - }); - } - get text() { - const chunks = this.#textChunks; - const waiters = this.#textWaiters; - const getDone = () => this.#textDone; - let cursor = 0; - return { - [Symbol.asyncIterator]() { - return { async next() { - while (true) { - if (cursor < chunks.length) - return { - done: false, - value: chunks[cursor++] - }; - if (getDone()) - return { - done: true, - value: undefined - }; - await new Promise((resolve2) => { - waiters.push(resolve2); - }); - } - } }; - }, - then: this.#textPromise.then.bind(this.#textPromise), - full: { async* [Symbol.asyncIterator]() { - let accumulated = ""; - for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { - while (true) { - if (cursor < chunks.length) - return { - done: false, - value: chunks[cursor++] - }; - if (getDone()) - return { - done: true, - value: undefined - }; - await new Promise((resolve2) => { - waiters.push(resolve2); - }); - } - } }) }) { - accumulated += chunk; - yield accumulated; - } - } } - }; - } - get reasoning() { - const chunks = this.#reasoningChunks; - const waiters = this.#reasoningWaiters; - const getDone = () => this.#reasoningDone; - let cursor = 0; - return { - [Symbol.asyncIterator]() { - return { async next() { - while (true) { - if (cursor < chunks.length) - return { - done: false, - value: chunks[cursor++] - }; - if (getDone()) - return { - done: true, - value: undefined - }; - await new Promise((resolve2) => { - waiters.push(resolve2); - }); - } - } }; - }, - then: this.#reasoningPromise.then.bind(this.#reasoningPromise), - full: { async* [Symbol.asyncIterator]() { - let accumulated = ""; - for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { - while (true) { - if (cursor < chunks.length) - return { - done: false, - value: chunks[cursor++] - }; - if (getDone()) - return { - done: true, - value: undefined - }; - await new Promise((resolve2) => { - waiters.push(resolve2); - }); - } - } }) }) { - accumulated += chunk; - yield accumulated; - } - } } - }; - } - get usage() { - const promise2 = (async () => { - let usage; - for await (const snapshot of this.#usageIterator()) - usage = snapshot; - return usage; - })(); - return { - [Symbol.asyncIterator]: () => this.#usageIterator(), - then: promise2.then.bind(promise2) - }; +var init_retry = __esm(() => { + init_constants3(); + init_errors7(); + init_config2(); + init_utils9(); + DEFAULT_STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 + ]; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/runner.js +function createPromiseBarrier() { + const barrier = { + next: () => { + return; + }, + wait: Promise.resolve(PROMISE_ADDED_SYMBOL) + }; + function waitHandler(resolve2) { + barrier.next = () => { + barrier.wait = new Promise(waitHandler); + resolve2(PROMISE_ADDED_SYMBOL); + }; + } + barrier.wait = new Promise(waitHandler); + return barrier; +} +async function call2(runner, task, func, name, input, options = {}) { + const scratchpad = task.config?.configurable?.[CONFIG_KEY_SCRATCHPAD]; + if (!scratchpad) + throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); + const cnt = scratchpad.callCounter; + scratchpad.callCounter += 1; + const wcall = new Call({ + func, + name, + input, + cache: options.cache, + retry: options.retry, + callbacks: options.callbacks + }); + const nextTask = await this.scheduleTask(task, cnt, wcall); + if (!nextTask) + return; + const existingPromise = this.executingTasksMap[nextTask.id]; + if (existingPromise !== undefined) + return existingPromise; + if (nextTask.writes.length > 0) { + const returns = nextTask.writes.filter(([c]) => c === RETURN); + const errors6 = nextTask.writes.filter(([c]) => c === ERROR2); + if (returns.length > 0) { + if (returns.length === 1) + return Promise.resolve(returns[0][1]); + throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); } - get toolCalls() { - const events = this.#events; - const iterator = async function* () { - for await (const event of events) - if (event.event === "content-block-finish" && event.content.type === "tool_call") - yield event.content; - }; - return { - [Symbol.asyncIterator]: iterator, - then: async (onfulfilled, onrejected) => { - try { - const calls = []; - for await (const call3 of iterator()) - calls.push(call3); - return onfulfilled ? onfulfilled(calls) : calls; - } catch (err) { - if (onrejected) - return onrejected(err); - throw err; - } - }, - full: { async* [Symbol.asyncIterator]() { - const calls = []; - for await (const call3 of iterator()) { - calls.push(call3); - yield [...calls]; - } - } } - }; + if (errors6.length > 0) { + if (errors6.length === 1) { + const errorValue = errors6[0][1]; + const error90 = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); + return Promise.reject(error90); + } + throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); } - get output() { - return { then: (onf, onr) => this.#assembleMessage().then(onf, onr) }; + return; + } else { + const prom = _runWithRetry(nextTask, options.retry, { [CONFIG_KEY_CALL]: call2.bind(this, runner, nextTask) }); + this.executingTasksMap[nextTask.id] = prom; + this.barrier.next(); + return prom.then(({ result, error: error90 }) => { + if (error90) + return Promise.reject(error90); + return result; + }); + } +} +var PROMISE_ADDED_SYMBOL, PregelRunner = class { + nodeFinished; + loop; + constructor({ loop, nodeFinished }) { + this.loop = loop; + this.nodeFinished = nodeFinished; + } + async tick(options = {}) { + const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; + const nodeErrors = /* @__PURE__ */ new Set; + let graphBubbleUp; + const exceptionSignalController = new AbortController; + const exceptionSignal = exceptionSignalController.signal; + const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : undefined; + const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); + const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ + exceptionSignal, + stepTimeoutSignal, + signal: options.signal + }); + const taskStream = this._executeTasksWithRetry(pendingTasks, { + signals, + retryPolicy, + maxConcurrency + }); + for await (const { task, error: error90, signalAborted } of taskStream) { + this._commit(task, error90); + if (isGraphInterrupt(error90)) + graphBubbleUp = error90; + else if (isGraphBubbleUp(error90) && !isGraphInterrupt(graphBubbleUp)) + graphBubbleUp = error90; + else if (error90 && (nodeErrors.size === 0 || !signalAborted)) { + exceptionSignalController.abort(); + nodeErrors.add(error90); + } } - get blocks() { - return this.assembled.blocks; + disposeCombinedSignal?.(); + onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat()); + if (nodeErrors.size === 1) + throw Array.from(nodeErrors)[0]; + else if (nodeErrors.size > 1) + throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); + if (isGraphInterrupt(graphBubbleUp)) + throw graphBubbleUp; + if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) + throw graphBubbleUp; + } + _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { + const previousSignals = this.loop.config.configurable?.["__pregel_abort_signals"] ?? {}; + const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; + const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; + const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); + const signals = { + externalAbortSignal, + timeoutAbortSignal, + composedAbortSignal + }; + this.loop.config = patchConfigurable2(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); + return { + signals, + disposeCombinedSignal + }; + } + async* _executeTasksWithRetry(tasks, options) { + const { retryPolicy, maxConcurrency, signals } = options ?? {}; + const barrier = createPromiseBarrier(); + const executingTasksMap = {}; + const thisCall = { + executingTasksMap, + barrier, + retryPolicy, + scheduleTask: async (task, writeIdx, call2) => this.loop.acceptPush(task, writeIdx, call2) + }; + if (signals?.composedAbortSignal?.aborted) + throw new Error("Abort"); + let startedTasksCount = 0; + let listener; + const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); + const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { + listener = () => reject(/* @__PURE__ */ new Error("Abort")); + timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); + }) : undefined; + while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { + for (;Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { + const task = tasks[startedTasksCount]; + executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [CONFIG_KEY_CALL]: call2?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error90) => { + return { + task, + error: error90, + signalAborted: signals?.composedAbortSignal?.aborted + }; + }); + } + const settledTask = await Promise.race([ + ...Object.values(executingTasksMap), + ...abortPromise ? [abortPromise] : [], + barrier.wait + ]); + if (settledTask === PROMISE_ADDED_SYMBOL) + continue; + yield settledTask; + if (listener != null) { + timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); + timeoutOrCancelSignal.dispose?.(); + } + delete executingTasksMap[settledTask.task.id]; } - [Symbol.asyncIterator]() { - return this.#events[Symbol.asyncIterator](); + } + _commit(task, error90) { + if (error90 !== undefined) + if (isGraphInterrupt(error90)) { + if (error90.interrupts.length) { + const interrupts = error90.interrupts.map((interrupt2) => [INTERRUPT, interrupt2]); + const resumes = task.writes.filter((w) => w[0] === RESUME); + if (resumes.length) + interrupts.push(...resumes); + this.loop.putWrites(task.id, interrupts); + } + } else if (isGraphBubbleUp(error90) && task.writes.length) + this.loop.putWrites(task.id, task.writes); + else + this.loop.putWrites(task.id, [[ERROR2, { + message: error90.message, + name: error90.name + }]]); + else { + if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes("langsmith:hidden"))) + this.nodeFinished(String(task.name)); + if (task.writes.length === 0) + task.writes.push([NO_WRITES, null]); + this.loop.putWrites(task.id, task.writes); } - then(onfulfilled, onrejected) { - return this.#assembleMessage().then(onfulfilled, onrejected); + } +}; +var init_runner = __esm(() => { + init_constants3(); + init_errors7(); + init_types7(); + init_utils9(); + init_retry(); + PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/validate.js +function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { + if (!channels) + throw new GraphValidationError("Channels not provided"); + const subscribedChannels = /* @__PURE__ */ new Set; + const allOutputChannels = /* @__PURE__ */ new Set; + for (const [name, node] of Object.entries(nodes)) { + if (name === "__interrupt__") + throw new GraphValidationError(`"Node name ${INTERRUPT} is reserved"`); + if (node.constructor === PregelNode) + node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); + else + throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); + } + for (const chan of subscribedChannels) + if (!(chan in channels)) + throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); + if (!Array.isArray(inputChannels)) { + if (!subscribedChannels.has(inputChannels)) + throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); + } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) + throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); + if (!Array.isArray(outputChannels)) + allOutputChannels.add(outputChannels); + else + outputChannels.forEach((chan) => allOutputChannels.add(chan)); + if (streamChannels && !Array.isArray(streamChannels)) + allOutputChannels.add(streamChannels); + else if (Array.isArray(streamChannels)) + streamChannels.forEach((chan) => allOutputChannels.add(chan)); + for (const chan of allOutputChannels) + if (!(chan in channels)) + throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); + if (interruptAfterNodes && interruptAfterNodes !== "*") { + for (const node of interruptAfterNodes) + if (!(node in nodes)) + throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } + if (interruptBeforeNodes && interruptBeforeNodes !== "*") { + for (const node of interruptBeforeNodes) + if (!(node in nodes)) + throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } +} +function validateKeys(keys, channels) { + if (Array.isArray(keys)) { + for (const key of keys) + if (!(key in channels)) + throw new Error(`Key ${String(key)} not found in channels`); + } else if (!(keys in channels)) + throw new Error(`Key ${String(keys)} not found in channels`); +} +var GraphValidationError; +var init_validate4 = __esm(() => { + init_constants3(); + init_read(); + GraphValidationError = class extends Error { + constructor(message) { + super(message); + this.name = "GraphValidationError"; } - async* #usageIterator() { - for await (const event of this.#events) - if (event.event === "message-start" && event.usage) - yield normalizeUsage2(event.usage); - else if (event.event === "message-finish" && event.usage) - yield normalizeUsage2(event.usage); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/topic.js +var Topic; +var init_topic = __esm(() => { + init_errors7(); + init_base15(); + Topic = class Topic2 extends BaseChannel { + lc_graph_name = "Topic"; + unique = false; + accumulate = false; + seen; + values; + constructor(fields) { + super(); + this.unique = fields?.unique ?? this.unique; + this.accumulate = fields?.accumulate ?? this.accumulate; + this.seen = /* @__PURE__ */ new Set; + this.values = []; } - async#assembleMessage() { - const contentBlocks = []; - let id; - let usage; - let metadata = {}; - let finishReason; - for await (const event of this.#events) - switch (event.event) { - case "message-start": - id = event.id ?? id; - if (event.usage) - usage = normalizeUsage2(event.usage); - break; - case "content-block-start": - contentBlocks[event.index] = event.content; - break; - case "content-block-delta": { - const current = contentBlocks[event.index]; - contentBlocks[event.index] = applyCoreEventDelta(current, event); - break; - } - case "content-block-finish": - contentBlocks[event.index] = event.content; - break; - case "message-finish": - finishReason = event.reason; - if (event.usage) - usage = normalizeUsage2(event.usage); - if (event.responseMetadata) - metadata = { - ...metadata, - ...event.responseMetadata - }; - break; - default: - break; - } - return new AIMessage({ - id, - content: contentBlocks.filter((block) => block != null), - usage_metadata: usage, - response_metadata: { - ...metadata, - ...finishReason ? { finish_reason: finishReason } : {}, - output_version: "v1" - } + fromCheckpoint(checkpoint) { + const empty = new Topic2({ + unique: this.unique, + accumulate: this.accumulate }); + if (typeof checkpoint !== "undefined") { + empty.seen = new Set(checkpoint[0]); + empty.values = checkpoint[1]; + } + return empty; } - [PUSH_EVENT](event) { - this.#events.push(event); - } - [UPDATE_CONTEXT](event) { - this.node = event.params.node ?? this.node; - } - [PUSH_TEXT](delta) { - this.#textChunks.push(delta); - const pending = this.#textWaiters.splice(0, this.#textWaiters.length); - for (const waiter of pending) - waiter(); + update(values) { + let updated = false; + if (!this.accumulate) { + updated = this.values.length > 0; + this.values = []; + } + const flatValues = values.flat(); + if (flatValues.length > 0) + if (this.unique) { + for (const value of flatValues) + if (!this.seen.has(value)) { + updated = true; + this.seen.add(value); + this.values.push(value); + } + } else { + updated = true; + this.values.push(...flatValues); + } + return updated; } - [PUSH_REASONING](delta) { - this.#reasoningChunks.push(delta); - const pending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); - for (const waiter of pending) - waiter(); + get() { + if (this.values.length === 0) + throw new EmptyChannelError; + return this.values; } - [FINISH]() { - this.#textDone = true; - this.#reasoningDone = true; - this.#resolveText(this.#textChunks.join("")); - this.#resolveReasoning(this.#reasoningChunks.join("")); - const textPending = this.#textWaiters.splice(0, this.#textWaiters.length); - for (const waiter of textPending) - waiter(); - const reasoningPending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); - for (const waiter of reasoningPending) - waiter(); - this.#events.close(); + checkpoint() { + return [[...this.seen], this.values]; } - [ERROR4]() { - this[FINISH](); + isAvailable() { + return this.values.length !== 0; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/media.js -function base64ToBytes(b64) { - const binary = atob(b64); - const bytes = new Uint8Array(binary.length); - for (let i = 0;i < binary.length; i++) - bytes[i] = binary.charCodeAt(i); - return bytes; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/pregel/index.js +function protocolEventsToEventStream(run2) { + const encoder2 = new TextEncoder; + return new ReadableStream({ async start(controller) { + try { + for await (const event of run2) { + const namespace = event.params.namespace; + const eventName = namespace.length ? `${event.method}|${namespace.join("|")}` : event.method; + controller.enqueue(encoder2.encode(`event: ${eventName} +data: ${JSON.stringify(event.params.data ?? {})} + +`)); + } + } catch (error90) { + controller.enqueue(encoder2.encode(`event: error +data: ${JSON.stringify({ message: String(error90) })} + +`)); + } finally { + controller.close(); + } + } }); } -function concatBytes(parts, totalLength) { - const out = new Uint8Array(totalLength); - let offset = 0; - for (const part of parts) { - out.set(part, offset); - offset += part.byteLength; +function _buildServerInfo(config3) { + const metadata = config3.metadata ?? {}; + const configurable = config3.configurable ?? {}; + const assistantId = configurable.assistant_id ?? metadata.assistant_id; + const graphId = configurable.graph_id ?? metadata.graph_id; + const authUserData = configurable.langgraph_auth_user; + let user; + if (authUserData != null && typeof authUserData === "object" && "identity" in authUserData) + user = authUserData; + if (assistantId != null || graphId != null || user != null) + return { + assistantId: assistantId != null ? String(assistantId) : "", + graphId: graphId != null ? String(graphId) : "", + user + }; +} +function _excludeAsMetadata(key, value) { + const keyLower = key.toLowerCase(); + let hasOmittedSubstring = false; + for (const substr of OMITTED_KEYS) + if (keyLower.includes(substr)) { + hasOmittedSubstring = true; + break; + } + return key.startsWith("__") || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || hasOmittedSubstring; +} +function _getTracingMetadataDefaults(config3) { + const configurable = config3.configurable; + if (!configurable) + return; + const metadata = {}; + for (const [key, value] of Object.entries(configurable)) { + if (_excludeAsMetadata(key, value)) + continue; + metadata[key] = value; } - return out; + return Object.keys(metadata).length > 0 ? metadata : undefined; } -var MEDIA_BLOCK_TYPES, MediaAssemblyError, MediaHandleImpl = class { - type; - messageId; - namespace; - node; - id; - mimeType; - url; - width; - height; - filename; - monotonic = true; - error; - #parts = []; - #totalBytes = 0; - #partialSnapshot = new Uint8Array(0); - #stream; - #streamController; - #blobResolve; - #blobReject; - #blobPromise; - #transcriptParts = []; - #transcriptResolve; - #transcriptReject; - #transcriptPromise; - #cachedObjectURL; - #urlSourced = false; - #urlFetchPromise; - #lastIndex = -1; - #finished = false; - #settled = false; - #fetchImpl; - constructor(options) { - this.type = options.type; - this.messageId = options.messageId; - this.namespace = options.namespace; - this.node = options.node; - this.id = options.id; - this.mimeType = options.mimeType; - this.url = options.url; - this.#fetchImpl = options.fetch; - this.#blobPromise = new Promise((resolve2, reject) => { - this.#blobResolve = resolve2; - this.#blobReject = reject; - }); - this.#blobPromise.catch(() => { - return; - }); - this.#transcriptPromise = new Promise((resolve2, reject) => { - this.#transcriptResolve = resolve2; - this.#transcriptReject = reject; - }); - this.#transcriptPromise.catch(() => { - return; +var Channel = class { + static subscribeTo(channels, options) { + const { key, tags } = { + key: undefined, + tags: undefined, + ...options ?? {} + }; + if (Array.isArray(channels) && key !== undefined) + throw new Error("Can't specify a key when subscribing to multiple channels"); + let channelMappingOrArray; + if (typeof channels === "string") + if (key) + channelMappingOrArray = { [key]: channels }; + else + channelMappingOrArray = [channels]; + else + channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); + return new PregelNode({ + channels: channelMappingOrArray, + triggers: Array.isArray(channels) ? channels : [channels], + tags }); } - observeIndex(index2) { - if (index2 !== this.#lastIndex + 1 && index2 !== this.#lastIndex) - this.monotonic = false; - if (index2 > this.#lastIndex) - this.#lastIndex = index2; - } - absorbBlock(block) { - if (this.#urlSourced) - return; - if (block.type === "audio") - this.#absorbAudio(block); - else if (block.type === "image") - this.#absorbImage(block); - else if (block.type === "video") - this.#absorbVideo(block); - else if (block.type === "file") - this.#absorbFile(block); - } - enterUrlMode(url2) { - this.#urlSourced = true; - this.url = url2; - } - pushBytes(bytes) { - if (this.#finished || this.#settled) - return; - if (bytes.byteLength === 0) - return; - this.#parts.push(bytes); - this.#totalBytes += bytes.byteLength; - this.#partialSnapshot = concatBytes(this.#parts, this.#totalBytes); - if (this.#streamController != null) - try { - this.#streamController.enqueue(bytes); - } catch {} - } - pushTranscript(fragment) { - if (this.type !== "audio") - return; - if (this.#finished || this.#settled) - return; - if (fragment.length === 0) - return; - this.#transcriptParts.push(fragment); - } - finish() { - if (this.#finished || this.#settled) - return; - this.#finished = true; - this.#settled = true; - const blob = new Blob([this.#partialSnapshot], { type: this.mimeType ?? "" }); - this.#blobResolve(blob); - this.#transcriptResolve(this.#transcriptParts.length === 0 ? undefined : this.#transcriptParts.join("")); - try { - this.#streamController?.close(); - } catch {} - } - fail(kind, reason, cause) { - if (this.#settled) - return this.error ?? new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); - this.#settled = true; - const err = new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); - this.error = err; - this.#blobReject(err); - this.#transcriptReject(err); - try { - this.#streamController?.error(err); - } catch {} - return err; - } - get partialBytes() { - return this.#partialSnapshot; - } - get blob() { - if (this.#urlSourced) - return this.#fetchUrlSourced().then((bytes) => new Blob([bytes], { type: this.mimeType ?? "" })); - return this.#blobPromise; - } - get transcript() { - return this.#transcriptPromise; + static writeTo(channels, writes) { + const channelWriteEntries = []; + for (const channel of channels) + channelWriteEntries.push({ + channel, + value: PASSTHROUGH, + skipNone: false + }); + for (const [key, value] of Object.entries(writes ?? {})) + if (Runnable.isRunnable(value) || typeof value === "function") + channelWriteEntries.push({ + channel: key, + value: PASSTHROUGH, + skipNone: true, + mapper: _coerceToRunnable(value) + }); + else + channelWriteEntries.push({ + channel: key, + value, + skipNone: false + }); + return new ChannelWrite(channelWriteEntries); } - get objectURL() { - if (this.#cachedObjectURL != null) { - const cached2 = this.#cachedObjectURL; - return Promise.resolve(cached2); +}, PartialRunnable, Pregel, OMITTED_KEYS; +var init_pregel = __esm(() => { + init_constants3(); + init_errors7(); + init_base15(); + init_config2(); + init_utils8(); + init_write(); + init_read(); + init_io(); + init_utils9(); + init_algo(); + init_subgraph(); + init_debug(); + init_stream5(); + init_loop(); + init_messages3(); + init_messages_v2(); + init_runner(); + init_convert(); + init_run_stream(); + init_stream4(); + init_validate4(); + init_topic(); + init_interrupt(); + init_dist3(); + init_runnables(); + init_manager(); + PartialRunnable = class extends Runnable { + lc_namespace = ["langgraph", "pregel"]; + invoke(_input, _options) { + throw new Error("Not implemented"); } - return this.blob.then((blob) => { - if (this.#cachedObjectURL != null) - return this.#cachedObjectURL; - const url2 = URL.createObjectURL(blob); - this.#cachedObjectURL = url2; - return url2; - }); - } - revoke() { - const url2 = this.#cachedObjectURL; - if (url2 == null) - return; - this.#cachedObjectURL = undefined; - try { - URL.revokeObjectURL(url2); - } catch {} - } - get stream() { - if (this.#stream != null) - return this.#stream; - if (this.#urlSourced) - return this.#buildUrlStream(); - return this.#buildInlineStream(); - } - #absorbAudio(block) { - const mimeType = block.mime_type ?? block.mimeType; - if (this.mimeType == null && mimeType != null) - this.mimeType = mimeType; - if (block.transcript != null && block.transcript.length > 0) - this.pushTranscript(block.transcript); - } - #absorbImage(block) { - const mimeType = block.mime_type ?? block.mimeType; - if (this.mimeType == null && mimeType != null) - this.mimeType = mimeType; - if (this.width == null && block.width != null) - this.width = block.width; - if (this.height == null && block.height != null) - this.height = block.height; - } - #absorbVideo(block) { - const mimeType = block.mime_type ?? block.mimeType; - if (this.mimeType == null && mimeType != null) - this.mimeType = mimeType; - } - #absorbFile(block) { - const mimeType = block.mime_type ?? block.mimeType; - if (this.mimeType == null && mimeType != null) - this.mimeType = mimeType; - if (this.filename == null && block.filename != null) - this.filename = block.filename; - } - #buildInlineStream() { - const seed = this.#partialSnapshot; - const alreadyFinished = this.#finished; - const alreadyErrored = this.error; - this.#stream = new ReadableStream({ - start: (controller) => { - this.#streamController = controller; - if (seed.byteLength > 0) - controller.enqueue(seed); - if (alreadyErrored != null) { - controller.error(alreadyErrored); - return; + withConfig(_config) { + return super.withConfig(_config); + } + stream(input, options) { + return super.stream(input, options); + } + }; + Pregel = class extends PartialRunnable { + static lc_name() { + return "LangGraph"; + } + lc_namespace = ["langgraph", "pregel"]; + lg_is_pregel = true; + nodes; + channels; + inputChannels; + outputChannels; + autoValidate = true; + streamMode = ["values"]; + streamChannels; + interruptAfter; + interruptBefore; + stepTimeout; + debug = false; + checkpointer; + retryPolicy; + config; + store; + cache; + userInterrupt; + streamTransformers; + triggerToNodes = {}; + constructor(fields) { + super(fields); + let { streamMode } = fields; + if (streamMode != null && !Array.isArray(streamMode)) + streamMode = [streamMode]; + this.nodes = fields.nodes; + this.channels = fields.channels; + if ("__pregel_tasks" in this.channels && "lc_graph_name" in this.channels["__pregel_tasks"] && this.channels["__pregel_tasks"].lc_graph_name !== "Topic") + throw new Error(`Channel '${TASKS}' is reserved and cannot be used in the graph.`); + else + this.channels[TASKS] = new Topic({ accumulate: false }); + this.autoValidate = fields.autoValidate ?? this.autoValidate; + this.streamMode = streamMode ?? this.streamMode; + this.inputChannels = fields.inputChannels; + this.outputChannels = fields.outputChannels; + this.streamChannels = fields.streamChannels ?? this.streamChannels; + this.interruptAfter = fields.interruptAfter; + this.interruptBefore = fields.interruptBefore; + this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; + this.debug = fields.debug ?? this.debug; + this.checkpointer = fields.checkpointer; + this.retryPolicy = fields.retryPolicy; + this.config = fields.config; + this.store = fields.store; + this.cache = fields.cache; + this.name = fields.name; + this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; + this.userInterrupt = fields.userInterrupt; + this.streamTransformers = fields.streamTransformers ?? []; + if (this.autoValidate) + this.validate(); + } + withConfig(config3) { + const { streamTransformers, ...restConfig } = config3; + const mergedConfig = mergeConfigs(this.config, restConfig); + const mergedStreamTransformers = [...this.streamTransformers, ...streamTransformers ?? []]; + return new this.constructor({ + ...this, + config: mergedConfig, + streamTransformers: mergedStreamTransformers + }); + } + validate() { + validateGraph({ + nodes: this.nodes, + channels: this.channels, + outputChannels: this.outputChannels, + inputChannels: this.inputChannels, + streamChannels: this.streamChannels, + interruptAfterNodes: this.interruptAfter, + interruptBeforeNodes: this.interruptBefore + }); + for (const [name, node] of Object.entries(this.nodes)) + for (const trigger of node.triggers) { + this.triggerToNodes[trigger] ??= []; + this.triggerToNodes[trigger].push(name); } - if (alreadyFinished) - controller.close(); - }, - cancel: () => { - this.#streamController = undefined; - } - }); - return this.#stream; - } - #buildUrlStream() { - const urlSourceFetch = this.#startUrlFetch(); - this.#stream = new ReadableStream({ - start: async (controller) => { - try { - const response = await urlSourceFetch; - if (response.body == null) { - const bytes = new Uint8Array(await response.arrayBuffer()); - if (bytes.byteLength > 0) - controller.enqueue(bytes); - controller.close(); - return; - } - const reader = response.body.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - if (value != null) - controller.enqueue(value); + return this; + } + get streamChannelsList() { + if (Array.isArray(this.streamChannels)) + return this.streamChannels; + else if (this.streamChannels) + return [this.streamChannels]; + else + return Object.keys(this.channels); + } + get streamChannelsAsIs() { + if (this.streamChannels) + return this.streamChannels; + else + return Object.keys(this.channels); + } + async getGraphAsync(config3) { + return this.getGraph(config3); + } + *getSubgraphs(namespace, recurse) { + for (const [name, node] of Object.entries(this.nodes)) { + if (namespace !== undefined) { + if (!namespace.startsWith(name)) + continue; + } + const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; + for (const candidate of candidates) { + const graph = findSubgraphPregel(candidate); + if (graph !== undefined) { + if (name === namespace) { + yield [name, graph]; + return; + } + if (namespace === undefined) + yield [name, graph]; + if (recurse) { + let newNamespace = namespace; + if (namespace !== undefined) + newNamespace = namespace.slice(name.length + 1); + for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) + yield [`${name}|${subgraphName}`, subgraph]; + } } - controller.close(); - } catch (err) { - controller.error(this.fail("fetch-failed", err?.message, err)); } - }, - cancel: () => { - this.#streamController = undefined; - } - }); - return this.#stream; - } - #startUrlFetch() { - const url2 = this.url; - return this.#fetchImpl(url2).then((response) => { - if (!response.ok) - throw new Error(`fetch(${url2}) failed: ${response.status} ${response.statusText}`); - return response; - }); - } - #fetchUrlSourced() { - if (this.#urlFetchPromise != null) - return this.#urlFetchPromise; - this.#urlFetchPromise = (async () => { - try { - const response = await this.#startUrlFetch(); - const bytes = new Uint8Array(await response.arrayBuffer()); - this.#parts.length = 0; - this.#parts.push(bytes); - this.#totalBytes = bytes.byteLength; - this.#partialSnapshot = bytes; - this.#finished = true; - this.#settled = true; - return bytes; - } catch (err) { - throw this.fail("fetch-failed", err?.message, err); } - })(); - return this.#urlFetchPromise; - } -}, MediaAssembler = class { - #callbacks; - #fetch; - #active = /* @__PURE__ */ new Map; - #activeByNamespaceNode = /* @__PURE__ */ new Map; - #syntheticCounter = 0; - constructor(options = {}) { - this.#callbacks = options; - if (options.fetch != null) - this.#fetch = options.fetch; - else if (typeof fetch === "function") - this.#fetch = fetch; - else - this.#fetch = () => { - throw new Error("MediaAssembler: no fetch implementation available. Pass `fetch` in options."); - }; - } - consume(event) { - const data = event.params.data; - const namespace = event.params.namespace; - const node = event.params.node; - const nsNodeKey = `${namespace.join("/")}::${node ?? ""}`; - if (data.event === "message-start") { - this.#flushSlot(nsNodeKey, "finish"); - this.#activeByNamespaceNode.set(nsNodeKey, { - messageId: data.id ?? "", - keys: /* @__PURE__ */ new Set, - indexKeys: /* @__PURE__ */ new Map - }); - return; - } - if (data.event === "message-finish") { - this.#flushSlot(nsNodeKey, "finish"); - this.#activeByNamespaceNode.delete(nsNodeKey); - return; - } - if (data.event === "error") { - this.#flushSlot(nsNodeKey, "error", data.message); - this.#activeByNamespaceNode.delete(nsNodeKey); - return; } - if (data.event !== "content-block-start" && data.event !== "content-block-delta" && data.event !== "content-block-finish") - return; - const block = data.content; - const blockIndex = data.index ?? 0; - let active = this.#activeByNamespaceNode.get(nsNodeKey); - if (active == null) { - active = { - messageId: `__synthetic_${++this.#syntheticCounter}`, - keys: /* @__PURE__ */ new Set, - indexKeys: /* @__PURE__ */ new Map - }; - this.#activeByNamespaceNode.set(nsNodeKey, active); + async* getSubgraphsAsync(namespace, recurse) { + yield* this.getSubgraphs(namespace, recurse); } - if (block == null && data.event === "content-block-delta") { - const delta = data.delta; - const deltaKey = active.indexKeys.get(blockIndex); - const deltaHandle = deltaKey != null ? this.#active.get(deltaKey) : undefined; - if (delta == null || typeof delta !== "object") - return; - const record2 = delta; - if (deltaHandle == null) { - if (record2.type !== "block-delta" || record2.fields == null || typeof record2.fields !== "object") - return; - const fields = record2.fields; - if (!MEDIA_BLOCK_TYPES.has(fields.type)) - return; - this.#consumeMediaBlock({ - active, - block: fields, - blockIndex, - dataEvent: data.event, - namespace, - node, - terminal: false, - createIfMissing: true - }); - return; + async _prepareStateSnapshot({ config: config3, saved, subgraphCheckpointer, applyPendingWrites = false }) { + if (saved === undefined) + return { + values: {}, + next: [], + config: config3, + tasks: [] + }; + const channels = emptyChannels(this.channels, saved.checkpoint); + if (saved.pendingWrites?.length) { + const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); + if (nullWrites.length > 0) + _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], undefined, this.triggerToNodes); } - deltaHandle.observeIndex(blockIndex); - if (record2.type === "data-delta" && typeof record2.data === "string") { - try { - deltaHandle.pushBytes(base64ToBytes(record2.data)); - } catch (err) { - deltaHandle.fail("message-error", "invalid base64 on delta", err); + const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + store: this.store + })); + const subgraphs = await gatherIterator(this.getSubgraphsAsync()); + const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; + const taskStates = {}; + for (const task of nextTasks) { + const matchingSubgraph = subgraphs.find(([name]) => name === task.name); + if (!matchingSubgraph) + continue; + let taskNs = `${String(task.name)}:${task.id}`; + if (parentNamespace) + taskNs = `${parentNamespace}|${taskNs}`; + if (subgraphCheckpointer === undefined) { + const config4 = { configurable: { + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + taskStates[task.id] = config4; + } else { + const subgraphConfig = { configurable: { + [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + const pregel = matchingSubgraph[1]; + taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); } - return; } - if (record2.type === "block-delta" && record2.fields != null && typeof record2.fields === "object") { - const fields = record2.fields; - deltaHandle.absorbBlock(fields); - if (!deltaHandle.error && fields.data != null) - try { - deltaHandle.pushBytes(base64ToBytes(fields.data)); - } catch (err) { - deltaHandle.fail("message-error", "invalid base64 on delta", err); - } + if (applyPendingWrites && saved.pendingWrites?.length) { + const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); + for (const [taskId, channel, value] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(channel)) + continue; + if (!(taskId in nextTaskById)) + continue; + nextTaskById[taskId].writes.push([String(channel), value]); + } + const tasksWithWrites2 = nextTasks.filter((task) => task.writes.length > 0); + if (tasksWithWrites2.length > 0) + _applyWrites(saved.checkpoint, channels, tasksWithWrites2, undefined, this.triggerToNodes); } - return; + let metadata = saved?.metadata; + if (metadata && saved?.config?.configurable?.thread_id) + metadata = { + ...metadata, + thread_id: saved.config.configurable.thread_id + }; + const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); + return { + values: readChannels(channels, this.streamChannelsAsIs), + next: nextList, + tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), + metadata, + config: patchCheckpointMap(saved.config, saved.metadata), + createdAt: saved.checkpoint.ts, + parentConfig: saved.parentConfig + }; } - if (block == null) - return; - const blockType = block.type; - if (!MEDIA_BLOCK_TYPES.has(blockType)) - return; - this.#consumeMediaBlock({ - active, - block, - blockIndex, - dataEvent: data.event, - namespace, - node, - terminal: data.event === "content-block-finish", - createIfMissing: data.event === "content-block-start" || data.event === "content-block-finish" - }); - } - #consumeMediaBlock({ active, block, blockIndex, dataEvent, namespace, node, terminal, createIfMissing }) { - const blockType = block.type; - if (!MEDIA_BLOCK_TYPES.has(blockType)) - return; - const mediaType = blockType; - const key = `${active.messageId}::${mediaType}::${blockIndex}`; - let handle = this.#active.get(key); - const isStart = dataEvent === "content-block-start"; - if (handle == null) { - const isTerminalBlock = terminal; - if (!isStart && !isTerminalBlock && !createIfMissing) - return; - const mediaBlock2 = block; - handle = new MediaHandleImpl({ - type: mediaType, - messageId: active.messageId, - namespace: [...namespace], - node, - id: mediaBlock2.id, - mimeType: mediaBlock2.mime_type ?? mediaBlock2.mimeType, - url: mediaBlock2.url != null && mediaBlock2.data == null ? mediaBlock2.url : undefined, - fetch: this.#fetch - }); - if (mediaBlock2.url != null && mediaBlock2.data == null) - handle.enterUrlMode(mediaBlock2.url); - handle.observeIndex(blockIndex); - handle.absorbBlock(block); - if (mediaBlock2.data != null) - try { - handle.pushBytes(base64ToBytes(mediaBlock2.data)); - } catch (err) { - handle.fail("message-error", "invalid base64 on initial block", err); - } - this.#active.set(key, handle); - active.keys.add(key); - active.indexKeys.set(blockIndex, key); - this.#emit(handle); - if (isTerminalBlock) { - handle.finish(); - this.#active.delete(key); - active.keys.delete(key); - active.indexKeys.delete(blockIndex); + async getState(config3, options) { + const checkpointer = config3.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config3.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config3.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) + if (name === recastNamespace) + return await subgraph.getState(patchConfigurable(config3, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); } - return; + const mergedConfig = mergeConfigs(this.config, config3); + const saved = await checkpointer.getTuple(config3); + return await this._prepareStateSnapshot({ + config: mergedConfig, + saved, + subgraphCheckpointer: options?.subgraphs ? checkpointer : undefined, + applyPendingWrites: !config3.configurable?.checkpoint_id + }); } - if (terminal) - return; - const mediaBlock = block; - handle.observeIndex(blockIndex); - handle.absorbBlock(block); - if (!handle.error && mediaBlock.data != null) - try { - handle.pushBytes(base64ToBytes(mediaBlock.data)); - } catch (err) { - handle.fail("message-error", "invalid base64 on delta", err); + async* getStateHistory(config3, options) { + const checkpointer = config3.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config3.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config3.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) + if (name === recastNamespace) { + yield* pregel.getStateHistory(patchConfigurable(config3, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); + return; + } } - } - #flushSlot(nsNodeKey, mode, errorMessage) { - const active = this.#activeByNamespaceNode.get(nsNodeKey); - if (active == null) - return; - for (const key of active.keys) { - const handle = this.#active.get(key); - if (handle != null) - if (mode === "finish") - handle.finish(); - else - handle.fail("message-error", errorMessage); - this.#active.delete(key); + const mergedConfig = mergeConfigs(this.config, config3, { configurable: { checkpoint_ns: checkpointNamespace } }); + for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) + yield this._prepareStateSnapshot({ + config: checkpointTuple.config, + saved: checkpointTuple + }); } - active.keys.clear(); - active.indexKeys.clear(); - } - close() { - for (const handle of this.#active.values()) - handle.fail("stream-closed", "upstream event stream closed"); - this.#active.clear(); - this.#activeByNamespaceNode.clear(); - } - #emit(handle) { - switch (handle.type) { - case "audio": - this.#callbacks.onAudio?.(handle); - break; - case "image": - this.#callbacks.onImage?.(handle); - break; - case "video": - this.#callbacks.onVideo?.(handle); - break; - case "file": - this.#callbacks.onFile?.(handle); - break; + async bulkUpdateState(startConfig, supersteps) { + const checkpointer = startConfig.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + if (supersteps.length === 0) + throw new Error("No supersteps provided"); + if (supersteps.some((s) => s.updates.length === 0)) + throw new Error("No updates provided"); + const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && startConfig.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) + return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); + throw new Error(`Subgraph "${recastNamespace}" not found`); + } + const updateSuperStep = async (inputConfig, updates) => { + const config3 = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; + const saved = await checkpointer.getTuple(config3); + const checkpoint = saved !== undefined ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); + const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; + const step = saved?.metadata?.step ?? -1; + let checkpointConfig = patchConfigurable(config3, { checkpoint_ns: config3.configurable?.checkpoint_ns ?? "" }); + let checkpointMetadata = config3.metadata ?? {}; + if (saved?.config.configurable) { + checkpointConfig = patchConfigurable(config3, saved.config.configurable); + checkpointMetadata = { + ...saved.metadata, + ...checkpointMetadata + }; + } + const { values, asNode } = updates[0]; + if (values == null && asNode === undefined) { + if (updates.length > 1) + throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); + return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, undefined, step), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, {}), saved ? saved.metadata : undefined); + } + const channels = emptyChannels(this.channels, checkpoint); + if (values === null && asNode === "__end__") { + if (updates.length > 1) + throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); + if (saved) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + checkpointer, + store: this.store + }); + const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + for (const [taskId, k, v] of saved.pendingWrites || []) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(k)) + continue; + if (!(taskId in nextTasks)) + continue; + nextTasks[taskId].writes.push([k, v]); + } + _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + } + return patchCheckpointMap(await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { + ...checkpointMetadata, + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : undefined); + } + if (asNode === "__copy__") { + if (updates.length > 1) + throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); + if (saved == null) + throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); + const isCopyWithUpdates = (values2) => { + if (!Array.isArray(values2)) + return false; + if (values2.length === 0) + return false; + return values2.every((v) => Array.isArray(v) && v.length === 2); + }; + const nextCheckpoint = createCheckpoint(checkpoint, undefined, step); + const nextConfig2 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: undefined }), nextCheckpoint, { + source: "fork", + step: step + 1, + parents: saved.metadata?.parents ?? {} + }, {}); + if (isCopyWithUpdates(values)) { + const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig2, false, { step: step + 2 }); + const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { + acc[name] ??= []; + acc[name].push({ id }); + return acc; + }, {}); + const userGroupBy = values.reduce((acc, item) => { + const [values2, asNode2] = item; + acc[asNode2] ??= []; + const targetIdx = acc[asNode2].length; + const taskId = tasksGroupBy[asNode2]?.[targetIdx]?.id; + acc[asNode2].push({ + values: values2, + asNode: asNode2, + taskId + }); + return acc; + }, {}); + return updateSuperStep(patchCheckpointMap(nextConfig2, saved.metadata), Object.values(userGroupBy).flat()); + } + return patchCheckpointMap(nextConfig2, saved.metadata); + } + if (asNode === "__input__") { + if (updates.length > 1) + throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); + const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); + if (inputWrites.length === 0) + throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); + _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: inputWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; + const nextConfig2 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { + source: "input", + step: nextStep, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); + await checkpointer.putWrites(nextConfig2, inputWrites, uuid52(INPUT, checkpoint.id)); + return patchCheckpointMap(nextConfig2, saved ? saved.metadata : undefined); + } + if (config3.configurable?.checkpoint_id === undefined && saved?.pendingWrites !== undefined && saved.pendingWrites.length > 0) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + store: this.store, + checkpointer: this.checkpointer, + step: (saved.metadata?.step ?? -1) + 1 + }); + const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], undefined, this.triggerToNodes); + for (const [tid, k, v] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(k) || nextTasks[tid] === undefined) + continue; + nextTasks[tid].writes.push([k, v]); + } + const tasks2 = Object.values(nextTasks).filter((task) => { + return task.writes.length > 0; + }); + if (tasks2.length > 0) + _applyWrites(checkpoint, channels, tasks2, undefined, this.triggerToNodes); + } + const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { + return Object.values(seenVersions); + }).flat().find((v) => !!v); + const validUpdates = []; + if (updates.length === 1) { + let { values: values2, asNode: asNode2, taskId } = updates[0]; + if (asNode2 === undefined && Object.keys(this.nodes).length === 1) + [asNode2] = Object.keys(this.nodes); + else if (asNode2 === undefined && nonNullVersion === undefined) { + if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== undefined) + asNode2 = this.inputChannels; + } else if (asNode2 === undefined) { + const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n3, seen]) => { + return Object.values(seen).map((v) => { + return [v, n3]; + }); + }).flat().filter(([_, v]) => v !== INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); + if (lastSeenByNode) { + if (lastSeenByNode.length === 1) + asNode2 = lastSeenByNode[0][1]; + else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) + asNode2 = lastSeenByNode[lastSeenByNode.length - 1][1]; + } + } + if (asNode2 === undefined) + throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); + validUpdates.push({ + values: values2, + asNode: asNode2, + taskId + }); + } else + for (const { asNode: asNode2, values: values2, taskId } of updates) { + if (asNode2 == null) + throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); + validUpdates.push({ + values: values2, + asNode: asNode2, + taskId + }); + } + const tasks = []; + for (const { asNode: asNode2, values: values2, taskId } of validUpdates) { + if (this.nodes[asNode2] === undefined) + throw new InvalidUpdateError(`Node "${asNode2.toString()}" does not exist`); + const writers = this.nodes[asNode2].getWriters(); + if (!writers.length) + throw new InvalidUpdateError(`No writers found for node "${asNode2.toString()}"`); + tasks.push({ + name: asNode2, + input: values2, + proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], + writes: [], + triggers: [INTERRUPT], + id: taskId ?? uuid52("__interrupt__", checkpoint.id), + writers: [] + }); + } + for (const task of tasks) + await task.proc.invoke(task.input, patchConfig({ + ...config3, + store: config3?.store ?? this.store + }, { + runName: config3.runName ?? `${this.getName()}UpdateState`, + configurable: { + [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) + } + })); + for (const task of tasks) { + const channelWrites = task.writes.filter((w) => w[0] !== PUSH); + if (saved !== undefined && channelWrites.length > 0) + await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); + } + _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); + const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, newVersions); + for (const task of tasks) { + const pushWrites = task.writes.filter((w) => w[0] === PUSH); + if (pushWrites.length > 0) + await checkpointer.putWrites(nextConfig, pushWrites, task.id); + } + return patchCheckpointMap(nextConfig, saved ? saved.metadata : undefined); + }; + let currentConfig = startConfig; + for (const { updates } of supersteps) + currentConfig = await updateSuperStep(currentConfig, updates); + return currentConfig; } - this.#callbacks.onMedia?.(handle); - } -}; -var init_media = __esm(() => { - MEDIA_BLOCK_TYPES = new Set([ - "audio", - "image", - "video", - "file" - ]); - MediaAssemblyError = class extends Error { - kind; - messageId; - partialBytes; - cause; - constructor(kind, messageId, partialBytes, message, options) { - super(message ?? `media ${kind} for message ${messageId}`); - this.name = "MediaAssemblyError"; - this.kind = kind; - this.messageId = messageId; - this.partialBytes = partialBytes; - this.cause = options?.cause; + async updateState(inputConfig, values, asNode) { + return this.bulkUpdateState(inputConfig, [{ updates: [{ + values, + asNode + }] }]); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/error.js -var ProtocolError2; -var init_error4 = __esm(() => { - ProtocolError2 = class extends Error { - code; - response; - constructor(response) { - super(response.message); - this.name = "ProtocolError"; - this.code = response.error; - this.response = response; + _defaults(config3) { + const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config3; + let streamModeSingle = true; + const defaultDebug = debug !== undefined ? debug : this.debug; + let defaultOutputKeys = outputKeys; + if (defaultOutputKeys === undefined) + defaultOutputKeys = this.streamChannelsAsIs; + else + validateKeys(defaultOutputKeys, this.channels); + let defaultInputKeys = inputKeys; + if (defaultInputKeys === undefined) + defaultInputKeys = this.inputChannels; + else + validateKeys(defaultInputKeys, this.channels); + const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; + const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; + let defaultStreamMode; + if (streamMode !== undefined) { + defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; + streamModeSingle = typeof streamMode === "string"; + } else { + if (config3.configurable?.["__pregel_task_id"] !== undefined) + defaultStreamMode = ["values"]; + else + defaultStreamMode = this.streamMode; + streamModeSingle = true; + } + let defaultCheckpointer; + if (this.checkpointer === false) + defaultCheckpointer = undefined; + else if (config3 !== undefined && config3.configurable?.["__pregel_checkpointer"] !== undefined) + defaultCheckpointer = config3.configurable[CONFIG_KEY_CHECKPOINTER]; + else if (this.checkpointer === true) + throw new Error("checkpointer: true cannot be used for root graphs."); + else + defaultCheckpointer = this.checkpointer; + const defaultStore = config3.store ?? this.store; + const defaultCache = config3.cache ?? this.cache; + if (config3.durability != null && config3.checkpointDuring != null) + throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); + const checkpointDuringDurability = (() => { + if (config3.checkpointDuring == null) + return; + if (config3.checkpointDuring === false) + return "exit"; + return "async"; + })(); + const defaultDurability = config3.durability ?? checkpointDuringDurability ?? config3?.configurable?.["__pregel_durability"] ?? "async"; + return [ + defaultDebug, + defaultStreamMode, + defaultInputKeys, + defaultOutputKeys, + rest, + defaultInterruptBefore, + defaultInterruptAfter, + defaultCheckpointer, + defaultStore, + streamModeSingle, + defaultCache, + defaultDurability + ]; + } + async stream(input, options) { + const abortController = new AbortController; + const config3 = { + recursionLimit: this.config?.recursionLimit, + ...options, + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + const stream2 = await super.stream(input, config3); + return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream2) : stream2, abortController); + } + async#streamEventsV3(input, options) { + const { version: version6, encoding, transformers: userTransformers, ...restOptions } = options; + const streamOptions = { + recursionLimit: this.config?.recursionLimit, + ...restOptions, + configurable: { + ...this.config?.configurable, + ...restOptions?.configurable + }, + version: version6, + streamMode: STREAM_EVENTS_V3_MODES, + subgraphs: true, + encoding: undefined + }; + const sourcePromise = this.stream(input, streamOptions); + const graphRun = createGraphRunStream({ [Symbol.asyncIterator]: async function* () { + const src = await sourcePromise; + for await (const chunk of src) + yield chunk; + } }, [...this.streamTransformers ?? [], ...userTransformers ?? []]); + if (encoding === "text/event-stream") { + const abortController = new AbortController; + abortController.signal.addEventListener("abort", () => graphRun.abort(abortController.signal.reason), { once: true }); + return new IterableReadableStreamWithAbortSignal(protocolEventsToEventStream(graphRun), abortController); + } + return graphRun; + } + streamEvents(input, options, streamOptions) { + if (options.version === "v3") + return this.#streamEventsV3(input, options); + const abortController = new AbortController; + const config3 = { + recursionLimit: this.config?.recursionLimit, + ...options, + callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks), + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config3, streamOptions), abortController); + } + async _validateInput(input) { + return input; + } + async _validateContext(context2) { + return context2; + } + async* _streamIterator(input, options) { + const streamEncoding = "version" in (options ?? {}) ? undefined : options?.encoding ?? undefined; + const streamSubgraphs = options?.subgraphs; + const inputConfig = ensureLangGraphConfig(this.config, options); + if (inputConfig.recursionLimit === undefined || inputConfig.recursionLimit < 1) + throw new Error(`Passed "recursionLimit" must be at least 1.`); + if (this.checkpointer !== undefined && this.checkpointer !== false && inputConfig.configurable === undefined) + throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); + const validInput = await this._validateInput(input); + const { runId, ...restConfig } = inputConfig; + const [debug, streamMode, , outputKeys, config3, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache2, durability] = this._defaults(restConfig); + config3.metadata = { + ls_integration: "langgraph", + ...config3.metadata + }; + if (typeof config3.context !== "undefined") + config3.context = await this._validateContext(config3.context); + else + config3.configurable = await this._validateContext(config3.configurable); + const stream2 = new IterableReadableWritableStream({ modes: new Set(streamMode) }); + if (this.checkpointer === true) { + config3.configurable ??= {}; + const ns3 = config3.configurable["checkpoint_ns"] ?? ""; + config3.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns3.split("|").map((part) => part.split(":")[0]).join("|"); + } + if (streamMode.includes("messages")) { + const messageStreamer = options?.version === "v3" ? new StreamProtocolMessagesHandler((chunk) => stream2.push(chunk)) : new StreamMessagesHandler((chunk) => stream2.push(chunk)); + const { callbacks } = config3; + if (callbacks === undefined) + config3.callbacks = [messageStreamer]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat(messageStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(messageStreamer, true); + config3.callbacks = copiedCallbacks; + } + } + if (streamMode.includes("tools")) { + const toolStreamer = new StreamToolsHandler((chunk) => stream2.push(chunk)); + const { callbacks } = config3; + if (callbacks === undefined) + config3.callbacks = [toolStreamer]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat(toolStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(toolStreamer, true); + config3.callbacks = copiedCallbacks; + } + } + config3.writer ??= (chunk) => { + if (!streamMode.includes("custom")) + return; + const ns3 = getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS]?.split("|").slice(0, -1); + stream2.push([ + ns3 ?? [], + "custom", + chunk + ]); + }; + config3.interrupt ??= this.userInterrupt ?? interrupt; + if (config3.serverInfo == null) + config3.serverInfo = _buildServerInfo(config3); + const callbackManagerOptions = { tracerInheritableMetadata: _getTracingMetadataDefaults(config3) }; + const runManager = await (await CallbackManager._configureSync(config3?.callbacks, undefined, config3?.tags, undefined, config3?.metadata, undefined, callbackManagerOptions))?.handleChainStart(this.toJSON(), _coerceToDict3(input, "input"), runId, undefined, undefined, undefined, config3?.runName ?? this.getName()); + const channelSpecs = getOnlyChannels(this.channels); + let loop; + let loopError; + const createAndRunLoop = async () => { + try { + loop = await PregelLoop.initialize({ + input: validInput, + config: config3, + checkpointer, + nodes: this.nodes, + channelSpecs, + outputKeys, + streamKeys: this.streamChannelsAsIs, + store, + cache: cache2, + stream: stream2, + interruptAfter, + interruptBefore, + manager: runManager, + debug: this.debug, + triggerToNodes: this.triggerToNodes, + durability + }); + const runner = new PregelRunner({ + loop, + nodeFinished: config3.configurable?.[CONFIG_KEY_NODE_FINISHED] + }); + if (options?.subgraphs) + loop.config.configurable = { + ...loop.config.configurable, + [CONFIG_KEY_STREAM]: loop.stream + }; + await this._runLoop({ + loop, + runner, + debug, + config: config3 + }); + if (durability === "sync") + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = e; + } finally { + try { + if (loop) { + await loop.store?.stop(); + await loop.cache?.stop(); + } + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = loopError ?? e; + } + if (loopError) + stream2.error(loopError); + else + stream2.close(); + } + }; + const runLoopPromise = createAndRunLoop(); + try { + for await (const chunk of stream2) { + if (chunk === undefined) + throw new Error("Data structure error."); + const [namespace, mode, payload, meta3] = chunk; + if (streamMode.includes(mode)) { + if (streamEncoding === "text/event-stream") { + if (streamSubgraphs) + yield [ + namespace, + mode, + payload + ]; + else + yield [ + null, + mode, + payload + ]; + continue; + } + if (streamSubgraphs && !streamModeSingle) + yield meta3 !== undefined ? [ + namespace, + mode, + payload, + meta3 + ] : [ + namespace, + mode, + payload + ]; + else if (!streamModeSingle) + yield [mode, payload]; + else if (streamSubgraphs) + yield [namespace, payload]; + else + yield payload; + } + } + } catch (e) { + await runManager?.handleChainError(loopError); + throw e; + } finally { + await runLoopPromise; + } + await runManager?.handleChainEnd(loop?.output ?? {}, runId, undefined, undefined, undefined); + } + async invoke(input, options) { + const streamMode = options?.streamMode ?? "values"; + const config3 = { + ...options, + outputKeys: options?.outputKeys ?? this.outputChannels, + streamMode, + encoding: undefined + }; + const chunks = []; + const stream2 = await this.stream(input, config3); + const interruptChunks = []; + let latest; + for await (const chunk of stream2) + if (streamMode === "values") + if (isInterrupted(chunk)) + interruptChunks.push(chunk[INTERRUPT]); + else + latest = chunk; + else + chunks.push(chunk); + if (streamMode === "values") { + if (interruptChunks.length > 0) { + const interrupts = interruptChunks.flat(1); + if (latest == null) + return { [INTERRUPT]: interrupts }; + if (typeof latest === "object") + return { + ...latest, + [INTERRUPT]: interrupts + }; + } + return latest; + } + return chunks; + } + async _runLoop(params) { + const { loop, runner, debug, config: config3 } = params; + let tickError; + try { + while (await loop.tick({ inputKeys: this.inputChannels })) { + for (const { task } of await loop._matchCachedWrites()) + loop._outputWrites(task.id, task.writes, true); + if (debug) + printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); + if (debug) + printStepTasks(loop.step, Object.values(loop.tasks)); + await runner.tick({ + timeout: this.stepTimeout, + retryPolicy: this.retryPolicy, + onStepWrite: (step, writes) => { + if (debug) + printStepWrites(step, writes, this.streamChannelsList); + }, + maxConcurrency: config3.maxConcurrency, + signal: config3.signal + }); + } + if (loop.status === "out_of_steps") + throw new GraphRecursionError([ + `Recursion limit of ${config3.recursionLimit} reached`, + "without hitting a stop condition. You can increase the", + `limit by setting the "recursionLimit" config key.` + ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); + } catch (e) { + tickError = e; + if (!await loop.finishAndHandleError(tickError)) + throw e; + } finally { + if (tickError === undefined) + await loop.finishAndHandleError(); + } + } + async clearCache() { + await this.cache?.clear([]); } }; + OMITTED_KEYS = new Set([ + "key", + "token", + "secret", + "password", + "auth" + ]); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/constants.js -var init_constants5 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/headless-tools.js -function parseHeadlessToolInterruptPayload(value) { - if (typeof value !== "object" || value == null) - return null; - const v = value; - if (v.type !== "tool") - return null; - const rawTc = v.toolCall ?? v.tool_call; - if (typeof rawTc !== "object" || rawTc == null) - return null; - const tc = rawTc; - if (typeof tc.name !== "string") - return null; - return { - type: "tool", - toolCall: { - id: typeof tc.id === "string" ? tc.id : undefined, - name: tc.name, - args: tc.args +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js +var EphemeralValue; +var init_ephemeral_value = __esm(() => { + init_errors7(); + init_base15(); + EphemeralValue = class EphemeralValue2 extends BaseChannel { + lc_graph_name = "EphemeralValue"; + guard; + value = []; + constructor(guard = true) { + super(); + this.guard = guard; } - }; -} -function isHeadlessToolInterrupt(interrupt2) { - return parseHeadlessToolInterruptPayload(interrupt2) != null; -} -var init_headless_tools = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/subscription.js -function normalizeSegment(segment) { - const idx = segment.indexOf(":"); - return idx === -1 ? segment : segment.slice(0, idx); -} -function isPrefixMatch(eventNamespace, prefix) { - if (prefix.length > eventNamespace.length) - return false; - for (let i = 0;i < prefix.length; i += 1) { - const segment = prefix[i]; - const candidate = eventNamespace[i]; - if (candidate === segment) - continue; - if (segment.includes(":")) - return false; - if (normalizeSegment(candidate) === segment) - continue; - return false; - } - return true; -} -function namespaceMatches(eventNamespace, prefixes, depth) { - if (!prefixes || prefixes.length === 0) - return true; - return prefixes.some((prefix) => { - if (!isPrefixMatch(eventNamespace, prefix)) - return false; - if (depth === undefined) + fromCheckpoint(checkpoint) { + const empty = new EphemeralValue2(this.guard); + if (typeof checkpoint !== "undefined") + empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) { + const updated = this.value.length > 0; + this.value = []; + return updated; + } + if (values.length !== 1 && this.guard) + throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); + this.value = [values[values.length - 1]]; return true; - return eventNamespace.length - prefix.length <= depth; - }); -} -function inferChannel(event) { - switch (event.method) { - case "values": - return "values"; - case "checkpoints": - return "checkpoints"; - case "updates": - return "updates"; - case "messages": - return "messages"; - case "tools": - return "tools"; - case "custom": { - const data = event.params.data; - return data?.name != null ? `custom:${data.name}` : "custom"; } - case "lifecycle": - return "lifecycle"; - case "input.requested": - return "input"; - case "tasks": - return "tasks"; - default: - return; - } -} -function matchesSubscription(event, definition) { - const channel = inferChannel(event); - if (channel === undefined) - return false; - const channels = definition.channels; - if (!(channels.includes(channel) || channel.startsWith("custom:") && channels.includes("custom"))) - return false; - return namespaceMatches(event.params.namespace, definition.namespaces, definition.depth); -} -var init_subscription = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/ui/messages.js -function tryCoerceMessageLikeToMessage(message) { - if (message.type === "human" || message.type === "user") - return new HumanMessage(message); - if (message.type === "ai" || message.type === "assistant") - return new AIMessage(normalizeAIMessageToolCalls(message)); - if (message.type === "system") - return new SystemMessage(message); - if (message.type === "tool" && "tool_call_id" in message) - return new ToolMessage({ - ...message, - tool_call_id: message.tool_call_id - }); - if (message.type === "remove" && message.id != null) - return new RemoveMessage({ - ...message, - id: message.id - }); - return coerceMessageLikeToMessage(message); -} -function normalizeAIMessageToolCalls(message) { - const record2 = message; - if (Array.isArray(record2.tool_calls) && record2.tool_calls.length > 0) - return message; - const toolCalls = extractToolCallsFromContent(record2.content); - if (toolCalls.length === 0) - return message; - return { - ...message, - tool_calls: toolCalls - }; -} -function extractToolCallsFromContent(content) { - if (!Array.isArray(content)) - return []; - return content.flatMap((block) => { - if (block == null || typeof block !== "object") - return []; - const record2 = block; - if (record2.type !== "tool_call" && record2.type !== "tool_use") - return []; - return [{ - id: record2.id ?? "", - name: record2.name ?? "", - args: normalizeToolCallArgs(record2.args ?? record2.input), - type: "tool_call" - }]; - }); -} -function normalizeToolCallArgs(value) { - if (value != null && typeof value === "object" && !Array.isArray(value)) - return value; - if (typeof value === "string" && value.length > 0) - try { - const parsed = JSON.parse(value); - if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) - return parsed; - } catch {} - return {}; -} -function ensureMessageInstances(messages) { - return messages.map((msg) => { - if (typeof msg.getType === "function") - return msg; - return tryCoerceMessageLikeToMessage(msg); - }); -} -var init_messages6 = __esm(() => { - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/tools.js -var ToolCallAssembler = class { - active = /* @__PURE__ */ new Map; - consume(event) { - const data = event.params.data; - if (data.event === "tool-started") - return this.handleStarted(event, data); - if (data.event === "tool-finished") { - this.handleFinished(data); - return; + get() { + if (this.value.length === 0) + throw new EmptyChannelError; + return this.value[0]; } - if (data.event === "tool-error") { - this.handleError(data); - return; + checkpoint() { + if (this.value.length === 0) + throw new EmptyChannelError; + return this.value[0]; } - } - failAll(reason) { - for (const tc of this.active.values()) { - tc.rejectOutput(reason); - tc.resolveStatus("error"); - tc.resolveError(reason.message); + isAvailable() { + return this.value.length !== 0; } - this.active.clear(); - } - handleStarted(event, data) { - let resolveOutput; - let rejectOutput; - let resolveStatus; - let resolveError; - const output = new Promise((resolve2, reject) => { - resolveOutput = resolve2; - rejectOutput = reject; - }); - output.catch(() => { - return; - }); - const status = new Promise((resolve2) => { - resolveStatus = resolve2; - }); - const error51 = new Promise((resolve2) => { - resolveError = resolve2; - }); - const entry = { - name: data.tool_name, - callId: data.tool_call_id, - namespace: [...event.params.namespace], - input: data.input, - resolveOutput, - rejectOutput, - resolveStatus, - resolveError - }; - this.active.set(data.tool_call_id, entry); - return { - name: entry.name, - callId: entry.callId, - namespace: entry.namespace, - input: entry.input, - output, - status, - error: error51 - }; - } - handleFinished(data) { - const entry = this.active.get(data.tool_call_id); - if (!entry) - return; - this.active.delete(data.tool_call_id); - entry.resolveOutput(data.output); - entry.resolveStatus("finished"); - entry.resolveError(undefined); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/graph.js +function isCompiledGraph(x) { + return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; +} +function _escapeMermaidKeywords(key) { + if (key === "subgraph") + return `"${key}"`; + return key; +} +var Branch = class { + path; + ends; + constructor(options) { + if (Runnable.isRunnable(options.path)) + this.path = options.path; + else + this.path = _coerceToRunnable(options.path); + this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n3) => { + acc[n3] = n3; + return acc; + }, {}) : options.pathMap; } - handleError(data) { - const entry = this.active.get(data.tool_call_id); - if (!entry) - return; - this.active.delete(data.tool_call_id); - entry.rejectOutput(new Error(data.message)); - entry.resolveStatus("error"); - entry.resolveError(data.message); + run(writer, reader) { + return ChannelWrite.registerWriter(new RunnableCallable({ + name: "", + trace: false, + func: async (input, config3) => { + try { + return await this._route(input, config3, writer, reader); + } catch (e) { + if (e.name === NodeInterrupt.unminifiable_name) + console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation. +NodeInterrupt should only be thrown inside a node, not in edge conditions.`); + throw e; + } + } + })); } -}; -var init_tools4 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subagents.js -var exports_subagents = {}; -__export(exports_subagents, { - SubagentHandle: () => SubagentHandle, - SubagentDiscoveryHandle: () => SubagentDiscoveryHandle -}); -var SubagentHandle = class { - name; - callId; - taskInput; - output; - namespace; - #session; - #messagesIterable; - #toolCallsIterable; - #subgraphsIterable; - #mediaDispatcherStarted = false; - #audioBuffer; - #imagesBuffer; - #videoBuffer; - #filesBuffer; - constructor(name, callId, namespace, taskInput, output, session) { - this.name = name; - this.callId = callId; - this.namespace = namespace; - this.taskInput = taskInput; - this.output = output; - this.#session = session; + async _route(input, config3, writer, reader) { + let result = await this.path.invoke(reader ? reader(config3) : input, config3); + if (!Array.isArray(result)) + result = [result]; + let destinations; + if (this.ends) + destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); + else + destinations = result; + if (destinations.some((dest) => !dest)) + throw new Error("Branch condition returned unknown or null destination"); + if (destinations.filter(_isSend).some((packet) => packet.node === "__end__")) + throw new InvalidUpdateError("Cannot send a packet to the END node"); + return await writer(destinations, config3) ?? input; } - get messages() { - if (this.#messagesIterable) - return this.#messagesIterable; - const buffer = new MultiCursorBuffer; - this.#messagesIterable = buffer; - const assembler = new StreamingMessageAssembler; - this.#startProjection(["messages"], (event) => { - if (event.method !== "messages") - return; - const msg = assembler.consume(event); - if (msg) - buffer.push(msg); - }, () => buffer.close()); - return buffer; +}, Graph$1 = class { + nodes; + edges; + branches; + entryPoint; + compiled = false; + constructor() { + this.nodes = {}; + this.edges = /* @__PURE__ */ new Set; + this.branches = {}; } - get toolCalls() { - if (this.#toolCallsIterable) - return this.#toolCallsIterable; - const buffer = new MultiCursorBuffer; - this.#toolCallsIterable = buffer; - const assembler = new ToolCallAssembler; - this.#startProjection(["tools"], (event) => { - if (event.method !== "tools") - return; - const tc = assembler.consume(event); - if (tc) - buffer.push(tc); - }, () => buffer.close()); - return buffer; + warnIfCompiled(message) { + if (this.compiled) + console.warn(message); } - get audio() { - this.#ensureMediaDispatcher(); - return this.#audioBuffer; + get allEdges() { + return this.edges; } - get images() { - this.#ensureMediaDispatcher(); - return this.#imagesBuffer; + addNode(...args) { + function isMutlipleNodes(args2) { + return args2.length >= 1 && typeof args2[0] !== "string"; + } + const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) + throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + for (const reservedChar of ["|", ":"]) + if (key.includes(reservedChar)) + throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) + throw new Error(`Node \`${key}\` already present.`); + if (key === "__end__") + throw new Error(`Node \`${key}\` is reserved.`); + const runnable = _coerceToRunnable(action); + this.nodes[key] = { + runnable, + metadata: options?.metadata, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends + }; + } + return this; } - get video() { - this.#ensureMediaDispatcher(); - return this.#videoBuffer; + addEdge(startKey, endKey) { + this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (startKey === "__end__") + throw new Error("END cannot be a start node"); + if (endKey === "__start__") + throw new Error("START cannot be an end node"); + if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) + throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); + this.edges.add([startKey, endKey]); + return this; } - get files() { - this.#ensureMediaDispatcher(); - return this.#filesBuffer; + addConditionalEdges(source, path2, pathMap) { + const options = typeof source === "object" ? source : { + source, + path: path2, + pathMap + }; + this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + if (!Runnable.isRunnable(options.path)) + options.path = _coerceToRunnable(options.path); + const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); + if (this.branches[options.source] && this.branches[options.source][name]) + throw new Error(`Condition \`${name}\` already present for node \`${source}\``); + this.branches[options.source] ??= {}; + this.branches[options.source][name] = new Branch(options); + return this; } - #ensureMediaDispatcher() { - if (this.#mediaDispatcherStarted) - return; - this.#mediaDispatcherStarted = true; - const audio = new MultiCursorBuffer; - const images = new MultiCursorBuffer; - const video = new MultiCursorBuffer; - const files = new MultiCursorBuffer; - this.#audioBuffer = audio; - this.#imagesBuffer = images; - this.#videoBuffer = video; - this.#filesBuffer = files; - const assembler = new MediaAssembler({ - onAudio: (m) => audio.push(m), - onImage: (m) => images.push(m), - onVideo: (m) => video.push(m), - onFile: (m) => files.push(m) - }); - this.#startProjection(["messages"], (event) => { - if (event.method !== "messages") - return; - assembler.consume(event); - }, () => { - assembler.close(); - audio.close(); - images.close(); - video.close(); - files.close(); - }); + setEntryPoint(key) { + this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(START, key); } - get subgraphs() { - if (this.#subgraphsIterable) - return this.#subgraphsIterable; - const buffer = new MultiCursorBuffer; - this.#subgraphsIterable = buffer; - (async () => { - const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ - channels: ["lifecycle"], - namespaces: [this.namespace] - }), this.#session, this.namespace); - for await (const sub of discovery) - buffer.push(sub); - buffer.close(); - })(); - return buffer; + setFinishPoint(key) { + this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(key, END); } - subscribe(paramsOrChannels, options = {}) { - if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) - return this.#session.subscribe({ - ...paramsOrChannels, - namespaces: paramsOrChannels.namespaces ?? [this.namespace] - }); - return this.#session.subscribe(paramsOrChannels, { - ...options, - namespaces: options.namespaces ?? [this.namespace] + compile({ checkpointer, interruptBefore, interruptAfter, name, transformers } = {}) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const compiled = new CompiledGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + [START]: new EphemeralValue, + [END]: new EphemeralValue + }, + inputChannels: START, + outputChannels: END, + streamChannels: [], + streamMode: "values", + name, + streamTransformers: transformers }); + for (const [key, node] of Object.entries(this.nodes)) + compiled.attachNode(key, node); + for (const [start, end] of this.edges) + compiled.attachEdge(start, end); + for (const [start, branches] of Object.entries(this.branches)) + for (const [name2, branch] of Object.entries(branches)) + compiled.attachBranch(start, name2, branch); + return compiled.validate(); } - async#startProjection(channels, onEvent, onDone) { - try { - const rawHandle = await this.#session.subscribe({ - channels, - namespaces: [this.namespace] - }); - for await (const event of rawHandle) - onEvent(event); - } finally { - onDone(); + validate(interrupt2) { + const allSources = new Set([...this.allEdges].map(([src, _]) => src)); + for (const [start] of Object.entries(this.branches)) + allSources.add(start); + for (const source of allSources) + if (source !== "__start__" && !(source in this.nodes)) + throw new Error(`Found edge starting at unknown node \`${source}\``); + const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); + for (const [start, branches] of Object.entries(this.branches)) + for (const branch of Object.values(branches)) + if (branch.ends != null) + for (const end of Object.values(branch.ends)) + allTargets.add(end); + else { + allTargets.add(END); + for (const node of Object.keys(this.nodes)) + if (node !== start) + allTargets.add(node); + } + for (const node of Object.values(this.nodes)) + for (const target of node.ends ?? []) + allTargets.add(target); + for (const node of Object.keys(this.nodes)) + if (!allTargets.has(node)) + throw new UnreachableNodeError([ + `Node \`${node}\` is not reachable.`, + "", + "If you are returning Command objects from your node,", + 'make sure you are passing names of potential destination nodes as an "ends" array', + 'into ".addNode(..., { ends: ["node1", "node2"] })".' + ].join(` +`), { lc_error_code: "UNREACHABLE_NODE" }); + for (const target of allTargets) + if (target !== "__end__" && !(target in this.nodes)) + throw new Error(`Found edge ending at unknown node \`${target}\``); + if (interrupt2) { + for (const node of interrupt2) + if (!(node in this.nodes)) + throw new Error(`Interrupt node \`${node}\` is not present`); } + this.compiled = true; } -}, SubagentDiscoveryHandle; -var init_subagents = __esm(() => { - init_multi_cursor_buffer(); - init_tools4(); - init_messages5(); - init_media(); - init_subgraphs2(); - SubagentDiscoveryHandle = class { - #source; - #session; - #queue = []; - #waiters = []; - #pending = /* @__PURE__ */ new Map; - #sourcePump; - #closed = false; - constructor(source, session) { - this.#source = source; - this.#session = session; +}, CompiledGraph; +var init_graph2 = __esm(() => { + init_constants3(); + init_errors7(); + init_utils8(); + init_write(); + init_read(); + init_subgraph(); + init_pregel(); + init_ephemeral_value(); + init_runnables(); + init_graph(); + init_v43(); + init_wrapper(); + CompiledGraph = class extends Pregel { + builder; + constructor({ builder, ...rest }) { + super(rest); + this.builder = builder; } - #processEvent(event) { - if (event.method !== "tools") - return; - const tools = event; - const data = tools.params.data; - const toolCallId = data.tool_call_id; - if (data.tool_name === "task" && data.event === "tool-started") { - const rawInput = data.input; - const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {}; - const name = input.subagent_type ?? "unknown"; - const description = input.description ?? ""; - let resolveTaskInput; - let resolveOutput; - let rejectOutput; - const taskInput = new Promise((r) => { - resolveTaskInput = r; - }); - const output = new Promise((res, rej) => { - resolveOutput = res; - rejectOutput = rej; - }); - resolveTaskInput(description); - this.#pending.set(toolCallId, { - resolveOutput, - rejectOutput - }); - return new SubagentHandle(name, toolCallId, [...tools.params.namespace], taskInput, output, this.#session); - } - if (toolCallId) { - const pending = this.#pending.get(toolCallId); - if (pending) { - if (data.event === "tool-finished") { - pending.resolveOutput(data.output); - this.#pending.delete(toolCallId); - } else if (data.event === "tool-error") { - const message = data.message ?? "unknown error"; - pending.rejectOutput(new Error(message)); - this.#pending.delete(toolCallId); - } - } - } + withConfig(config3) { + return super.withConfig(config3); } - #start() { - if (this.#sourcePump) - return; - this.#sourcePump = (async () => { - for await (const event of this.#source) { - const handle = this.#processEvent(event); - if (!handle) - continue; - const waiter = this.#waiters.shift(); - if (waiter) - waiter({ - done: false, - value: handle - }); - else - this.#queue.push(handle); - } - this.#closed = true; - for (const pending of this.#pending.values()) - pending.resolveOutput(undefined); - this.#pending.clear(); - while (this.#waiters.length > 0) - this.#waiters.shift()?.({ - done: true, - value: undefined - }); - })(); + attachNode(key, node) { + this.channels[key] = new EphemeralValue; + this.nodes[key] = new PregelNode({ + channels: [], + triggers: [], + metadata: node.metadata, + subgraphs: node.subgraphs, + ends: node.ends + }).pipe(node.runnable).pipe(new ChannelWrite([{ + channel: key, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + this.streamChannels.push(key); } - async close() { - this.#closed = true; - await this.#source.unsubscribe(); + attachEdge(start, end) { + if (end === "__end__") { + if (start === "__start__") + throw new Error("Cannot have an edge from START to END"); + this.nodes[start].writers.push(new ChannelWrite([{ + channel: END, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + } else { + this.nodes[end].triggers.push(start); + this.nodes[end].channels.push(start); + } } - [Symbol.asyncIterator]() { - this.#start(); - return { - next: async () => { - if (this.#queue.length > 0) - return { - done: false, - value: this.#queue.shift() - }; - if (this.#closed) - return { - done: true, - value: undefined - }; - return await new Promise((resolve2) => { - this.#waiters.push(resolve2); - }); - }, - return: async () => { - await this.close(); + attachBranch(start, name, branch) { + if (start === "__start__" && !this.nodes["__start__"]) + this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); + this.nodes[start].pipe(branch.run((dests) => { + return new ChannelWrite(dests.map((dest) => { + if (_isSend(dest)) + return dest; return { - done: true, - value: undefined + channel: dest === "__end__" ? END : `branch:${start}:${name}:${dest}`, + value: PASSTHROUGH }; + }), [TAG_HIDDEN]); + })); + const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); + for (const end of ends) + if (end !== "__end__") { + const channelName = `branch:${start}:${name}:${end}`; + this.channels[channelName] = new EphemeralValue; + this.nodes[end].triggers.push(channelName); + this.nodes[end].channels.push(channelName); } - }; + } + async getGraphAsync(config3) { + const xray = config3?.xray; + const graph = new Graph; + const startNodes = { [START]: graph.addNode({ schema: exports_external3.any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) + subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); + function addEdge(start, end, label, conditional = false) { + if (end === "__end__" && endNodes["__end__"] === undefined) + endNodes[END] = graph.addNode({ schema: exports_external3.any() }, END); + if (startNodes[start] === undefined) + return; + if (endNodes[end] === undefined) + throw new Error(`End node ${end} not found!`); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) + metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) + metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) + metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== undefined ? await subgraphs[key].getGraphAsync({ + ...config3, + xray: newXrayValue + }) : node.getGraph(config3); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + let _isRunnableInterface = function(thing) { + return thing ? thing.lc_runnable : false; + }, _nodeDataStr = function(id, data) { + if (id !== undefined && !validate8(id)) + return id; + else if (_isRunnableInterface(data)) + try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else + return data.name ?? "UnknownSchema"; + }; + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === undefined) + throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + if (s !== undefined) + startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) + return -1; + else if (b > a) + return 1; + else + return 0; + }); + for (const [start, end] of sortedEdges) + addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== undefined) + ends = branch.ends; + else + ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) + addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + for (const [key, node] of Object.entries(this.builder.nodes)) + if (node.ends !== undefined) + for (const end of node.ends) + addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), undefined, true); + return graph; + } + getGraph(config3) { + const xray = config3?.xray; + const graph = new Graph; + const startNodes = { [START]: graph.addNode({ schema: exports_external3.any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) + subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); + function addEdge(start, end, label, conditional = false) { + if (end === "__end__" && endNodes["__end__"] === undefined) + endNodes[END] = graph.addNode({ schema: exports_external3.any() }, END); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) + metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) + metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) + metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== undefined ? subgraphs[key].getGraph({ + ...config3, + xray: newXrayValue + }) : node.getGraph(config3); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + let _isRunnableInterface = function(thing) { + return thing ? thing.lc_runnable : false; + }, _nodeDataStr = function(id, data) { + if (id !== undefined && !validate8(id)) + return id; + else if (_isRunnableInterface(data)) + try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else + return data.name ?? "UnknownSchema"; + }; + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === undefined) + throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + if (s !== undefined) + startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) + return -1; + else if (b > a) + return 1; + else + return 0; + }); + for (const [start, end] of sortedEdges) + addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== undefined) + ends = branch.ends; + else + ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) + addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + return graph; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subgraphs.js -var SubgraphHandle = class { - name; - index; - namespace; - cause; - graphName; - toolStartedEvent; - #session; - #messagesIterable; - #valuesProjection; - #toolCallsIterable; - #subgraphsIterable; - #subagentsIterable; - #outputPromise; - #mediaDispatcherStarted = false; - #audioBuffer; - #imagesBuffer; - #videoBuffer; - #filesBuffer; - constructor(name, index2, namespace, session, options) { - this.name = name; - this.index = index2; - this.namespace = namespace; - this.cause = options?.cause; - this.graphName = options?.graphName; - this.toolStartedEvent = options?.toolStartedEvent; - this.#session = session; - } - get messages() { - if (this.#messagesIterable) - return this.#messagesIterable; - const buffer = new MultiCursorBuffer; - this.#messagesIterable = buffer; - const assembler = new StreamingMessageAssembler; - this.#startProjection(["messages"], (event) => { - if (event.method !== "messages") - return; - const msg = assembler.consume(event); - if (msg) - buffer.push(msg); - }, () => buffer.close()); - return buffer; - } - get values() { - if (this.#valuesProjection) - return this.#valuesProjection; - const buffer = new MultiCursorBuffer; - let lastValue; - let resolveOutput; - const outputPromise = new Promise((resolve2) => { - resolveOutput = resolve2; - }); - this.#outputPromise = outputPromise; - const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); - this.#valuesProjection = projection; - this.#startProjection(["values"], (event) => { - if (event.method !== "values") - return; - const data = event.params.data; - lastValue = data; - buffer.push(data); - }, () => { - resolveOutput(lastValue); - buffer.close(); - }); - return projection; - } - get toolCalls() { - if (this.#toolCallsIterable) - return this.#toolCallsIterable; - const buffer = new MultiCursorBuffer; - this.#toolCallsIterable = buffer; - const assembler = new ToolCallAssembler; - this.#startProjection(["tools"], (event) => { - if (event.method !== "tools") - return; - const tc = assembler.consume(event); - if (tc) - buffer.push(tc); - }, () => buffer.close()); - return buffer; - } - get subgraphs() { - if (this.#subgraphsIterable) - return this.#subgraphsIterable; - const buffer = new MultiCursorBuffer; - this.#subgraphsIterable = buffer; - (async () => { - const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ - channels: ["lifecycle", "tools"], - namespaces: [this.namespace] - }), this.#session, this.namespace); - for await (const sub of discovery) - buffer.push(sub); - buffer.close(); - })(); - return buffer; - } - get subagents() { - if (this.#subagentsIterable) - return this.#subagentsIterable; - const buffer = new MultiCursorBuffer; - this.#subagentsIterable = buffer; - (async () => { - const rawHandle = await this.#session.subscribe({ - channels: ["tools", "lifecycle"], - namespaces: [this.namespace] - }); - const { SubagentDiscoveryHandle: Discovery } = await Promise.resolve().then(() => (init_subagents(), exports_subagents)); - const discovery = new Discovery(rawHandle, this.#session); - for await (const sub of discovery) - buffer.push(sub); - buffer.close(); - })(); - return buffer; - } - get audio() { - this.#ensureMediaDispatcher(); - return this.#audioBuffer; - } - get images() { - this.#ensureMediaDispatcher(); - return this.#imagesBuffer; - } - get video() { - this.#ensureMediaDispatcher(); - return this.#videoBuffer; - } - get files() { - this.#ensureMediaDispatcher(); - return this.#filesBuffer; - } - get output() { - this.values; - return this.#outputPromise; - } - #ensureMediaDispatcher() { - if (this.#mediaDispatcherStarted) - return; - this.#mediaDispatcherStarted = true; - const audio = new MultiCursorBuffer; - const images = new MultiCursorBuffer; - const video = new MultiCursorBuffer; - const files = new MultiCursorBuffer; - this.#audioBuffer = audio; - this.#imagesBuffer = images; - this.#videoBuffer = video; - this.#filesBuffer = files; - const assembler = new MediaAssembler({ - onAudio: (m) => audio.push(m), - onImage: (m) => images.push(m), - onVideo: (m) => video.push(m), - onFile: (m) => files.push(m) - }); - this.#startProjection(["messages"], (event) => { - if (event.method !== "messages") - return; - assembler.consume(event); - }, () => { - assembler.close(); - audio.close(); - images.close(); - video.close(); - files.close(); - }); - } - subscribe(paramsOrChannels, options = {}) { - if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) - return this.#session.subscribe({ - ...paramsOrChannels, - namespaces: paramsOrChannels.namespaces ?? [this.namespace] - }); - return this.#session.subscribe(paramsOrChannels, { - ...options, - namespaces: options.namespaces ?? [this.namespace] - }); - } - async#startProjection(channels, onEvent, onDone) { +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/types.js +function isStandardSchema2(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +} +function isStandardJSONSchema(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +} +function isSerializableSchema2(schema) { + return isStandardSchema2(schema) && isStandardJSONSchema(schema); +} +var init_types8 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/adapter.js +function getJsonSchemaFromSchema(schema) { + if (isStandardJSONSchema(schema)) try { - const rawHandle = await this.#session.subscribe({ - channels, - namespaces: [this.namespace] - }); - for await (const event of rawHandle) - onEvent(event); - } finally { - onDone(); + return schema["~standard"].jsonSchema.input({ target: "draft-07" }); + } catch { + return; } - } -}, SubgraphDiscoveryHandle; -var init_subgraphs2 = __esm(() => { - init_multi_cursor_buffer(); - init_tools4(); - init_messages5(); - init_media(); - SubgraphDiscoveryHandle = class { - #source; - #session; - #parentNamespace; - #discovered = /* @__PURE__ */ new Set; - #pendingToolStarts = /* @__PURE__ */ new Map; - #pendingToolCallHandles = /* @__PURE__ */ new Map; - #queue = []; - #waiters = []; - #sourcePump; - #closed = false; - constructor(source, session, parentNamespace = []) { - this.#source = source; - this.#session = session; - this.#parentNamespace = parentNamespace; +} +function getSchemaDefaultGetter(schema) { + if (schema == null) + return; + if (!isStandardSchema2(schema)) + return; + try { + const result = schema["~standard"].validate(undefined); + if (result && typeof result === "object" && !(("then" in result) && typeof result.then === "function")) { + const syncResult = result; + if (!syncResult.issues) { + const defaultValue = syncResult.value; + return () => defaultValue; + } } - #emit(handle) { - const waiter = this.#waiters.shift(); - if (waiter) - waiter({ - done: false, - value: handle - }); - else - this.#queue.push(handle); + } catch {} +} +var init_adapter = __esm(() => { + init_types8(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/untracked_value.js +var MISSING, UntrackedValueChannel; +var init_untracked_value = __esm(() => { + init_errors7(); + init_base15(); + MISSING = Symbol.for("langgraph.channel.missing"); + UntrackedValueChannel = class UntrackedValueChannel2 extends BaseChannel { + lc_graph_name = "UntrackedValue"; + guard; + _value = MISSING; + initialValueFactory; + constructor(options) { + super(); + this.guard = options?.guard ?? true; + this.initialValueFactory = options?.initialValueFactory; + if (this.initialValueFactory) + this._value = this.initialValueFactory(); } - #processToolEvent(event) { - if (event.method !== "tools") + fromCheckpoint(_checkpoint) { + return new UntrackedValueChannel2({ + guard: this.guard, + initialValueFactory: this.initialValueFactory + }); + } + update(values) { + if (values.length === 0) return false; - const tools = event; - const data = tools.params.data; - if (data.event !== "tool-started") - return true; - const toolCallId = data.tool_call_id; - if (!toolCallId) - return true; - const pendingHandle = this.#pendingToolCallHandles.get(toolCallId); - if (pendingHandle) { - pendingHandle.toolStartedEvent = tools; - this.#pendingToolCallHandles.delete(toolCallId); + if (values.length !== 1 && this.guard) + throw new InvalidUpdateError("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this._value = values[values.length - 1]; + return true; + } + get() { + if (this._value === MISSING) + throw new EmptyChannelError; + return this._value; + } + checkpoint() {} + isAvailable() { + return this._value !== MISSING; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/values/reduced.js +var REDUCED_VALUE_SYMBOL, ReducedValue; +var init_reduced = __esm(() => { + REDUCED_VALUE_SYMBOL = Symbol.for("langgraph.state.reduced_value"); + ReducedValue = class { + [REDUCED_VALUE_SYMBOL] = true; + valueSchema; + inputSchema; + reducer; + jsonSchemaExtra; + constructor(valueSchema, init) { + this.reducer = init.reducer; + this.jsonSchemaExtra = init.jsonSchemaExtra; + this.valueSchema = valueSchema; + this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; + this.jsonSchemaExtra = init.jsonSchemaExtra; + } + static isInstance(value) { + return typeof value === "object" && value !== null && REDUCED_VALUE_SYMBOL in value && value[REDUCED_VALUE_SYMBOL] === true; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/values/untracked.js +var UNTRACKED_VALUE_SYMBOL, UntrackedValue; +var init_untracked = __esm(() => { + UNTRACKED_VALUE_SYMBOL = Symbol.for("langgraph.state.untracked_value"); + UntrackedValue = class { + [UNTRACKED_VALUE_SYMBOL] = true; + schema; + guard; + constructor(schema, init) { + this.schema = schema; + this.guard = init?.guard ?? true; + } + static isInstance(value) { + return typeof value === "object" && value !== null && UNTRACKED_VALUE_SYMBOL in value; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js +var areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)), NamedBarrierValue, NamedBarrierValueAfterFinish; +var init_named_barrier_value = __esm(() => { + init_errors7(); + init_base15(); + NamedBarrierValue = class NamedBarrierValue2 extends BaseChannel { + lc_graph_name = "NamedBarrierValue"; + names; + seen; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set; + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValue2(this.names); + if (typeof checkpoint !== "undefined") + empty.seen = new Set(checkpoint); + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) + if (this.names.has(nodeName)) { + if (!this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } + } else + throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!areSetsEqual(this.names, this.seen)) + throw new EmptyChannelError; + } + checkpoint() { + return [...this.seen]; + } + consume() { + if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set; return true; } - this.#pendingToolStarts.set(toolCallId, tools); - return true; + return false; } - #processEvent(event) { - if (this.#processToolEvent(event)) - return; - if (event.method !== "lifecycle") - return; - const lifecycle = event; - if (lifecycle.params.data.event !== "started") - return; - const ns3 = event.params.namespace; - if (ns3.length !== this.#parentNamespace.length + 1) - return; - if (!this.#parentNamespace.every((seg, i) => ns3[i] === seg)) - return; - const nsKey2 = ns3.join("/"); - if (this.#discovered.has(nsKey2)) - return; - this.#discovered.add(nsKey2); - const lastSegment = ns3[ns3.length - 1] ?? ""; - const colonIdx = lastSegment.lastIndexOf(":"); - let name; - let index2; - if (colonIdx >= 0) { - name = lastSegment.slice(0, colonIdx); - const suffix = lastSegment.slice(colonIdx + 1); - index2 = /^\d+$/.test(suffix) ? Number(suffix) : 0; - } else { - name = lastSegment; - index2 = 0; + isAvailable() { + return !!this.names && areSetsEqual(this.names, this.seen); + } + }; + NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish2 extends BaseChannel { + lc_graph_name = "NamedBarrierValueAfterFinish"; + names; + seen; + finished; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set; + this.finished = false; + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValueAfterFinish2(this.names); + if (typeof checkpoint !== "undefined") { + const [seen, finished] = checkpoint; + empty.seen = new Set(seen); + empty.finished = finished; } - const data = lifecycle.params.data; - const cause = data.cause && typeof data.cause === "object" ? data.cause : undefined; - let toolStartedEvent; - if (cause?.type === "toolCall") { - const toolCallId = cause.tool_call_id; - if (toolCallId) { - toolStartedEvent = this.#pendingToolStarts.get(toolCallId); - this.#pendingToolStarts.delete(toolCallId); - } + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) + if (this.names.has(nodeName) && !this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } else if (!this.names.has(nodeName)) + throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!this.finished || !areSetsEqual(this.names, this.seen)) + throw new EmptyChannelError; + } + checkpoint() { + return [[...this.seen], this.finished]; + } + consume() { + if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set; + this.finished = false; + return true; } - const handle = new SubgraphHandle(name, index2, [...ns3], this.#session, { - cause, - graphName: data.graph_name, - toolStartedEvent - }); - if (cause?.type === "toolCall" && toolStartedEvent == null) { - const toolCallId = cause.tool_call_id; - if (toolCallId) - this.#pendingToolCallHandles.set(toolCallId, handle); + return false; + } + finish() { + if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { + this.finished = true; + return true; } - return handle; + return false; } - #start() { - if (this.#sourcePump) - return; - this.#sourcePump = (async () => { - for await (const event of this.#source) { - const handle = this.#processEvent(event); - if (!handle) - continue; - this.#emit(handle); - } - this.#pendingToolStarts.clear(); - this.#pendingToolCallHandles.clear(); - this.#closed = true; - while (this.#waiters.length > 0) - this.#waiters.shift()?.({ - done: true, - value: undefined - }); - })(); + isAvailable() { + return this.finished && !!this.names && areSetsEqual(this.names, this.seen); } - async close() { - this.#closed = true; - await this.#source.unsubscribe(); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/any_value.js +var init_any_value = __esm(() => { + init_errors7(); + init_base15(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js +var init_dynamic_barrier_value = __esm(() => { + init_errors7(); + init_base15(); + init_named_barrier_value(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/channels/index.js +var init_channels = __esm(() => { + init_base15(); + init_binop(); + init_last_value(); + init_topic(); + init_ephemeral_value(); + init_named_barrier_value(); + init_any_value(); + init_dynamic_barrier_value(); + init_untracked_value(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/schema.js +var STATE_SCHEMA_SYMBOL, StateSchema; +var init_schema = __esm(() => { + init_binop(); + init_last_value(); + init_types8(); + init_adapter(); + init_untracked_value(); + init_channels(); + init_reduced(); + init_untracked(); + STATE_SCHEMA_SYMBOL = Symbol.for("langgraph.state.state_schema"); + StateSchema = class { + [STATE_SCHEMA_SYMBOL] = true; + constructor(fields) { + this.fields = fields; } - [Symbol.asyncIterator]() { - this.#start(); - return { - next: async () => { - if (this.#queue.length > 0) - return { - done: false, - value: this.#queue.shift() - }; - if (this.#closed) - return { - done: true, - value: undefined - }; - return await new Promise((resolve2) => { - this.#waiters.push(resolve2); + getChannels() { + const channels = {}; + for (const [key, value] of Object.entries(this.fields)) + if (ReducedValue.isInstance(value)) { + const defaultGetter = getSchemaDefaultGetter(value.valueSchema); + channels[key] = new BinaryOperatorAggregate(value.reducer, defaultGetter); + } else if (UntrackedValue.isInstance(value)) { + const defaultGetter = value.schema ? getSchemaDefaultGetter(value.schema) : undefined; + channels[key] = new UntrackedValueChannel({ + guard: value.guard, + initialValueFactory: defaultGetter }); - }, - return: async () => { - await this.close(); - return { - done: true, - value: undefined - }; + } else if (isStandardSchema2(value)) + channels[key] = new LastValue(getSchemaDefaultGetter(value)); + else + throw new Error(`Invalid state field "${key}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`); + return channels; + } + getJsonSchema() { + const properties = {}; + const required3 = []; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (ReducedValue.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema(value.valueSchema); + if (value.jsonSchemaExtra) + fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue.isInstance(value)) + fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : undefined; + else if (isStandardSchema2(value)) + fieldSchema = getJsonSchemaFromSchema(value); + if (fieldSchema) { + properties[key] = fieldSchema; + let hasDefault = false; + if (ReducedValue.isInstance(value)) + hasDefault = getSchemaDefaultGetter(value.valueSchema) !== undefined; + else if (UntrackedValue.isInstance(value)) + hasDefault = value.schema ? getSchemaDefaultGetter(value.schema) !== undefined : false; + else + hasDefault = getSchemaDefaultGetter(value) !== undefined; + if (!hasDefault) + required3.push(key); } + } + return { + type: "object", + properties, + required: required3.length > 0 ? required3 : undefined + }; + } + getInputJsonSchema() { + const properties = {}; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (ReducedValue.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema(value.inputSchema); + if (value.jsonSchemaExtra) + fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue.isInstance(value)) + fieldSchema = value.schema ? getJsonSchemaFromSchema(value.schema) : undefined; + else if (isStandardSchema2(value)) + fieldSchema = getJsonSchemaFromSchema(value); + if (fieldSchema) + properties[key] = fieldSchema; + } + return { + type: "object", + properties }; } + getChannelKeys() { + return Object.entries(this.fields).map(([key]) => key); + } + getAllKeys() { + return Object.keys(this.fields); + } + async validateInput(data) { + if (data == null || typeof data !== "object") + return data; + const result = {}; + for (const [key, value] of Object.entries(data)) { + const fieldDef = this.fields[key]; + if (fieldDef === undefined) { + result[key] = value; + continue; + } + let schema; + if (ReducedValue.isInstance(fieldDef)) + schema = fieldDef.inputSchema; + else if (UntrackedValue.isInstance(fieldDef)) + schema = fieldDef.schema; + else if (isStandardSchema2(fieldDef)) + schema = fieldDef; + if (schema) { + const validationResult = await schema["~standard"].validate(value); + if (validationResult.issues) + throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); + result[key] = validationResult.value; + } else + result[key] = value; + } + return result; + } + static isInstance(value) { + return typeof value === "object" && value !== null && STATE_SCHEMA_SYMBOL in value && value[STATE_SCHEMA_SYMBOL] === true; + } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/index.js -var init_handles = __esm(() => { - init_tools4(); - init_subgraphs2(); - init_subagents(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/messages_reducer.js +function messagesStateReducer(left, right) { + const leftArray = Array.isArray(left) ? left : [left]; + const rightArray = Array.isArray(right) ? right : [right]; + const leftMessages = leftArray.map(coerceMessageLikeToMessage); + const rightMessages = rightArray.map(coerceMessageLikeToMessage); + for (const m of leftMessages) + if (m.id === null || m.id === undefined) { + m.id = v44(); + m.lc_kwargs.id = m.id; + } + let removeAllIdx; + for (let i = 0;i < rightMessages.length; i += 1) { + const m = rightMessages[i]; + if (m.id === null || m.id === undefined) { + m.id = v44(); + m.lc_kwargs.id = m.id; + } + if (RemoveMessage.isInstance(m) && m.id === "__remove_all__") + removeAllIdx = i; + } + if (removeAllIdx != null) + return rightMessages.slice(removeAllIdx + 1); + const merged = [...leftMessages]; + const mergedById = new Map(merged.map((m, i) => [m.id, i])); + const idsToRemove = /* @__PURE__ */ new Set; + for (const m of rightMessages) { + const existingIdx = mergedById.get(m.id); + if (existingIdx !== undefined) + if (RemoveMessage.isInstance(m)) + idsToRemove.add(m.id); + else { + idsToRemove.delete(m.id); + merged[existingIdx] = m; + } + else { + if (RemoveMessage.isInstance(m)) + throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); + mergedById.set(m.id, merged.length); + merged.push(m); + } + } + return merged.filter((m) => !idsToRemove.has(m.id)); +} +var REMOVE_ALL_MESSAGES = "__remove_all__"; +var init_messages_reducer = __esm(() => { + init_wrapper(); + init_messages(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/index.js -function coerceStateMessages(value) { - if (value == null || typeof value !== "object" || Array.isArray(value)) - return value; - const state = value; - const messages = state.messages; - if (!Array.isArray(messages) || messages.length === 0) - return value; - if (!messages.some((msg) => { - if (msg == null || typeof msg !== "object") - return false; - if (typeof msg.getType === "function") - return false; - const type = msg.type; - return typeof type === "string" && MESSAGE_LIKE_TYPES.has(type); - })) - return value; - return { - ...state, - messages: ensureMessageInstances(messages) - }; -} -function namespaceKey(ns3) { - return ns3.join("\x00"); -} -function maxSeq(current, next) { - if (next == null) - return current; - if (current == null) - return next; - return Math.max(current, next); -} -function isRootTerminalLifecycle(event) { - if (event.method !== "lifecycle") - return false; - if (event.params.namespace.length !== 0) - return false; - const data = event.params.data; - return data?.event != null && ROOT_TERMINAL_LIFECYCLE_EVENTS.has(data.event); -} -function namespaceListsEqual(a, b) { - if (a === b) - return true; - if (a === undefined || b === undefined) - return false; - if (a.length !== b.length) - return false; - const aKeys = /* @__PURE__ */ new Set; - for (const ns3 of a) - aKeys.add(namespaceKey(ns3)); - for (const ns3 of b) - if (!aKeys.has(namespaceKey(ns3))) - return false; - return true; -} -function filterEqual(a, b) { - if (a === b) - return true; - if (a == null || b == null) +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/prebuilt/messages.js +var MessagesValue; +var init_messages4 = __esm(() => { + init_reduced(); + init_messages_reducer(); + init_v43(); + MessagesValue = new ReducedValue(exports_external3.custom().default(() => []), { + inputSchema: exports_external3.custom(), + reducer: messagesStateReducer, + jsonSchemaExtra: { + langgraph_type: "messages", + description: "A list of chat messages" + } + }); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/prebuilt/index.js +var init_prebuilt = __esm(() => { + init_messages4(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/values/index.js +var init_values2 = __esm(() => { + init_reduced(); + init_untracked(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/state/index.js +var init_state = __esm(() => { + init_types8(); + init_adapter(); + init_reduced(); + init_untracked(); + init_schema(); + init_messages4(); + init_prebuilt(); + init_values2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/zod/meta.js +function withLangGraph(schema, meta3) { + if (meta3.reducer && !meta3.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) + meta3.default = defaultValueGetter; + } + if (meta3.reducer) { + const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta3.reducer?.schema ?? schema }); + schemaMetaRegistry.extend(schemaWithReducer, () => meta3); + return schemaWithReducer; + } else { + schemaMetaRegistry.extend(schema, () => meta3); + return schema; + } +} +var SchemaMetaRegistry = class { + _map = /* @__PURE__ */ new Map; + _extensionCache = /* @__PURE__ */ new Map; + get(schema) { + return this._map.get(schema); + } + extend(schema, predicate) { + const existingMeta = this.get(schema); + this._map.set(schema, predicate(existingMeta)); + } + remove(schema) { + this._map.delete(schema); + return this; + } + has(schema) { + return this._map.has(schema); + } + getChannelsForSchema(schema) { + const channels = {}; + const shape = getInteropZodObjectShape(schema); + for (const [key, channelSchema] of Object.entries(shape)) { + const meta3 = this.get(channelSchema); + if (meta3?.reducer) + channels[key] = new BinaryOperatorAggregate(meta3.reducer.fn, meta3.default); + else + channels[key] = new LastValue(meta3?.default); + } + return channels; + } + getExtendedChannelSchemas(schema, effects) { + if (Object.keys(effects).length === 0) + return schema; + const cacheKey2 = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); + const cache2 = this._extensionCache.get(cacheKey2) ?? /* @__PURE__ */ new Map; + if (cache2.has(schema)) + return cache2.get(schema); + let modifiedSchema = schema; + if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { + const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema2]) => { + const meta3 = this.get(schema2); + let outputSchema = effects.withReducerSchema ? meta3?.reducer?.schema ?? schema2 : schema2; + if (effects.withJsonSchemaExtrasAsDescription && meta3?.jsonSchemaExtra) { + const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema2); + const strExtras = JSON.stringify({ + ...meta3.jsonSchemaExtra, + description + }); + outputSchema = outputSchema.describe(`lg:${strExtras}`); + } + return [key, outputSchema]; + }); + modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); + if (isZodSchemaV3(modifiedSchema)) + modifiedSchema._def.unknownKeys = "strip"; + } + if (effects.asPartial) + modifiedSchema = interopZodObjectPartial(modifiedSchema); + cache2.set(schema, modifiedSchema); + this._extensionCache.set(cacheKey2, cache2); + return modifiedSchema; + } +}, schemaMetaRegistry; +var init_meta = __esm(() => { + init_binop(); + init_last_value(); + init_types3(); + schemaMetaRegistry = new SchemaMetaRegistry; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/types.js +function isStateDefinitionInit(value) { + if (value == null) return false; - if (a.channels.length !== b.channels.length) + if (StateSchema.isInstance(value)) + return true; + if (isInteropZodObject(value)) + return true; + if (typeof value === "object" && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot") + return true; + if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.values(value).every((v) => typeof v === "function" || isBaseChannel(v))) + return true; + return false; +} +function isStateGraphInit(value) { + if (typeof value !== "object" || value == null) return false; - const aChannels = new Set(a.channels); - for (const ch of b.channels) - if (!aChannels.has(ch)) - return false; - if (!namespaceListsEqual(a.namespaces, b.namespaces)) + const obj = value; + const hasState = "state" in obj && isStateDefinitionInit(obj.state); + const hasStateSchema = "stateSchema" in obj && isStateDefinitionInit(obj.stateSchema); + const hasInput = "input" in obj && isStateDefinitionInit(obj.input); + if (!hasState && !hasStateSchema && !hasInput) return false; - if ((a.depth ?? null) !== (b.depth ?? null)) + if ("input" in obj && obj.input != null && !isStateDefinitionInit(obj.input)) return false; - return true; -} -function isPrefix(prefix, candidate) { - if (prefix.length > candidate.length) + if ("output" in obj && obj.output != null && !isStateDefinitionInit(obj.output)) return false; - for (let i = 0;i < prefix.length; i += 1) - if (prefix[i] !== candidate[i]) - return false; return true; } -function filterCovers(coverer, target) { - const covererChannels = new Set(coverer.channels); - for (const ch of target.channels) - if (!covererChannels.has(ch)) - return false; - const covererDepth = coverer.depth; - const targetDepth = target.depth; - if (coverer.namespaces == null) { - if (covererDepth == null) - return true; - if (targetDepth == null) - return false; - return targetDepth <= covererDepth; +var init_types9 = __esm(() => { + init_constants3(); + init_base15(); + init_schema(); + init_types3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/state.js +function _getChannels(schema) { + const channels = {}; + for (const [name, val] of Object.entries(schema)) + if (name === ROOT2) + channels[name] = getChannel(val); + else + channels[name] = getChannel(val); + return channels; +} +function isStateGraphArgs(obj) { + return typeof obj === "object" && obj !== null && obj.channels !== undefined; +} +function _controlBranch(value) { + if (_isSend(value)) + return [value]; + const commands = []; + if (isCommand(value)) + commands.push(value); + else if (Array.isArray(value)) + commands.push(...value.filter(isCommand)); + const destinations = []; + for (const command of commands) { + if (command.graph === Command.PARENT) + throw new ParentCommand(command); + if (_isSend(command.goto)) + destinations.push(command.goto); + else if (typeof command.goto === "string") + destinations.push(command.goto); + else if (Array.isArray(command.goto)) + destinations.push(...command.goto); } - if (target.namespaces == null) - return false; - for (const tp of target.namespaces) - if (!coverer.namespaces.some((cp) => { - if (!isPrefix(cp, tp)) - return false; - if (covererDepth == null) - return true; - if (targetDepth == null) - return false; - return tp.length - cp.length + targetDepth <= covererDepth; - })) - return false; - return true; + return destinations; } -function normalizeSubscribeParams(paramsOrChannels, options = {}) { - if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) - return paramsOrChannels; - const channels = Array.isArray(paramsOrChannels) ? [...paramsOrChannels] : [paramsOrChannels]; - return { - ...options, - channels - }; +function _getControlBranch() { + return new Branch({ path: new RunnableCallable({ + func: _controlBranch, + tags: [TAG_HIDDEN], + trace: false, + recurse: false, + name: "" + }) }); } -var MESSAGE_LIKE_TYPES, ROOT_TERMINAL_LIFECYCLE_EVENTS, SubscriptionHandle, ThreadStream = class { - threadId; - ordering = {}; - run; - agent; - input; - state; - interrupted = false; - interrupts = []; - assistantId; - #nextCommandId; - #transportAdapter; - #pending = /* @__PURE__ */ new Map; - #subscriptions = /* @__PURE__ */ new Map; - #seenEventIds = /* @__PURE__ */ new Set; - #headlessInterruptsAwaitingTerminal = /* @__PURE__ */ new Set; - #closed = false; - #opened = false; - #openPromise; - #sharedStream = null; - #sharedStreamFilter = null; - #rotationState = "idle"; - #pendingSubResolves = []; - #terminalPauseTimer; - #terminalPauseSeq; - #lifecycleSubId = null; - #lifecycleStartPromise; - #lifecycleWatcherHandle = null; - #lifecycleWatcherStartPromise; - #onEventListeners = /* @__PURE__ */ new Set; - #messagesIterable; - #valuesProjection; - #toolCallsIterable; - #subgraphsIterable; - #subagentsIterable; - #outputPromise; - #extensionsProxy; - #extensionsCache = /* @__PURE__ */ new Map; - #extensionsDispatcherStarted = false; - #extensionsEnded = false; - #extensionsEvents = []; - #extensionsEventListeners = []; - #extensionsEndListeners = []; - #mediaDispatcherStarted = false; - #mediaAssembler; - #mediaHandles = /* @__PURE__ */ new Set; - #audioBuffer = new MultiCursorBuffer; - #imagesBuffer = new MultiCursorBuffer; - #videoBuffer = new MultiCursorBuffer; - #filesBuffer = new MultiCursorBuffer; - #fetchOption; - constructor(transportAdapter, options) { - if (!options?.assistantId) - throw new Error("ThreadStream requires an assistantId option."); - this.#transportAdapter = transportAdapter; - this.threadId = transportAdapter.threadId; - this.assistantId = options.assistantId; - this.#nextCommandId = options.startingCommandId ?? 1; - this.#fetchOption = options.fetch; - this.run = { start: async (params) => { - this.#prepareForNextRun(); - this.#ensureLifecycleTracking(); - this.values; - return await this.#send("run.start", { - ...params, - assistant_id: this.assistantId - }); - } }; - this.agent = { getTree: async (params = {}) => await this.#send("agent.getTree", params) }; - this.input = { - respond: async (params) => { - this.#prepareForNextRun(); - this.#ensureLifecycleTracking(); - this.values; - await this.#send("input.respond", params); - }, - inject: async (params) => { - await this.#send("input.inject", params); +var ROOT2 = "__root__", PartialStateSchema, StateGraph, CompiledStateGraph; +var init_state2 = __esm(() => { + init_constants3(); + init_errors7(); + init_last_value(); + init_annotation(); + init_utils8(); + init_write(); + init_read(); + init_subgraph(); + init_ephemeral_value(); + init_graph2(); + init_named_barrier_value(); + init_schema(); + init_state(); + init_meta(); + init_types9(); + init_runnables(); + init_types3(); + PartialStateSchema = Symbol.for("langgraph.state.partial"); + StateGraph = class extends Graph$1 { + channels = {}; + waitingEdges = /* @__PURE__ */ new Set; + _schemaDefinition; + _schemaRuntimeDefinition; + _inputDefinition; + _inputRuntimeDefinition; + _outputDefinition; + _outputRuntimeDefinition; + _schemaDefinitions = /* @__PURE__ */ new Map; + _metaRegistry = schemaMetaRegistry; + _configSchema; + _configRuntimeSchema; + _interrupt; + _writer; + constructor(stateOrInit, options) { + super(); + const init = this._normalizeToStateGraphInit(stateOrInit, options); + const stateSchema = init.state ?? init.stateSchema ?? init.input; + if (!stateSchema) + throw new StateGraphInputError; + const stateChannelDef = this._getChannelsFromSchema(stateSchema); + this._schemaDefinition = stateChannelDef; + if (StateSchema.isInstance(stateSchema)) + this._schemaRuntimeDefinition = stateSchema; + else if (isInteropZodObject(stateSchema)) + this._schemaRuntimeDefinition = stateSchema; + if (init.input) + if (StateSchema.isInstance(init.input)) + this._inputRuntimeDefinition = init.input; + else if (isInteropZodObject(init.input)) + this._inputRuntimeDefinition = init.input; + else + this._inputRuntimeDefinition = PartialStateSchema; + else + this._inputRuntimeDefinition = PartialStateSchema; + if (init.output) + if (StateSchema.isInstance(init.output)) + this._outputRuntimeDefinition = init.output; + else if (isInteropZodObject(init.output)) + this._outputRuntimeDefinition = init.output; + else + this._outputRuntimeDefinition = this._schemaRuntimeDefinition; + else + this._outputRuntimeDefinition = this._schemaRuntimeDefinition; + const inputChannelDef = init.input ? this._getChannelsFromSchema(init.input) : stateChannelDef; + const outputChannelDef = init.output ? this._getChannelsFromSchema(init.output) : stateChannelDef; + this._inputDefinition = inputChannelDef; + this._outputDefinition = outputChannelDef; + this._addSchema(this._schemaDefinition); + this._addSchema(this._inputDefinition); + this._addSchema(this._outputDefinition); + if (init.context) { + if (isInteropZodObject(init.context)) + this._configRuntimeSchema = init.context; } - }; - this.state = { - get: async (params) => await this.#send("state.get", params), - listCheckpoints: async (params) => await this.#send("state.listCheckpoints", params), - fork: async (params) => await this.#send("state.fork", params) - }; - if (this.#transportAdapter.openEventStream == null) - this.#consumeEvents(); - } - async#ensureOpen() { - if (this.#opened) - return; - if (this.#openPromise == null) - this.#openPromise = this.#transportAdapter.open().then(() => { - this.#opened = true; - }); - await this.#openPromise; - } - #lifecycleChannels() { - return ["lifecycle", "input"]; - } - #ensureLifecycleTracking() { - if (this.#lifecycleStartPromise != null) - return; - this.#lifecycleStartPromise = (async () => { - this.#lifecycleSubId = (await this.#subscribeRaw({ channels: this.#lifecycleChannels() })).subscriptionId; - })().catch(() => { - return; - }); - } - #prepareForNextRun() { - this.interrupted = false; - this.interrupts.length = 0; - if (this.#terminalPauseTimer != null) { - clearTimeout(this.#terminalPauseTimer); - this.#terminalPauseTimer = undefined; + this._interrupt = init.interrupt; + this._writer = init.writer; } - this.#terminalPauseSeq = undefined; - for (const [id, subscription] of this.#subscriptions) - if (id !== this.#lifecycleSubId) - subscription.resume(); - } - get messages() { - if (this.#messagesIterable) - return this.#messagesIterable; - const buffer = new MultiCursorBuffer; - this.#messagesIterable = buffer; - const assembler = new StreamingMessageAssembler; - this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { - if (event.method !== "messages") - return; - const msg = assembler.consume(event); - if (msg) - buffer.push(toStreamingMessageHandle(msg)); - }, () => buffer.close()); - return buffer; - } - get values() { - if (this.#valuesProjection) - return this.#valuesProjection; - const buffer = new MultiCursorBuffer; - let lastValue; - let resolveOutput; - const outputPromise = new Promise((resolve2) => { - resolveOutput = resolve2; - }); - this.#outputPromise = outputPromise; - const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); - this.#valuesProjection = projection; - this.#startProjection(["values", ...this.#lifecycleChannels()], (event) => { - if (event.method !== "values") - return; - const data = coerceStateMessages(event.params.data); - lastValue = data; - buffer.push(data); - }, () => { - resolveOutput(lastValue); - buffer.close(); - }); - return projection; - } - get toolCalls() { - if (this.#toolCallsIterable) - return this.#toolCallsIterable; - const buffer = new MultiCursorBuffer; - this.#toolCallsIterable = buffer; - const assembler = new ToolCallAssembler; - this.#startProjection(["tools", ...this.#lifecycleChannels()], (event) => { - if (event.method !== "tools") - return; - const tc = assembler.consume(event); - if (tc) - buffer.push(tc); - }, () => buffer.close()); - return buffer; - } - get subgraphs() { - if (this.#subgraphsIterable) - return this.#subgraphsIterable; - const buffer = new MultiCursorBuffer; - this.#subgraphsIterable = buffer; - (async () => { - const discovery = new SubgraphDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this, []); - for await (const sub of discovery) - buffer.push(sub); - buffer.close(); - })(); - return buffer; - } - get subagents() { - if (this.#subagentsIterable) - return this.#subagentsIterable; - const buffer = new MultiCursorBuffer; - this.#subagentsIterable = buffer; - (async () => { - const discovery = new SubagentDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this); - for await (const sub of discovery) - buffer.push(sub); - buffer.close(); - })(); - return buffer; - } - get audio() { - this.#ensureMediaDispatcher(); - return this.#audioBuffer; - } - get images() { - this.#ensureMediaDispatcher(); - return this.#imagesBuffer; - } - get video() { - this.#ensureMediaDispatcher(); - return this.#videoBuffer; - } - get files() { - this.#ensureMediaDispatcher(); - return this.#filesBuffer; - } - get output() { - this.values; - return this.#outputPromise; - } - get extensions() { - if (this.#extensionsProxy) - return this.#extensionsProxy; - const cache2 = this.#extensionsCache; - const createExtension = (name) => this.#createExtension(name); - this.#extensionsProxy = new Proxy(Object.create(null), { - get: (_target, prop) => { - if (typeof prop !== "string") - return; - const cached2 = cache2.get(prop); - if (cached2) - return cached2; - const extension = createExtension(prop); - cache2.set(prop, extension); - return extension; - }, - has: (_target, prop) => typeof prop === "string" - }); - return this.#extensionsProxy; - } - #ensureExtensionsDispatcher() { - if (this.#extensionsDispatcherStarted) - return; - this.#extensionsDispatcherStarted = true; - this.#startProjection(["custom", ...this.#lifecycleChannels()], (event) => { - if (event.method !== "custom") - return; - this.#extensionsEvents.push(event); - for (const listener of this.#extensionsEventListeners) - listener(event); - }, () => { - this.#extensionsEnded = true; - const listeners = this.#extensionsEndListeners.splice(0); - for (const listener of listeners) - listener(); - }, { endOnRootTerminal: true }); - } - #ensureMediaDispatcher() { - if (this.#mediaDispatcherStarted) - return; - this.#mediaDispatcherStarted = true; - const assembler = new MediaAssembler({ - fetch: this.#fetchOption, - onAudio: (m) => { - this.#mediaHandles.add(m); - this.#audioBuffer.push(m); - }, - onImage: (m) => { - this.#mediaHandles.add(m); - this.#imagesBuffer.push(m); - }, - onVideo: (m) => { - this.#mediaHandles.add(m); - this.#videoBuffer.push(m); - }, - onFile: (m) => { - this.#mediaHandles.add(m); - this.#filesBuffer.push(m); + _normalizeToStateGraphInit(stateOrInit, options) { + if (isStateGraphInit(stateOrInit)) { + if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) + return { + ...stateOrInit, + context: options + }; + const opts = options; + return { + ...stateOrInit, + input: stateOrInit.input ?? opts?.input, + output: stateOrInit.output ?? opts?.output, + context: stateOrInit.context ?? opts?.context, + interrupt: stateOrInit.interrupt ?? opts?.interrupt, + writer: stateOrInit.writer ?? opts?.writer, + nodes: stateOrInit.nodes ?? opts?.nodes + }; } - }); - this.#mediaAssembler = assembler; - this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { - if (event.method !== "messages") - return; - assembler.consume(event); - }, () => { - assembler.close(); - this.#audioBuffer.close(); - this.#imagesBuffer.close(); - this.#videoBuffer.close(); - this.#filesBuffer.close(); - }); - } - #createExtension(name) { - this.#ensureExtensionsDispatcher(); - const buffer = new MultiCursorBuffer; - let lastValue; - let resolveFinal; - const finalPromise = new Promise((resolve2) => { - resolveFinal = resolve2; - }); - const handleEvent = (event) => { - const data = event.params.data; - if (data?.name !== name) - return; - lastValue = data.payload; - buffer.push(data.payload); - }; - for (const event of this.#extensionsEvents) - handleEvent(event); - this.#extensionsEventListeners.push(handleEvent); - const settle = () => { - resolveFinal(lastValue); - buffer.close(); - }; - if (this.#extensionsEnded) - settle(); - else - this.#extensionsEndListeners.push(settle); - return Object.assign(buffer, { then: (onfulfilled, onrejected) => finalPromise.then(onfulfilled, onrejected) }); - } - async#startProjection(channels, onEvent, onDone, options = {}) { - let endTimer; - let rawHandle; - try { - rawHandle = await this.#subscribeRaw({ channels }); - const handle = rawHandle; - for await (const event of handle) { - onEvent(event); - if (options.endOnRootTerminal && endTimer == null && isRootTerminalLifecycle(event)) - endTimer = setTimeout(() => { - endTimer = undefined; - handle.unsubscribe().catch(() => { - return; - }); - }, 0); + if (isStateDefinitionInit(stateOrInit)) { + if (isInteropZodObject(options) || AnnotationRoot.isInstance(options)) + return { + state: stateOrInit, + context: options + }; + const opts = options; + return { + state: stateOrInit, + input: opts?.input, + output: opts?.output, + context: opts?.context, + interrupt: opts?.interrupt, + writer: opts?.writer, + nodes: opts?.nodes + }; } - } catch {} finally { - if (endTimer != null) - clearTimeout(endTimer); - onDone(); - } - } - async submitRun(params) { - this.#prepareForNextRun(); - this.#startLifecycleWatcher(); - return await this.#send("run.start", { - ...params, - assistant_id: this.assistantId - }); - } - async respondInput(params) { - this.#prepareForNextRun(); - this.#startLifecycleWatcher(); - await this.#send("input.respond", params); - } - onEvent(listener) { - this.#onEventListeners.add(listener); - return () => { - this.#onEventListeners.delete(listener); - }; - } - #startLifecycleWatcher() { - if (this.#lifecycleWatcherStartPromise != null) - return; - if (this.#transportAdapter.openEventStream != null) { - this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherSse(); - return; + if (isStateGraphArgs(stateOrInit)) + return { state: _getChannels(stateOrInit.channels) }; + throw new StateGraphInputError; } - this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherWebSocket(); - } - async#startLifecycleWatcherSse() { - const filter = { channels: ["lifecycle", "input"] }; - let handle; - try { - handle = this.#transportAdapter.openEventStream(filter); - } catch { - return; + _getChannelsFromSchema(schema) { + if (StateSchema.isInstance(schema)) + return schema.getChannels(); + if (isInteropZodObject(schema)) + return this._metaRegistry.getChannelsForSchema(schema); + if (typeof schema === "object" && "lc_graph_name" in schema && schema.lc_graph_name === "AnnotationRoot") + return schema.spec; + if (typeof schema === "object" && !Array.isArray(schema) && Object.keys(schema).length > 0) + return schema; + throw new StateGraphInputError("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition."); } - try { - await handle.ready; - } catch { - try { - handle.close(); - } catch {} - return; + get allEdges() { + return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); } - if (this.#closed) { - try { - handle.close(); - } catch {} - return; + _addSchema(stateDefinition) { + if (this._schemaDefinitions.has(stateDefinition)) + return; + this._schemaDefinitions.set(stateDefinition, stateDefinition); + for (const [key, val] of Object.entries(stateDefinition)) { + let channel; + if (typeof val === "function") + channel = val(); + else + channel = val; + if (this.channels[key] !== undefined) { + if (!this.channels[key].equals(channel)) { + if (channel.lc_graph_name !== "LastValue") + throw new Error(`Channel "${key}" already exists with a different type.`); + } + } else + this.channels[key] = channel; + } } - this.#lifecycleWatcherHandle = handle; - try { - for await (const message of handle.events) { - if (this.#closed) - break; - this.#handleLifecycleWatcherMessage(message); + addNode(...args) { + function isMultipleNodes(args2) { + return args2.length >= 1 && typeof args2[0] !== "string"; } - } catch {} - } - async#startLifecycleWatcherWebSocket() { - let handle; - try { - handle = await this.#subscribeRaw({ channels: ["lifecycle", "input"] }); - } catch { - return; + const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) + throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + if (key in this.channels) + throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); + for (const reservedChar of ["|", ":"]) + if (key.includes(reservedChar)) + throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) + throw new Error(`Node \`${key}\` already present.`); + if (key === "__end__" || key === "__start__") + throw new Error(`Node \`${key}\` is reserved.`); + let inputSpec = this._schemaDefinition; + if (options?.input !== undefined) + inputSpec = this._getChannelsFromSchema(options.input); + this._addSchema(inputSpec); + let runnable; + if (Runnable.isRunnable(action)) + runnable = action; + else if (typeof action === "function") + runnable = new RunnableCallable({ + func: action, + name: key, + trace: false + }); + else + runnable = _coerceToRunnable(action); + let cachePolicy = options?.cachePolicy; + if (typeof cachePolicy === "boolean") + cachePolicy = cachePolicy ? {} : undefined; + const nodeSpec = { + runnable, + retryPolicy: options?.retryPolicy, + cachePolicy, + metadata: options?.metadata, + input: inputSpec ?? this._schemaDefinition, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends, + defer: options?.defer + }; + this.nodes[key] = nodeSpec; + } + return this; } - if (this.#closed) { - try { - handle.close(); - } catch {} - return; + addEdge(startKey, endKey) { + if (typeof startKey === "string") + return super.addEdge(startKey, endKey); + if (this.compiled) + console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + for (const start of startKey) { + if (start === "__end__") + throw new Error("END cannot be a start node"); + if (!Object.keys(this.nodes).some((node) => node === start)) + throw new Error(`Need to add a node named "${start}" first`); + } + if (endKey === "__end__") + throw new Error("END cannot be an end node"); + if (!Object.keys(this.nodes).some((node) => node === endKey)) + throw new Error(`Need to add a node named "${endKey}" first`); + this.waitingEdges.add([startKey, endKey]); + return this; } - try { - for await (const _event of handle) - if (this.#closed) - break; - } catch {} - } - #handleLifecycleWatcherMessage(message) { - if (message.type !== "event") - return; - if (typeof message.seq === "number") - this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); - if (message.event_id) - this.ordering.lastEventId = message.event_id; - const eventId = message.event_id ?? undefined; - const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); - if (eventId != null) - this.#seenEventIds.add(eventId); - if (globallyProcessed) - return; - this.#applyThreadLevelEffects(message); - this.#fireOnEvent(message); - } - #applyThreadLevelEffects(event) { - if (event.method === "lifecycle") { - if (event.params.data.event === "interrupted") - this.interrupted = true; + addSequence(nodes) { + const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); + if (parsedNodes.length === 0) + throw new Error("Sequence requires at least one node."); + let previousNode; + for (const [key, action, options] of parsedNodes) { + if (key in this.nodes) + throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); + const validKey = key; + this.addNode(validKey, action, options); + if (previousNode != null) + this.addEdge(previousNode, validKey); + previousNode = validKey; + } + return this; } - if (event.method === "input.requested") { - const data = event.params.data; - const interruptId = data.interrupt_id ?? `interrupt_${this.interrupts.length}`; - this.interrupts.push({ - interruptId, - payload: data.payload, - namespace: [...event.params.namespace] + compile({ checkpointer, store, cache: cache2, interruptBefore, interruptAfter, name, description, transformers } = {}) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); + const outputChannels = outputKeys.length === 1 && outputKeys[0] === ROOT2 ? ROOT2 : outputKeys; + const streamKeys = Object.keys(this.channels); + const streamChannels = streamKeys.length === 1 && streamKeys[0] === ROOT2 ? ROOT2 : streamKeys; + const userInterrupt = this._interrupt; + const compiled = new CompiledStateGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + ...this.channels, + [START]: new EphemeralValue + }, + inputChannels: START, + outputChannels, + streamChannels, + streamMode: "updates", + store, + cache: cache2, + name, + description, + userInterrupt, + streamTransformers: transformers }); - if (isHeadlessToolInterrupt(data.payload)) - this.#headlessInterruptsAwaitingTerminal.add(interruptId); - } - } - #fireOnEvent(event) { - if (this.#onEventListeners.size === 0) - return; - for (const listener of this.#onEventListeners) - try { - listener(event); - } catch {} - } - async close() { - if (this.#closed) - return; - this.#closed = true; - if (this.#terminalPauseTimer != null) { - clearTimeout(this.#terminalPauseTimer); - this.#terminalPauseTimer = undefined; - } - this.#terminalPauseSeq = undefined; - for (const pending of this.#pendingSubResolves) - pending.reject(/* @__PURE__ */ new Error("ThreadStream closed")); - this.#pendingSubResolves.length = 0; - if (this.#sharedStream != null) { - try { - this.#sharedStream.close(); - } catch {} - this.#sharedStream = null; - this.#sharedStreamFilter = null; + compiled.attachNode(START); + for (const [key, node] of Object.entries(this.nodes)) + compiled.attachNode(key, node); + compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); + for (const [key] of Object.entries(this.nodes)) + compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); + for (const [start, end] of this.edges) + compiled.attachEdge(start, end); + for (const [starts, end] of this.waitingEdges) + compiled.attachEdge(starts, end); + for (const [start, branches] of Object.entries(this.branches)) + for (const [name2, branch] of Object.entries(branches)) + compiled.attachBranch(start, name2, branch); + return compiled.validate(); } - if (this.#lifecycleWatcherHandle != null) { - try { - this.#lifecycleWatcherHandle.close(); - } catch {} - this.#lifecycleWatcherHandle = null; + }; + CompiledStateGraph = class extends CompiledGraph { + description; + _metaRegistry = schemaMetaRegistry; + constructor({ description, ...rest }) { + super(rest); + this.description = description; } - const lifecycleWatcherStartPromise = this.#lifecycleWatcherStartPromise; - this.#lifecycleWatcherStartPromise = undefined; - this.#onEventListeners.clear(); - for (const subscription of this.#subscriptions.values()) - subscription.close(); - this.#subscriptions.clear(); - try { - await lifecycleWatcherStartPromise; - } catch {} - for (const handle of this.#mediaHandles) - try { - handle.revoke(); - } catch {} - this.#mediaHandles.clear(); - this.#mediaAssembler?.close(); - this.#audioBuffer.close(); - this.#imagesBuffer.close(); - this.#videoBuffer.close(); - this.#filesBuffer.close(); - await this.#transportAdapter.close(); - } - async subscribe(paramsOrChannels, options = {}) { - const isParamsObject = typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels; - const params = normalizeSubscribeParams(paramsOrChannels, options); - return await this.#subscribeRaw(params, { unwrapNamedCustom: !isParamsObject }); - } - async#subscribeRaw(params, options = {}) { - await this.#ensureOpen(); - const { unwrapNamedCustom = true } = options; - const hasOnlyNamedCustom = params.channels.length > 0 && params.channels.every((ch) => ch.startsWith("custom:")); - const transform2 = unwrapNamedCustom && hasOnlyNamedCustom ? (event) => event.params.data?.payload ?? event : undefined; - if (this.#transportAdapter.openEventStream != null) - return this.#subscribeViaSharedStream(params, transform2); - return this.#subscribeViaCommand(params, transform2); - } - async#subscribeViaSharedStream(params, transform2) { - const subscriptionId = `sse-${this.#nextCommandId++}`; - const handle = new SubscriptionHandle(subscriptionId, params, async (id) => { - this.#subscriptions.delete(id); - this.#scheduleReconcile(); - }, transform2); - const subscription = Object.assign(handle, { - filter: params, - registeredAfterSeq: this.ordering.lastSeenSeq, - seenEventIds: /* @__PURE__ */ new Set - }); - this.#subscriptions.set(subscriptionId, subscription); - const covered = new Promise((resolve2, reject) => { - this.#pendingSubResolves.push({ - filter: params, - resolve: resolve2, - reject - }); - }); - this.#scheduleReconcile(); - try { - await covered; - } catch (err) { - this.#subscriptions.delete(subscriptionId); - throw err; - } - return handle; - } - #computeUnionFilter() { - if (this.#subscriptions.size === 0) - return null; - const channels = /* @__PURE__ */ new Set; - let wildcardNamespaces = false; - const namespaceMap = /* @__PURE__ */ new Map; - let unboundedDepth = false; - let maxDepth = 0; - for (const sub of this.#subscriptions.values()) { - for (const ch of sub.filter.channels) - channels.add(ch); - if (sub.filter.namespaces == null) - wildcardNamespaces = true; - else if (!wildcardNamespaces) - for (const ns3 of sub.filter.namespaces) - namespaceMap.set(namespaceKey(ns3), ns3); - if (sub.filter.depth == null) - unboundedDepth = true; - else if (!unboundedDepth && sub.filter.depth > maxDepth) - maxDepth = sub.filter.depth; - } - const result = { channels: [...channels] }; - if (!wildcardNamespaces) - result.namespaces = [...namespaceMap.values()]; - if (!unboundedDepth) - result.depth = maxDepth; - return result; - } - #scheduleReconcile() { - if (this.#closed) - return; - if (this.#rotationState !== "idle") - return; - this.#rotationState = "scheduled"; - queueMicrotask(() => { - if (this.#closed) { - this.#rotationState = "idle"; - return; + attachNode(key, node) { + let outputKeys; + if (key === "__start__") + outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); + else + outputKeys = Object.keys(this.builder.channels); + function _getRoot(input) { + if (isCommand(input)) { + if (input.graph === Command.PARENT) + return null; + return input._updateAsTuples(); + } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { + const updates = []; + for (const i of input) + if (isCommand(i)) { + if (i.graph === Command.PARENT) + continue; + updates.push(...i._updateAsTuples()); + } else + updates.push([ROOT2, i]); + return updates; + } else if (input != null) + return [[ROOT2, input]]; + return null; } - this.#rotationState = "idle"; - this.#reconcileStream().catch(() => { - this.#rotationState = "idle"; - }); - }); - } - async#reconcileStream() { - if (this.#closed) - return; - if (this.#rotationState === "rotating") - return; - const desired = this.#computeUnionFilter(); - if (desired == null) - return; - if (this.#sharedStreamFilter != null && filterEqual(desired, this.#sharedStreamFilter) && this.#pendingSubResolves.length === 0) { - this.#resolvePending(); - return; - } - this.#rotationState = "rotating"; - let newHandle; - try { - newHandle = this.#transportAdapter.openEventStream(desired); - } catch (err) { - this.#rotationState = "idle"; - this.#rejectUncoveredPending(err); - return; - } - try { - await newHandle.ready; - } catch (err) { - this.#rotationState = "idle"; - try { - newHandle.close(); - } catch {} - this.#rejectUncoveredPending(err); - return; - } - if (this.#closed) { - try { - newHandle.close(); - } catch {} - this.#rotationState = "idle"; - return; - } - this.#pumpStream(newHandle); - const oldHandle = this.#sharedStream; - this.#sharedStream = newHandle; - this.#sharedStreamFilter = desired; - if (oldHandle != null) - try { - oldHandle.close(); - } catch {} - this.#rotationState = "idle"; - this.#resolvePending(); - const next = this.#computeUnionFilter(); - if (next != null && !filterEqual(next, this.#sharedStreamFilter)) - this.#scheduleReconcile(); - } - async#pumpStream(handle) { - try { - for await (const message of handle.events) { - if (this.#closed) - break; - this.#handleIncoming(message); + const nodeKey = key; + function _getUpdates(input) { + if (!input) + return null; + else if (isCommand(input)) { + if (input.graph === Command.PARENT) + return null; + return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); + } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { + const updates = []; + for (const item of input) + if (isCommand(item)) { + if (item.graph === Command.PARENT) + continue; + updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); + } else { + const itemUpdates = _getUpdates(item); + if (itemUpdates) + updates.push(...itemUpdates ?? []); + } + return updates; + } else if (typeof input === "object" && !Array.isArray(input)) + return Object.entries(input).filter(([k]) => outputKeys.includes(k)); + else { + const typeofInput = Array.isArray(input) ? "array" : typeof input; + throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); + } } - } catch (err) { - if (handle === this.#sharedStream && !this.#closed) - this.#failThreadWithError(err); - } - } - #resolvePending() { - if (this.#sharedStreamFilter == null) - return; - const current = this.#sharedStreamFilter; - if (this.#pendingSubResolves.length === 0) - return; - const stillPending = []; - for (const pending of this.#pendingSubResolves) - if (filterCovers(current, pending.filter)) - pending.resolve(); - else - stillPending.push(pending); - this.#pendingSubResolves.length = 0; - this.#pendingSubResolves.push(...stillPending); - } - #rejectUncoveredPending(err) { - if (this.#pendingSubResolves.length === 0) - return; - const current = this.#sharedStreamFilter; - const stillPending = []; - for (const pending of this.#pendingSubResolves) - if (current != null && filterCovers(current, pending.filter)) - pending.resolve(); - else - stillPending.push(pending); - this.#pendingSubResolves.length = 0; - for (const pending of stillPending) - pending.reject(err); - } - #failThreadWithError(err) { - const normalized = err instanceof Error ? err : new Error(String(err)); - for (const pending of this.#pending.values()) - pending.reject(normalized); - this.#pending.clear(); - for (const pending of this.#pendingSubResolves) - pending.reject(normalized); - this.#pendingSubResolves.length = 0; - for (const subscription of this.#subscriptions.values()) - subscription.close(); - } - async#subscribeViaCommand(params, transform2) { - const result = await this.#send("subscription.subscribe", params); - const handle = new SubscriptionHandle(result.subscription_id, params, async (id) => { - this.#subscriptions.delete(id); - if (!this.#closed) - await this.#send("subscription.unsubscribe", { subscription_id: id }).catch((err) => { - if (err instanceof ProtocolError2 && err.code === "no_such_subscription") - return; - throw err; + const stateWriteEntries = [{ + value: PASSTHROUGH, + mapper: new RunnableCallable({ + func: outputKeys.length && outputKeys[0] === ROOT2 ? _getRoot : _getUpdates, + trace: false, + recurse: false + }) + }]; + if (key === "__start__") + this.nodes[key] = new PregelNode({ + tags: [TAG_HIDDEN], + triggers: [START], + channels: [START], + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] }); - }, transform2); - const subscription = Object.assign(handle, { - filter: params, - registeredAfterSeq: this.ordering.lastSeenSeq, - seenEventIds: /* @__PURE__ */ new Set - }); - this.#subscriptions.set(result.subscription_id, subscription); - return handle; - } - async#consumeEvents() { - try { - for await (const message of this.#transportAdapter.events()) - this.#handleIncoming(message); - for (const subscription of this.#subscriptions.values()) - subscription.close(); - } catch (error51) { - const normalized = error51 instanceof Error ? error51 : new Error(String(error51)); - for (const pending of this.#pending.values()) - pending.reject(normalized); - for (const subscription of this.#subscriptions.values()) - subscription.close(); - this.#pending.clear(); + else { + const inputDefinition = node?.input ?? this.builder._schemaDefinition; + const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); + const isSingleInput = Object.keys(inputValues).length === 1 && ROOT2 in inputValues; + const branchChannel = `branch:to:${key}`; + this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish : new EphemeralValue(false); + this.nodes[key] = new PregelNode({ + triggers: [branchChannel], + channels: isSingleInput ? Object.keys(inputValues) : inputValues, + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], + mapper: isSingleInput ? undefined : (input) => { + return Object.fromEntries(Object.entries(input).filter(([k]) => (k in inputValues))); + }, + bound: node?.runnable, + metadata: node?.metadata, + retryPolicy: node?.retryPolicy, + cachePolicy: node?.cachePolicy, + subgraphs: node?.subgraphs, + ends: node?.ends + }); + } } - } - #scheduleTerminalPause(terminalSeq) { - if (this.#terminalPauseTimer != null) - clearTimeout(this.#terminalPauseTimer); - this.#terminalPauseSeq = terminalSeq ?? null; - this.#terminalPauseTimer = setTimeout(() => { - this.#terminalPauseTimer = undefined; - if (this.#closed) + attachEdge(starts, end) { + if (end === "__end__") return; - for (const [id, subscription] of this.#subscriptions) { - if (id === this.#lifecycleSubId) - continue; - if (terminalSeq != null && subscription.registeredAfterSeq != null && subscription.registeredAfterSeq >= terminalSeq) - continue; - subscription.pause(); - } - }, 0); - } - #handleIncoming(message) { - if (message.type === "event") { - if (typeof message.seq === "number") - this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); - if (message.event_id) - this.ordering.lastEventId = message.event_id; - const eventId = message.event_id ?? undefined; - const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); - if (eventId != null) - this.#seenEventIds.add(eventId); - const TERMINAL_LIFECYCLE_EVENTS = new Set([ - "interrupted", - "completed", - "failed" - ]); - if (!globallyProcessed) { - this.#applyThreadLevelEffects(message); - this.#fireOnEvent(message); + if (typeof starts === "string") + this.nodes[starts].writers.push(new ChannelWrite([{ + channel: `branch:to:${end}`, + value: null + }], [TAG_HIDDEN])); + else if (Array.isArray(starts)) { + const channelName = `join:${starts.join("+")}:${end}`; + this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); + this.nodes[end].triggers.push(channelName); + for (const start of starts) + this.nodes[start].writers.push(new ChannelWrite([{ + channel: channelName, + value: start + }], [TAG_HIDDEN])); } - let fannedToAny = false; - for (const subscription of this.#subscriptions.values()) { - if (!matchesSubscription(message, subscription.filter)) - continue; - if (eventId != null) { - if (subscription.seenEventIds.has(eventId)) - continue; - subscription.seenEventIds.add(eventId); + } + attachBranch(start, _, branch, options = { withReader: true }) { + const branchWriter = async (packets, config3) => { + const filteredPackets = packets.filter((p) => p !== END); + if (!filteredPackets.length) + return; + const writes = filteredPackets.map((p) => { + if (_isSend(p)) + return p; + return { + channel: p === "__end__" ? p : `branch:to:${p}`, + value: start + }; + }); + await ChannelWrite.doWrite({ + ...config3, + tags: (config3.tags ?? []).concat([TAG_HIDDEN]) + }, writes); + }; + this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config3) => ChannelRead.doRead(config3, this.streamChannels ?? this.outputChannels, true) : undefined)); + } + async _validateInput(input) { + if (input == null) + return input; + const inputDef = this.builder._inputRuntimeDefinition; + const schemaDef = this.builder._schemaRuntimeDefinition; + if (StateSchema.isInstance(inputDef)) { + if (isCommand(input)) { + const parsedInput = input; + if (input.update) + parsedInput.update = await inputDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); + return parsedInput; } - subscription.push(message); - fannedToAny = true; + return await inputDef.validateInput(input); } - if (fannedToAny && this.#terminalPauseSeq !== undefined && !(message.method === "lifecycle" && message.params.namespace.length === 0)) { - const eventSeq = typeof message.seq === "number" ? message.seq : undefined; - const terminalSeq = this.#terminalPauseSeq; - if (terminalSeq === null || eventSeq == null || eventSeq > terminalSeq) { - if (this.#terminalPauseTimer != null) { - clearTimeout(this.#terminalPauseTimer); - this.#terminalPauseTimer = undefined; - } - for (const [id, subscription] of this.#subscriptions) - if (id !== this.#lifecycleSubId) - subscription.resume(); - this.#scheduleTerminalPause(terminalSeq === null ? undefined : terminalSeq); + if (inputDef === PartialStateSchema && StateSchema.isInstance(schemaDef)) { + if (isCommand(input)) { + const parsedInput = input; + if (input.update) + parsedInput.update = await schemaDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); + return parsedInput; } + return await schemaDef.validateInput(input); } - if (fannedToAny && message.method === "lifecycle" && message.params.namespace.length === 0 && TERMINAL_LIFECYCLE_EVENTS.has(message.params.data.event)) { - if (message.params.data.event === "interrupted" && this.#headlessInterruptsAwaitingTerminal.size > 0) { - this.#headlessInterruptsAwaitingTerminal.clear(); + const schema = (() => { + const apply = (schema2) => { + if (schema2 == null) + return; + return this._metaRegistry.getExtendedChannelSchemas(schema2, { withReducerSchema: true }); + }; + if (isInteropZodObject(inputDef)) + return apply(inputDef); + if (inputDef === PartialStateSchema) { + if (isInteropZodObject(schemaDef)) + return interopZodObjectPartial(apply(schemaDef)); return; } - this.#scheduleTerminalPause(typeof message.seq === "number" ? message.seq : undefined); - } - return; - } - const messageId = typeof message.id === "number" ? message.id : undefined; - const pending = messageId === undefined ? undefined : this.#pending.get(messageId); - if (!pending) - return; - if (messageId !== undefined) - this.#pending.delete(messageId); - if (message.type === "error") { - pending.reject(new ProtocolError2(message)); - return; - } - if (typeof message.meta?.applied_through_seq === "number") - this.ordering.lastAppliedThroughSeq = message.meta.applied_through_seq; - pending.resolve(message); - } - async#send(method, params) { - await this.#ensureOpen(); - const id = this.#nextCommandId++; - const command = { - id, - method, - params - }; - const responsePromise = new Promise((resolve2, reject) => { - this.#pending.set(id, { - resolve: resolve2, - reject - }); - }); - const immediate = await this.#transportAdapter.send(command); - if (immediate) { - this.#pending.delete(id); - if (immediate.type === "error") - throw new ProtocolError2(immediate); - if (typeof immediate.meta?.applied_through_seq === "number") - this.ordering.lastAppliedThroughSeq = immediate.meta.applied_through_seq; - return immediate.result; - } - return (await responsePromise).result; - } -}; -var init_stream8 = __esm(() => { - init_subscription(); - init_multi_cursor_buffer(); - init_messages6(); - init_tools4(); - init_messages5(); - init_media(); - init_subgraphs2(); - init_subagents(); - init_handles(); - init_error4(); - init_constants5(); - init_headless_tools(); - MESSAGE_LIKE_TYPES = new Set([ - "human", - "user", - "ai", - "assistant", - "tool", - "system", - "function", - "remove" - ]); - ROOT_TERMINAL_LIFECYCLE_EVENTS = new Set([ - "completed", - "failed", - "interrupted" - ]); - SubscriptionHandle = class { - subscriptionId; - params; - queue = []; - waiters = []; - closed = false; - paused = false; - resumeResolve; - onUnsubscribe; - transform; - constructor(subscriptionId, params, onUnsubscribe, transform2) { - this.subscriptionId = subscriptionId; - this.params = params; - this.onUnsubscribe = onUnsubscribe; - this.transform = transform2 ?? ((event) => event); - } - push(event) { - if (this.closed) - return; - const value = this.transform(event); - const waiter = this.waiters.shift(); - if (waiter) { - waiter({ - done: false, - value - }); - return; + })(); + if (isCommand(input)) { + const parsedInput = input; + if (input.update && schema != null) + parsedInput.update = interopParse(schema, input.update); + return parsedInput; } - this.queue.push(value); - } - pause() { - if (this.closed) - return; - this.paused = true; - while (this.waiters.length > 0) - this.waiters.shift()?.({ - done: true, - value: undefined - }); - } - resume() { - this.paused = false; - this.resumeResolve?.(); - this.resumeResolve = undefined; - } - waitForResume() { - if (!this.paused) - return Promise.resolve(); - return new Promise((resolve2) => { - this.resumeResolve = resolve2; - }); - } - get isPaused() { - return this.paused; - } - close() { - this.closed = true; - this.paused = false; - while (this.waiters.length > 0) - this.waiters.shift()?.({ - done: true, - value: undefined - }); - this.resumeResolve?.(); - this.resumeResolve = undefined; + if (schema != null) + return interopParse(schema, input); + return input; } - async unsubscribe() { - if (this.closed) - return; - this.close(); - await this.onUnsubscribe(this.subscriptionId); + isInterrupted(input) { + return isInterrupted(input); } - [Symbol.asyncIterator]() { - return { - next: async () => { - if (this.queue.length > 0) - return { - done: false, - value: this.queue.shift() - }; - if (this.closed || this.paused) - return { - done: true, - value: undefined - }; - return await new Promise((resolve2) => { - this.waiters.push(resolve2); - }); - }, - return: async () => { - this.close(); - return { - done: true, - value: undefined - }; - } - }; + async _validateContext(config3) { + const configSchema = this.builder._configRuntimeSchema; + if (isInteropZodObject(configSchema)) + interopParse(configSchema, config3); + return config3; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/queue.js -var AsyncQueue = class { - values = []; - waiters = []; - rejecters = []; - closed = false; - error = null; - push(value) { - if (this.closed) - return; - const waiter = this.waiters.shift(); - this.rejecters.shift(); - if (waiter) { - waiter({ - done: false, - value - }); - return; - } - this.values.push(value); - } - close(error51) { - if (this.closed) - return; - this.closed = true; - this.error = error51 == null ? null : error51 instanceof Error ? error51 : new Error(String(error51)); - if (this.error) { - for (const rejecter of this.rejecters.splice(0)) - rejecter(this.error); - this.waiters.length = 0; - return; - } - for (const waiter of this.waiters.splice(0)) - waiter({ - done: true, - value: undefined - }); - this.rejecters.length = 0; - } - async shift() { - if (this.values.length > 0) - return { - done: false, - value: this.values.shift() - }; - if (this.error) - throw this.error; - if (this.closed) - return { - done: true, - value: undefined - }; - return await new Promise((resolve2, reject) => { - this.waiters.push(resolve2); - this.rejecters.push(reject); - }); - } -}; -var init_queue = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/utils.js -function mergeHeaders2(...headerGroups) { - const merged = new Headers; - for (const group of headerGroups) { - if (!group) - continue; - if (group instanceof Headers) { - group.forEach((value, key) => { - merged.set(key, value); - }); - continue; - } - if (Array.isArray(group)) { - for (const [key, value] of group) - if (value == null) - merged.delete(key); - else - merged.set(key, value); - continue; - } - for (const [key, value] of Object.entries(group)) - if (value == null) - merged.delete(key); - else - merged.set(key, value); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/message.js +function pushMessage(message, options) { + const { stateKey: userStateKey, ...userConfig } = options ?? {}; + const config3 = ensureLangGraphConfig(userConfig); + let stateKey = userStateKey ?? "messages"; + if (userStateKey === null) + stateKey = undefined; + const validMessage = coerceMessageLikeToMessage(message); + if (!validMessage.id) + throw new Error("Message ID is required."); + const messagesHandler = (() => { + if (Array.isArray(config3.callbacks)) + return config3.callbacks; + if (typeof config3.callbacks !== "undefined") + return config3.callbacks.handlers; + return []; + })().find((cb) => ("name" in cb) && cb.name === "StreamMessagesHandler"); + if (messagesHandler) { + const metadata = config3.metadata ?? {}; + const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); + messagesHandler._emit([namespace, metadata], validMessage, undefined, false); } - return merged; + if (stateKey) + config3.configurable?.__pregel_send?.([[stateKey, validMessage]]); + return validMessage; } -function isProtocolResponse(value) { - return isRecord2(value) && typeof value.type === "string" && (value.type === "success" || value.type === "error"); -} -var isRecord2 = (value) => typeof value === "object" && value !== null, toAbsoluteUrl = (apiUrl, path2) => new URL(path2, apiUrl.endsWith("/") ? apiUrl : `${apiUrl}/`), toError = (error51) => error51 instanceof Error ? error51 : new Error(String(error51)), toWebSocketUrl = (apiUrl) => { - const url2 = new URL(apiUrl); - url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:"; - url2.search = ""; - url2.hash = ""; - return url2.toString(); -}, hasHeaders = (headers) => Object.values(headers ?? {}).some((value) => value != null); -var init_utils14 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/constants.js -var TRAILING_NEWLINE2; -var init_constants6 = __esm(() => { - TRAILING_NEWLINE2 = [13, 10]; +var MessageGraph; +var init_message2 = __esm(() => { + init_config2(); + init_messages_reducer(); + init_state2(); + init_messages(); + MessageGraph = class extends StateGraph { + constructor() { + super({ channels: { __root__: { + reducer: messagesStateReducer, + default: () => [] + } } }); + } + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/decoder.js -function joinArrays2(data) { - const totalLength = data.reduce((acc, curr) => acc + curr.length, 0); - const merged = new Uint8Array(totalLength); - let offset = 0; - for (const chunk of data) { - merged.set(chunk, offset); - offset += chunk.length; - } - return merged; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/func/index.js +function task(optionsOrName, func) { + const options = typeof optionsOrName === "string" ? { + name: optionsOrName, + retry: undefined, + cachePolicy: undefined + } : optionsOrName; + const { name, retry } = options; + if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) + throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); + const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : undefined); + let cache2; + if (typeof cachePolicy === "boolean") + cache2 = cachePolicy ? {} : undefined; + else + cache2 = cachePolicy; + return (...args) => { + return call({ + func, + name, + retry, + cache: cache2 + }, ...args); + }; } -function decodeArraysToJson2(decoder, data) { - return JSON.parse(decoder.decode(joinArrays2(data))); +function getPreviousState() { + return AsyncLocalStorageProviderSingleton2.getRunnableConfig().configurable?.[CONFIG_KEY_PREVIOUS_STATE]; } -function BytesLineDecoder2() { - let buffer = []; - let trailingCr = false; - return new TransformStream({ - start() { - buffer = []; - trailingCr = false; - }, - transform(chunk, controller) { - let text = chunk; - if (trailingCr) { - text = joinArrays2([[13], text]); - trailingCr = false; - } - if (text.length > 0 && text.at(-1) === 13) { - trailingCr = true; - text = text.subarray(0, -1); - } - if (!text.length) - return; - const trailingNewline = TRAILING_NEWLINE2.includes(text.at(-1)); - const lastIdx = text.length - 1; - const { lines } = text.reduce((acc, cur, idx) => { - if (acc.from > idx) - return acc; - if (cur === 13 || cur === 10) { - acc.lines.push(text.subarray(acc.from, idx)); - if (cur === 13 && text[idx + 1] === 10) - acc.from = idx + 2; - else - acc.from = idx + 1; - } - if (idx === lastIdx && acc.from <= lastIdx) - acc.lines.push(text.subarray(acc.from)); - return acc; - }, { - lines: [], - from: 0 - }); - if (lines.length === 1 && !trailingNewline) { - buffer.push(lines[0]); - return; - } - if (buffer.length) { - buffer.push(lines[0]); - lines[0] = joinArrays2(buffer); - buffer = []; - } - if (!trailingNewline && lines.length) - buffer = [lines.pop()]; - for (const line of lines) - controller.enqueue(line); - }, - flush(controller) { - if (buffer.length) - controller.enqueue(joinArrays2(buffer)); +var entrypoint = function entrypoint2(optionsOrName, func) { + const { name, checkpointer, store, cache: cache2 } = typeof optionsOrName === "string" ? { + name: optionsOrName, + checkpointer: undefined, + store: undefined + } : optionsOrName; + if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) + throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); + const streamMode = "updates"; + const bound = getRunnableForEntrypoint(name, func); + function isEntrypointFinal(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; + } + const pluckReturnValue = new RunnableCallable({ + name: "pluckReturnValue", + func: (value) => { + return isEntrypointFinal(value) ? value.value : value; } }); -} -function SSEDecoder2() { - let event = ""; - let data = []; - let lastEventId = ""; - let retry = null; - const decoder = new TextDecoder; - return new TransformStream({ - transform(chunk, controller) { - if (!chunk.length) { - if (!event && !data.length && !lastEventId && retry == null) - return; - controller.enqueue({ - id: lastEventId || undefined, - event, - data: data.length ? decodeArraysToJson2(decoder, data) : null - }); - event = ""; - data = []; - retry = null; - return; - } - if (chunk[0] === 58) - return; - const sepIdx = chunk.indexOf(58); - if (sepIdx === -1) - return; - const fieldName = decoder.decode(chunk.subarray(0, sepIdx)); - let value = chunk.subarray(sepIdx + 1); - if (value[0] === 32) - value = value.subarray(1); - if (fieldName === "event") - event = decoder.decode(value); - else if (fieldName === "data") - data.push(value); - else if (fieldName === "id") { - if (value.indexOf(0) === -1) - lastEventId = decoder.decode(value); - } else if (fieldName === "retry") { - const retryNum = Number.parseInt(decoder.decode(value), 10); - if (!Number.isNaN(retryNum)) - retry = retryNum; - } - }, - flush(controller) { - if (event) - controller.enqueue({ - id: lastEventId || undefined, - event, - data: data.length ? decodeArraysToJson2(decoder, data) : null - }); + const pluckSaveValue = new RunnableCallable({ + name: "pluckSaveValue", + func: (value) => { + return isEntrypointFinal(value) ? value.save : value; } }); -} -var init_decoder = __esm(() => { - init_constants6(); + const entrypointNode = new PregelNode({ + bound, + triggers: [START], + channels: [START], + writers: [new ChannelWrite([{ + channel: END, + value: PASSTHROUGH, + mapper: pluckReturnValue + }, { + channel: PREVIOUS, + value: PASSTHROUGH, + mapper: pluckSaveValue + }], [TAG_HIDDEN])] + }); + return new Pregel({ + name, + checkpointer, + nodes: { [name]: entrypointNode }, + channels: { + [START]: new EphemeralValue, + [END]: new LastValue, + [PREVIOUS]: new LastValue + }, + inputChannels: START, + outputChannels: END, + streamChannels: END, + streamMode, + store, + cache: cache2 + }); +}; +var init_func = __esm(() => { + init_constants3(); + init_last_value(); + init_utils8(); + init_write(); + init_read(); + init_call(); + init_pregel(); + init_ephemeral_value(); + init_singletons(); + entrypoint.final = function final({ value, save }) { + return { + value, + save, + __lg_type: "__pregel_final" + }; + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/stream.js -var IterableReadableStream3; -var init_stream9 = __esm(() => { - IterableReadableStream3 = class IterableReadableStream4 extends ReadableStream { - reader; - ensureReader() { - if (!this.reader) - this.reader = this.getReader(); - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); - return { - done: true, - value: undefined - }; - } - return { - done: false, - value: result.value - }; - } catch (error51) { - this.reader.releaseLock(); - throw error51; - } - } - async return() { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - return { - done: true, - value: undefined - }; - } - async throw(error51) { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - throw error51; - } - async[Symbol.asyncDispose]() { - await this.return(); - } - [Symbol.asyncIterator]() { - return this; - } - static fromReadableStream(stream2) { - const reader = stream2.getReader(); - return new IterableReadableStream4({ - start(controller) { - return pump2(); - function pump2() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump2(); - }); - } - }, - cancel() { - reader.releaseLock(); - } - }); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/messages_annotation.js +var MessagesAnnotation, MessagesZodMeta, MessagesZodState; +var init_messages_annotation = __esm(() => { + init_annotation(); + init_messages_reducer(); + init_meta(); + init_v3(); + MessagesAnnotation = Annotation.Root({ messages: Annotation({ + reducer: messagesStateReducer, + default: () => [] + }) }); + MessagesZodMeta = { + reducer: { fn: messagesStateReducer }, + jsonSchemaExtra: { langgraph_type: "messages" }, + default: () => [] }; + MessagesZodState = exports_external2.object({ messages: withLangGraph(exports_external2.custom(), MessagesZodMeta) }); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/http.js -var ProtocolSseTransportAdapter = class { - threadId; - queue = new AsyncQueue; - fetchImpl; - apiUrl; - defaultHeaders; - onRequest; - fetchFactory; - commandsUrl; - streamUrl; - sessionAbortController = new AbortController; - eventStreams = /* @__PURE__ */ new Set; - closed = false; - constructor(options) { - this.fetchImpl = options.fetch ?? fetch; - this.apiUrl = options.apiUrl; - this.defaultHeaders = options.defaultHeaders ?? {}; - this.onRequest = options.onRequest; - this.fetchFactory = options.fetchFactory; - this.threadId = options.threadId; - this.commandsUrl = options.paths?.commands ?? `/threads/${this.threadId}/commands`; - this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; - } - async resolveFetch() { - if (this.fetchFactory) - return await this.fetchFactory(); - return this.fetchImpl; - } - async open() {} - async send(command) { - const response = await this.request(this.commandsUrl, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(command), - signal: this.sessionAbortController.signal - }); - if (response.status === 202 || response.status === 204) - return; - const payload = await response.json(); - if (!isProtocolResponse(payload)) - throw new Error("Protocol command did not return a valid response."); - return payload; - } - events() { - const queue2 = this.queue; - return { [Symbol.asyncIterator]: () => ({ - next: async () => await queue2.shift(), - return: async () => { - queue2.close(); - return { - done: true, - value: undefined - }; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/writer.js +function writer(chunk) { + const config3 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (!config3) + throw new Error("Called interrupt() outside the context of a graph."); + const conf = config3.configurable; + if (!conf) + throw new Error("No configurable found in config"); + return conf.writer?.(chunk); +} +var init_writer = __esm(() => { + init_singletons(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/index.js +var init_graph3 = __esm(() => { + init_constants3(); + init_annotation(); + init_graph2(); + init_messages_reducer(); + init_state2(); + init_message2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/web.js +var init_web = __esm(() => { + init_constants3(); + init_errors7(); + init_base15(); + init_binop(); + init_annotation(); + init_config2(); + init_stream_channel(); + init_convert(); + init_lifecycle(); + init_messages2(); + init_subgraphs(); + init_values(); + init_types6(); + init_run_stream(); + init_stream4(); + init_interrupt(); + init_graph2(); + init_types8(); + init_adapter(); + init_untracked_value(); + init_channels(); + init_reduced(); + init_untracked(); + init_schema(); + init_messages_reducer(); + init_messages4(); + init_state(); + init_state2(); + init_message2(); + init_graph3(); + init_func(); + init_messages_annotation(); + init_writer(); + init_dist3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/index.js +var exports_dist = {}; +__export(exports_dist, { + writer: () => writer, + task: () => task, + pushMessage: () => pushMessage, + messagesStateReducer: () => messagesStateReducer, + isStandardSchema: () => isStandardSchema2, + isSerializableSchema: () => isSerializableSchema2, + isParentCommand: () => isParentCommand, + isNativeTransformer: () => isNativeTransformer, + isInterrupted: () => isInterrupted, + isGraphInterrupt: () => isGraphInterrupt, + isGraphBubbleUp: () => isGraphBubbleUp, + isCommand: () => isCommand, + interrupt: () => interrupt, + getWriter: () => getWriter, + getSubgraphsSeenSet: () => getSubgraphsSeenSet, + getStore: () => getStore, + getSchemaDefaultGetter: () => getSchemaDefaultGetter, + getPreviousState: () => getPreviousState, + getJsonSchemaFromSchema: () => getJsonSchemaFromSchema, + getCurrentTaskInput: () => getCurrentTaskInput, + getConfig: () => getConfig, + filterSubgraphHandles: () => filterSubgraphHandles, + filterLifecycleEntries: () => filterLifecycleEntries, + entrypoint: () => entrypoint, + emptyCheckpoint: () => emptyCheckpoint, + createValuesTransformer: () => createValuesTransformer, + createSubgraphDiscoveryTransformer: () => createSubgraphDiscoveryTransformer, + createMessagesTransformer: () => createMessagesTransformer, + createLifecycleTransformer: () => createLifecycleTransformer, + createGraphRunStream: () => createGraphRunStream, + copyCheckpoint: () => copyCheckpoint, + convertToProtocolEvent: () => convertToProtocolEvent, + addMessages: () => messagesStateReducer, + UntrackedValueChannel: () => UntrackedValueChannel, + UntrackedValue: () => UntrackedValue, + UnreachableNodeError: () => UnreachableNodeError, + SubgraphRunStream: () => SubgraphRunStream, + StreamChannel: () => StreamChannel, + StateSchema: () => StateSchema, + StateGraphInputError: () => StateGraphInputError, + StateGraph: () => StateGraph, + Send: () => Send, + STREAM_EVENTS_V3_MODES: () => STREAM_EVENTS_V3_MODES, + START: () => START, + RemoteException: () => RemoteException, + ReducedValue: () => ReducedValue, + REMOVE_ALL_MESSAGES: () => REMOVE_ALL_MESSAGES, + ParentCommand: () => ParentCommand, + Overwrite: () => Overwrite, + NodeInterrupt: () => NodeInterrupt, + MultipleSubgraphsError: () => MultipleSubgraphsError, + MessagesZodState: () => MessagesZodState, + MessagesZodMeta: () => MessagesZodMeta, + MessagesValue: () => MessagesValue, + MessagesAnnotation: () => MessagesAnnotation, + MessageGraph: () => MessageGraph, + MemorySaver: () => MemorySaver, + InvalidUpdateError: () => InvalidUpdateError, + InMemoryStore: () => InMemoryStore2, + INTERRUPT: () => INTERRUPT, + GraphValueError: () => GraphValueError, + GraphRunStream: () => GraphRunStream, + GraphRecursionError: () => GraphRecursionError, + GraphInterrupt: () => GraphInterrupt, + GraphBubbleUp: () => GraphBubbleUp, + Graph: () => Graph$1, + EventLog: () => StreamChannel, + EmptyInputError: () => EmptyInputError, + EmptyChannelError: () => EmptyChannelError, + END: () => END, + CompiledStateGraph: () => CompiledStateGraph, + CommandInstance: () => CommandInstance, + Command: () => Command, + ChatModelStreamImpl: () => ChatModelStream, + COMMAND_SYMBOL: () => COMMAND_SYMBOL, + BinaryOperatorAggregate: () => BinaryOperatorAggregate, + BaseStore: () => BaseStore2, + BaseLangGraphError: () => BaseLangGraphError, + BaseCheckpointSaver: () => BaseCheckpointSaver, + BaseChannel: () => BaseChannel, + AsyncBatchedStore: () => AsyncBatchedStore, + Annotation: () => Annotation +}); +var init_dist4 = __esm(() => { + init_async_local_storage2(); + init_constants3(); + init_errors7(); + init_base15(); + init_binop(); + init_annotation(); + init_config2(); + init_stream_channel(); + init_convert(); + init_lifecycle(); + init_messages2(); + init_subgraphs(); + init_values(); + init_types6(); + init_run_stream(); + init_stream4(); + init_interrupt(); + init_graph2(); + init_types8(); + init_adapter(); + init_untracked_value(); + init_reduced(); + init_untracked(); + init_schema(); + init_messages_reducer(); + init_messages4(); + init_state2(); + init_message2(); + init_func(); + init_messages_annotation(); + init_writer(); + init_web(); + initializeAsyncLocalStorageSingleton(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/tools/headless.js +function createHeadlessTool(fields) { + const { name, description, schema } = fields; + const wrappedTool = tool(async (args, config3) => { + const { interrupt: interrupt2 } = await Promise.resolve().then(() => (init_dist4(), exports_dist)); + return interrupt2({ + type: "tool", + toolCall: { + id: config3?.toolCall?.id, + name, + args } - }) }; - } - openEventStream(params) { - if (this.closed) - throw new Error("Protocol transport is closed."); - const ac = new AbortController; - this.eventStreams.add(ac); - const streamQueue = new AsyncQueue; - const streamUrl = this.streamUrl; - let resolveReady; - let rejectReady; - const ready = new Promise((resolve2, reject) => { - resolveReady = resolve2; - rejectReady = reject; }); - const since = params.since; - const startStream = async () => { - try { - const response = await this.request(streamUrl, { - method: "POST", - headers: { - "content-type": "application/json", - accept: "text/event-stream" - }, - body: JSON.stringify({ - channels: params.channels, - ...params.namespaces ? { namespaces: params.namespaces } : {}, - ...params.depth != null ? { depth: params.depth } : {}, - ...typeof since === "number" ? { since } : {} - }), - signal: ac.signal - }); - resolveReady(); - const stream2 = (response.body ?? new ReadableStream({ start(controller) { - controller.close(); - } })).pipeThrough(BytesLineDecoder2()).pipeThrough(SSEDecoder2()); - const iterable = IterableReadableStream3.fromReadableStream(stream2); - for await (const event of iterable) { - if (ac.signal.aborted || this.closed) - break; - if (isRecord2(event.data)) { - const msg = event.data; - streamQueue.push(msg); - } - } - streamQueue.close(); - } catch (error51) { - rejectReady(error51); - if (ac.signal.aborted || this.closed) { - streamQueue.close(); - return; - } - streamQueue.close(error51); - } - }; - startStream(); - const cleanup = () => { - this.eventStreams.delete(ac); - ac.abort(); - streamQueue.close(); - }; - return { - events: { [Symbol.asyncIterator]: () => ({ - next: async () => await streamQueue.shift(), - return: async () => { - cleanup(); - return { - done: true, - value: undefined - }; - } - }) }, - ready, - close: cleanup - }; - } - async close() { - if (this.closed) - return; - this.closed = true; - this.sessionAbortController.abort(); - for (const ac of this.eventStreams) - ac.abort(); - this.eventStreams.clear(); - this.queue.close(); - } - async request(path2, init) { - const url2 = toAbsoluteUrl(this.apiUrl, path2); - let requestInit = { - ...init, - headers: mergeHeaders2(this.defaultHeaders, init.headers) - }; - if (this.onRequest) - requestInit = await this.onRequest(url2, requestInit); - try { - const response = await (await this.resolveFetch())(url2.toString(), requestInit); - if (!response.ok) { - let detail = ""; - try { - const body = await response.text(); - const parsed = JSON.parse(body); - if (typeof parsed === "object" && parsed != null) - detail = parsed.message ?? parsed.error ?? ""; - if (!detail) - detail = body; - } catch {} - const message = detail ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}` : `Protocol request failed: ${response.status} ${response.statusText}`; - throw new Error(message); - } - return response; - } catch (error51) { - throw toError(error51); - } - } + }, { + name, + description, + schema, + metadata: { headlessTool: true } + }); + const headlessTool = Object.assign(wrappedTool, { implement: (execute) => ({ + tool: headlessTool, + execute + }) }); + return headlessTool; +} +var tool$1 = (funcOrFields, fields) => { + if (typeof funcOrFields !== "function") + return createHeadlessTool(funcOrFields); + return tool(funcOrFields, fields); }; -var init_http = __esm(() => { - init_queue(); - init_utils14(); - init_decoder(); - init_stream9(); +var init_headless = __esm(() => { + init_tools2(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/websocket.js -var ProtocolWebSocketTransportAdapter = class { - threadId; - queue = new AsyncQueue; - apiUrl; - defaultHeaders; - onRequest; - webSocketFactory; - streamUrl; - pending = /* @__PURE__ */ new Map; - socket = null; - closed = false; - intentionalClose = false; - constructor(options) { - this.apiUrl = options.apiUrl; - this.threadId = options.threadId; - this.defaultHeaders = options.defaultHeaders; - this.onRequest = options.onRequest; - this.webSocketFactory = options.webSocketFactory ?? ((url2) => new WebSocket(url2)); - this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; - } - async open() { - if (this.socket != null) - return; - this.assertBrowserSafeTransportConfig(); - const wsUrl = toWebSocketUrl(new URL(this.streamUrl, this.apiUrl.endsWith("/") ? this.apiUrl : `${this.apiUrl}/`).toString()); - const socket = this.webSocketFactory(wsUrl); - this.socket = socket; - this.closed = false; - this.intentionalClose = false; - socket.addEventListener("message", this.handleMessage); - socket.addEventListener("close", this.handleClose); - socket.addEventListener("error", this.handleSocketError); - await new Promise((resolve2, reject) => { - const onOpen = () => { - cleanup(); - resolve2(); - }; - const onError2 = () => { - cleanup(); - reject(/* @__PURE__ */ new Error("Failed to open protocol WebSocket.")); - }; - const cleanup = () => { - socket.removeEventListener("open", onOpen); - socket.removeEventListener("error", onError2); - }; - socket.addEventListener("open", onOpen, { once: true }); - socket.addEventListener("error", onError2, { once: true }); - }); - } - async send(command) { - return await this.sendCommand(command); - } - events() { - const queue2 = this.queue; - return { [Symbol.asyncIterator]: () => ({ - next: async () => await queue2.shift(), - return: async () => { - queue2.close(); - return { - done: true, - value: undefined - }; - } - }) }; - } - async close() { - if (this.closed) - return; - this.closed = true; - this.intentionalClose = true; - for (const { reject } of this.pending.values()) - reject(/* @__PURE__ */ new Error("Protocol WebSocket connection closed.")); - this.pending.clear(); - this.queue.close(); - const socket = this.socket; - this.socket = null; - if (!socket) - return; - await new Promise((resolve2) => { - if (socket.readyState === WebSocket.CLOSED) { - resolve2(); - return; - } - const onClose = () => { - socket.removeEventListener("close", onClose); - resolve2(); - }; - socket.addEventListener("close", onClose, { once: true }); - if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) - socket.close(); - else - resolve2(); - }); - } - assertBrowserSafeTransportConfig() { - if (hasHeaders(this.defaultHeaders) || this.onRequest != null) - throw new Error("Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup."); - } - async sendCommand(command) { - const socket = this.socket; - if (socket == null || socket.readyState !== WebSocket.OPEN) - throw new Error("Protocol WebSocket is not open."); - return await new Promise((resolve2, reject) => { - this.pending.set(command.id, { - resolve: resolve2, - reject - }); - try { - socket.send(JSON.stringify(command)); - } catch (error51) { - this.pending.delete(command.id); - reject(toError(error51)); - } - }); - } - handleMessage = (event) => { - let payload; - try { - payload = JSON.parse(String(event.data)); - } catch { - return; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/errors.js +var MultipleToolsBoundError, MultipleStructuredOutputsError, StructuredOutputParsingError, ToolInvocationError, MiddlewareError; +var init_errors8 = __esm(() => { + init_dist4(); + MultipleToolsBoundError = class extends Error { + constructor() { + super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter."); } - if (isRecord2(payload) && typeof payload.id === "number" && (payload.type === "success" || payload.type === "error")) { - const pending = this.pending.get(payload.id); - if (pending) { - this.pending.delete(payload.id); - pending.resolve(payload); - } - return; + }; + MultipleStructuredOutputsError = class extends Error { + toolNames; + constructor(toolNames) { + super(`The model has called multiple tools: ${toolNames.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`); + this.toolNames = toolNames; } - if (isRecord2(payload) && payload.type === "event") - this.queue.push(payload); }; - handleClose = () => { - this.socket = null; - if (this.intentionalClose || this.closed) { - this.queue.close(); - return; + StructuredOutputParsingError = class extends Error { + toolName; + errors; + constructor(toolName, errors6) { + super(`Failed to parse structured output for tool '${toolName}':${errors6.map((e) => ` + - ${e}`).join("")}.`); + this.toolName = toolName; + this.errors = errors6; } - const error51 = /* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly."); - for (const { reject } of this.pending.values()) - reject(error51); - this.pending.clear(); - this.queue.close(error51); }; - handleSocketError = () => { - if (this.closed || this.intentionalClose) - return; - const error51 = /* @__PURE__ */ new Error("Protocol WebSocket encountered an error."); - for (const { reject } of this.pending.values()) - reject(error51); - this.pending.clear(); - this.queue.close(error51); + ToolInvocationError = class extends Error { + toolCall; + toolError; + constructor(toolError, toolCall) { + const error90 = toolError instanceof Error ? toolError : new Error(String(toolError)); + const toolArgs = JSON.stringify(toolCall.args); + super(`Error invoking tool '${toolCall.name}' with kwargs ${toolArgs} with error: ${error90.stack} + Please fix the error and try again.`); + this.toolCall = toolCall; + this.toolError = error90; + } + }; + MiddlewareError = class MiddlewareError2 extends Error { + static "~brand" = "MiddlewareError"; + constructor(error90, middlewareName) { + const errorMessage = error90 instanceof Error ? error90.message : String(error90); + super(errorMessage); + this.name = error90 instanceof Error ? error90.name : `${middlewareName[0].toUpperCase() + middlewareName.slice(1)}Error`; + if (error90 instanceof Error) + this.cause = error90; + } + static wrap(error90, middlewareName) { + if (isGraphBubbleUp(error90)) + return error90; + return new MiddlewareError2(error90, middlewareName); + } + static isInstance(error90) { + return error90 instanceof Error && "~brand" in error90 && error90["~brand"] === "MiddlewareError"; + } }; -}; -var init_websocket = __esm(() => { - init_queue(); - init_utils14(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/agent-server.js -var HttpAgentServerAdapter = class { - threadId; - #delegate; - constructor(options) { - this.threadId = options.threadId; - this.#delegate = options.webSocketFactory != null ? new ProtocolWebSocketTransportAdapter({ - apiUrl: options.apiUrl, - threadId: options.threadId, - defaultHeaders: options.defaultHeaders, - onRequest: options.onRequest, - paths: options.paths, - webSocketFactory: options.webSocketFactory - }) : new ProtocolSseTransportAdapter({ - apiUrl: options.apiUrl, - threadId: options.threadId, - defaultHeaders: options.defaultHeaders, - onRequest: options.onRequest, - fetch: options.fetch, - paths: options.paths - }); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/model.js +function isBaseChatModel(model) { + return "invoke" in model && typeof model.invoke === "function" && "_streamResponseChunks" in model; +} +function isConfigurableModel(model) { + return typeof model === "object" && model != null && "_queuedMethodOperations" in model && "_getModelInstance" in model && typeof model._getModelInstance === "function"; +} +var init_model = () => {}; + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/responses.js +function transformResponseFormat(responseFormat, options, model) { + if (!responseFormat) + return []; + if (typeof responseFormat === "object" && responseFormat !== null && "__responseFormatUndefined" in responseFormat) + return []; + if (Array.isArray(responseFormat)) { + if (responseFormat.every((item) => item instanceof ToolStrategy || item instanceof ProviderStrategy)) + return responseFormat; + if (responseFormat.every((item) => isSerializableSchema(item))) + return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + if (responseFormat.every((item) => isInteropZodObject(item))) + return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + if (responseFormat.every((item) => typeof item === "object" && item !== null && !isInteropZodObject(item) && !isSerializableSchema(item))) + return responseFormat.map((item) => ToolStrategy.fromSchema(item, options)); + throw new Error(`Invalid response format: list contains mixed types. +All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`); } - open() { - return this.#delegate.open(); + if (responseFormat instanceof ToolStrategy || responseFormat instanceof ProviderStrategy) + return [responseFormat]; + const useProviderStrategy = hasSupportForJsonSchemaOutput(model); + if (isSerializableSchema(responseFormat)) + return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + if (isInteropZodObject(responseFormat)) + return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + if (typeof responseFormat === "object" && responseFormat !== null && "properties" in responseFormat) + return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)]; + throw new Error(`Invalid response format: ${String(responseFormat)}`); +} +function hasSupportForJsonSchemaOutput(model) { + if (!model || !isBaseChatModel(model) || !("profile" in model) || typeof model.profile !== "object" || !model.profile) + return false; + return "structuredOutput" in model.profile && model.profile.structuredOutput === true; +} +var PROVIDER_STRATEGY_DEFAULT_STRICT = true, bindingIdentifier = 0, ToolStrategy = class ToolStrategy2 { + constructor(schema, tool2, options) { + this.schema = schema; + this.tool = tool2; + this.options = options; } - send(command) { - return this.#delegate.send(command); + get name() { + return this.tool.function.name; } - events() { - return this.#delegate.events(); + static fromSchema(schema, outputOptions) { + function getFunctionName(name) { + return name ?? `extract-${++bindingIdentifier}`; + } + if (isSerializableSchema(schema) || isInteropZodSchema(schema)) { + const asJsonSchema = toJsonSchema(schema); + return new ToolStrategy2(asJsonSchema, { + type: "function", + function: { + name: getFunctionName(asJsonSchema.title), + strict: false, + description: asJsonSchema.description ?? "Tool for extracting structured output from the model's response.", + parameters: asJsonSchema + } + }, outputOptions); + } + let functionDefinition; + if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) + functionDefinition = schema; + else + functionDefinition = { + name: getFunctionName(schema.title), + description: schema.description ?? "", + parameters: schema.schema || schema + }; + return new ToolStrategy2(toJsonSchema(schema), { + type: "function", + function: functionDefinition + }, outputOptions); } - openEventStream(params) { - if (this.#delegate.openEventStream == null) - throw new Error("HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path)."); - return this.#delegate.openEventStream(params); + parse(toolArgs) { + const result = new Validator(this.schema).validate(toolArgs); + if (!result.valid) + throw new StructuredOutputParsingError(this.name, result.errors.map((e) => e.error)); + return toolArgs; } - close() { - return this.#delegate.close(); +}, ProviderStrategy = class ProviderStrategy2 { + _schemaType; + schema; + strict; + constructor(schemaOrOptions, strict) { + if ("schema" in schemaOrOptions && typeof schemaOrOptions.schema === "object" && schemaOrOptions.schema !== null && !("type" in schemaOrOptions)) { + const options = schemaOrOptions; + this.schema = options.schema; + this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; + } else { + this.schema = schemaOrOptions; + this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT; + } + } + static fromSchema(schema, strict) { + return new ProviderStrategy2(toJsonSchema(schema), strict); + } + parse(response) { + let textContent; + if (typeof response.content === "string") + textContent = response.content; + else if (Array.isArray(response.content)) { + for (const block of response.content) + if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") { + textContent = block.text; + break; + } + } + if (!textContent || textContent === "") + return; + try { + const content = JSON.parse(textContent); + if (!new Validator(this.schema).validate(content).valid) + return; + return content; + } catch {} } }; -var init_agent_server = __esm(() => { - init_http(); - init_websocket(); +var init_responses = __esm(() => { + init_model(); + init_errors8(); + init_types3(); + init_json_schema3(); + init_standard_schema(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/assistants/index.js -var AssistantsClient; -var init_assistants = __esm(() => { - init_base16(); - AssistantsClient = class extends BaseClient { - async get(assistantId, options) { - return this.fetch(`/assistants/${assistantId}`, { signal: options?.signal }); - } - async getGraph(assistantId, options) { - return this.fetch(`/assistants/${assistantId}/graph`, { - params: { xray: options?.xray }, - signal: options?.signal - }); - } - async getSchemas(assistantId, options) { - return this.fetch(`/assistants/${assistantId}/schemas`, { signal: options?.signal }); - } - async getSubgraphs(assistantId, options) { - if (options?.namespace) - return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, { - params: { recurse: options?.recurse }, - signal: options?.signal - }); - return this.fetch(`/assistants/${assistantId}/subgraphs`, { - params: { recurse: options?.recurse }, - signal: options?.signal - }); - } - async create(payload) { - return this.fetch("/assistants", { - method: "POST", - json: { - graph_id: payload.graphId, - config: payload.config, - context: payload.context, - metadata: payload.metadata, - assistant_id: payload.assistantId, - if_exists: payload.ifExists, - name: payload.name, - description: payload.description - }, - signal: payload.signal - }); - } - async update(assistantId, payload) { - return this.fetch(`/assistants/${assistantId}`, { - method: "PATCH", - json: { - graph_id: payload.graphId, - config: payload.config, - context: payload.context, - metadata: payload.metadata, - name: payload.name, - description: payload.description - }, - signal: payload.signal - }); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/utils.js +function countTokensApproximately(messages, tools) { + const charsPerToken = 4; + let totalChars = 0; + if (tools && tools.length > 0) { + let toolsChars = 0; + for (const tool2 of tools) { + const toolDict = isLangChainTool(tool2) ? convertToOpenAITool(tool2) : tool2; + toolsChars += JSON.stringify(toolDict).length; } - async delete(assistantId, options) { - return this.fetch(`/assistants/${assistantId}?delete_threads=${options?.deleteThreads ?? false}`, { - method: "DELETE", - signal: options?.signal + totalChars += toolsChars; + } + for (const msg of messages) { + let textContent; + if (typeof msg.content === "string") + textContent = msg.content; + else if (Array.isArray(msg.content)) + textContent = msg.content.map((item) => { + if (typeof item === "string") + return item; + if (item.type === "text" && "text" in item) + return item.text; + return ""; + }).join(""); + else + textContent = ""; + if (AIMessage.isInstance(msg) && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) + textContent += JSON.stringify(msg.tool_calls); + if (ToolMessage.isInstance(msg)) + textContent += msg.tool_call_id ?? ""; + totalChars += textContent.length; + } + return Math.ceil(totalChars / charsPerToken); +} +function getHookConstraint(hook) { + if (!hook || typeof hook === "function") + return; + return hook.canJumpTo; +} +function getHookFunction(arg) { + if (typeof arg === "function") + return arg; + return arg.hook; +} +var init_utils10 = __esm(() => { + init_messages(); + init_tools2(); + init_function_calling(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/stream.js +function isOwnEvent(ns3, path2) { + if (ns3.length < path2.length || ns3.length > path2.length + 1) + return false; + for (let i = 0;i < path2.length; i += 1) + if (ns3[i] !== path2[i]) + return false; + return true; +} +function isHeadlessToolInterruptError(message, toolCallId) { + try { + const parsed = JSON.parse(message); + if (!Array.isArray(parsed)) + return false; + return parsed.some((entry) => { + if (entry == null || typeof entry !== "object") + return false; + const value = entry.value; + if (value == null || typeof value !== "object") + return false; + const payload = value; + return payload.type === "tool" && (toolCallId == null || payload.toolCall?.id == null || payload.toolCall.id === toolCallId); + }); + } catch { + return false; + } +} +function isSerializedToolMessage(value) { + if (value == null || typeof value !== "object") + return false; + const record3 = value; + if (record3.type !== "constructor" || !Array.isArray(record3.id)) + return false; + return record3.id[record3.id.length - 1] === "ToolMessage"; +} +function normalizeToolOutput(output) { + if (ToolMessage.isInstance(output)) + return output.content; + if (isSerializedToolMessage(output)) + return output.kwargs?.content; + return output; +} +function createToolCallTransformer(path2) { + return () => { + const toolCallsLog = StreamChannel.local(); + const pendingCalls = /* @__PURE__ */ new Map; + function createToolCallEntry(callId, name, rawInput) { + if (pendingCalls.has(callId)) + return; + const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput; + let resolveOutput; + let rejectOutput; + let resolveStatus; + let resolveError; + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; }); - } - async search(query3) { - const json2 = { - graph_id: query3?.graphId ?? undefined, - name: query3?.name ?? undefined, - metadata: query3?.metadata ?? undefined, - limit: query3?.limit ?? 10, - offset: query3?.offset ?? 0, - sort_by: query3?.sortBy ?? undefined, - sort_order: query3?.sortOrder ?? undefined, - select: query3?.select ?? undefined - }; - const [assistants, response] = await this.fetch("/assistants/search", { - method: "POST", - json: json2, - withResponse: true, - signal: query3?.signal + const status = new Promise((res) => { + resolveStatus = res; }); - if (query3?.includePagination) - return { - assistants, - next: response.headers.get("X-Pagination-Next") - }; - return assistants; - } - async count(query3) { - return this.fetch(`/assistants/count`, { - method: "POST", - json: { - metadata: query3?.metadata ?? undefined, - graph_id: query3?.graphId ?? undefined, - name: query3?.name ?? undefined - }, - signal: query3?.signal + const error90 = new Promise((res) => { + resolveError = res; }); - } - async getVersions(assistantId, payload) { - return this.fetch(`/assistants/${assistantId}/versions`, { - method: "POST", - json: { - metadata: payload?.metadata ?? undefined, - limit: payload?.limit ?? 10, - offset: payload?.offset ?? 0 - }, - signal: payload?.signal + pendingCalls.set(callId, { + resolveOutput, + rejectOutput, + resolveStatus, + resolveError }); - } - async setLatest(assistantId, version4, options) { - return this.fetch(`/assistants/${assistantId}/latest`, { - method: "POST", - json: { version: version4 }, - signal: options?.signal + toolCallsLog.push({ + name, + callId, + input, + output, + status, + error: error90 }); } + return { + __native: true, + init: () => ({ toolCalls: toolCallsLog }), + process(event) { + if (!isOwnEvent(event.params.namespace, path2)) + return true; + if (event.method === "messages") { + const data = event.params.data; + if (data.event === "content-block-finish") { + const cb = data.contentBlock ?? data.content_block; + if (cb?.type === "tool_call") + createToolCallEntry(String(cb.id ?? ""), String(cb.name ?? ""), cb.args ?? cb.input); + } + } + if (event.method === "tools") { + const data = event.params.data; + const toolCallId = data.tool_call_id; + if (data.event === "tool-started") + createToolCallEntry(toolCallId, data.tool_name ?? "unknown", data.input); + const pending = toolCallId ? pendingCalls.get(toolCallId) : undefined; + if (pending) { + if (data.event === "tool-finished") { + pending.resolveOutput(normalizeToolOutput(data.output)); + pending.resolveStatus("finished"); + pending.resolveError(undefined); + pendingCalls.delete(toolCallId); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + if (isHeadlessToolInterruptError(message, toolCallId)) + return true; + pending.rejectOutput(new Error(message)); + pending.resolveStatus("error"); + pending.resolveError(message); + pendingCalls.delete(toolCallId); + } + } + } + return true; + }, + finalize() { + for (const pending of pendingCalls.values()) { + pending.resolveStatus("finished"); + pending.resolveError(undefined); + pending.resolveOutput(undefined); + } + pendingCalls.clear(); + toolCallsLog.close(); + }, + fail(err) { + for (const pending of pendingCalls.values()) { + pending.resolveStatus("error"); + pending.resolveError(err instanceof Error ? err.message : String(err)); + pending.rejectOutput(err); + } + pendingCalls.clear(); + toolCallsLog.fail(err); + } + }; }; +} +var init_stream6 = __esm(() => { + init_messages(); + init_dist4(); }); -// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/rng.js -import { randomFillSync } from "node:crypto"; -function rng3() { - if (poolPtr > rnds8Pool.length - 16) { - randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/types.js +var MIDDLEWARE_BRAND; +var init_types10 = __esm(() => { + MIDDLEWARE_BRAND = Symbol.for("AgentMiddleware"); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware.js +function createMiddleware(config3) { + return { + [MIDDLEWARE_BRAND]: true, + name: config3.name, + stateSchema: config3.stateSchema, + contextSchema: config3.contextSchema, + wrapToolCall: config3.wrapToolCall, + wrapModelCall: config3.wrapModelCall, + beforeAgent: config3.beforeAgent, + beforeModel: config3.beforeModel, + afterModel: config3.afterModel, + afterAgent: config3.afterAgent, + tools: config3.tools + }; } -var rnds8Pool, poolPtr; -var init_rng3 = __esm(() => { - rnds8Pool = new Uint8Array(256); - poolPtr = rnds8Pool.length; +var init_middleware = __esm(() => { + init_types10(); }); -// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/stringify.js -function unsafeStringify4(arr3, offset = 0) { - return (byteToHex4[arr3[offset + 0]] + byteToHex4[arr3[offset + 1]] + byteToHex4[arr3[offset + 2]] + byteToHex4[arr3[offset + 3]] + "-" + byteToHex4[arr3[offset + 4]] + byteToHex4[arr3[offset + 5]] + "-" + byteToHex4[arr3[offset + 6]] + byteToHex4[arr3[offset + 7]] + "-" + byteToHex4[arr3[offset + 8]] + byteToHex4[arr3[offset + 9]] + "-" + byteToHex4[arr3[offset + 10]] + byteToHex4[arr3[offset + 11]] + byteToHex4[arr3[offset + 12]] + byteToHex4[arr3[offset + 13]] + byteToHex4[arr3[offset + 14]] + byteToHex4[arr3[offset + 15]]).toLowerCase(); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/tests/utils.js +var init_utils11 = __esm(() => { + init_messages(); + init_chat_models(); + init_runnables(); + init_tools2(); + init_dist3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/zod/plugin.js +function applyPluginPrototype(prototype) { + const cache2 = globalThis[metaSymbol]; + if (cache2.has(prototype)) + return; + Object.defineProperty(prototype, "langgraph", { get() { + const zodThis = this; + return { + metadata(jsonSchemaExtra) { + return withLangGraph(zodThis, { jsonSchemaExtra }); + }, + reducer(fn, schema) { + return withLangGraph(zodThis, { + default: getInteropZodDefaultGetter(zodThis), + reducer: { + schema, + fn + } + }); + } + }; + } }); + cache2.add(prototype); } -var byteToHex4; -var init_stringify3 = __esm(() => { - byteToHex4 = []; - for (let i = 0;i < 256; ++i) { - byteToHex4.push((i + 256).toString(16).slice(1)); +var metaSymbol; +var init_plugin = __esm(() => { + init_meta(); + init_v43(); + init_types3(); + init_v3(); + metaSymbol = Symbol.for("langgraph-zod"); + if (!(metaSymbol in globalThis)) + globalThis[metaSymbol] = /* @__PURE__ */ new WeakSet; + try { + applyPluginPrototype(exports_external2.ZodType.prototype); + applyPluginPrototype(exports_external3.ZodType.prototype); + } catch (error90) { + throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.", { cause: error90 }); } }); -// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/v7.js -function v74(options, buf, offset) { - let bytes; - if (options) { - bytes = v7Bytes3(options.random ?? options.rng?.() ?? rng3(), options.msecs, options.seq, buf, offset); - } else { - const now = Date.now(); - const rnds = rng3(); - updateV7State3(_state4, now, rnds); - bytes = v7Bytes3(rnds, _state4.msecs, _state4.seq, buf, offset); - } - return buf ?? unsafeStringify4(bytes); -} -function updateV7State3(state, now, rnds) { - state.msecs ??= -Infinity; - state.seq ??= 0; - if (now > state.msecs) { - state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; - state.msecs = now; - } else { - state.seq = state.seq + 1 | 0; - if (state.seq === 0) { - state.msecs++; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/zod/zod-registry.js +var LanggraphZodMetaRegistry, registry3; +var init_zod_registry = __esm(() => { + init_meta(); + init_types3(); + init_core4(); + LanggraphZodMetaRegistry = class extends $ZodRegistry2 { + constructor(parent) { + super(); + this.parent = parent; + this._map = this.parent._map; } - } - return state; -} -function v7Bytes3(rnds, msecs, seq, buf, offset = 0) { - if (rnds.length < 16) { - throw new Error("Random bytes length must be >= 16"); - } - if (!buf) { - buf = new Uint8Array(16); - offset = 0; - } else { - if (offset < 0 || offset + 16 > buf.length) { - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + add(schema, ..._meta) { + const firstMeta = _meta[0]; + if (firstMeta && !firstMeta?.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) + firstMeta.default = defaultValueGetter; + } + return super.add(schema, ..._meta); } - } - msecs ??= Date.now(); - seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; - buf[offset++] = msecs / 1099511627776 & 255; - buf[offset++] = msecs / 4294967296 & 255; - buf[offset++] = msecs / 16777216 & 255; - buf[offset++] = msecs / 65536 & 255; - buf[offset++] = msecs / 256 & 255; - buf[offset++] = msecs & 255; - buf[offset++] = 112 | seq >>> 28 & 15; - buf[offset++] = seq >>> 20 & 255; - buf[offset++] = 128 | seq >>> 14 & 63; - buf[offset++] = seq >>> 6 & 255; - buf[offset++] = seq << 2 & 255 | rnds[10] & 3; - buf[offset++] = rnds[11]; - buf[offset++] = rnds[12]; - buf[offset++] = rnds[13]; - buf[offset++] = rnds[14]; - buf[offset++] = rnds[15]; - return buf; -} -var _state4, v7_default2; -var init_v73 = __esm(() => { - init_rng3(); - init_stringify3(); - _state4 = {}; - v7_default2 = v74; + }; + registry3 = new LanggraphZodMetaRegistry(schemaMetaRegistry); }); -// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/index.js -var init_dist_node = __esm(() => { - init_v73(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_dsuhob7l64k2hyvfwdqy2dgx4m/node_modules/@langchain/langgraph/dist/graph/zod/index.js +var init_zod3 = __esm(() => { + init_meta(); + init_plugin(); + init_zod_registry(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/threads/index.js -var ThreadsClient; -var init_threads = __esm(() => { - init_base16(); - init_stream8(); - init_http(); - init_websocket(); - init_dist_node(); - ThreadsClient = class extends BaseClient { - async get(threadId, options) { - return this.fetch(`/threads/${threadId}`, { - params: { include: options?.include ?? undefined }, - signal: options?.signal - }); - } - async create(payload) { - const ttlPayload = typeof payload?.ttl === "number" ? { - ttl: payload.ttl, - strategy: "delete" - } : payload?.ttl; - return this.fetch(`/threads`, { - method: "POST", - json: { - metadata: { - ...payload?.metadata, - graph_id: payload?.graphId - }, - thread_id: payload?.threadId, - if_exists: payload?.ifExists, - supersteps: payload?.supersteps?.map((s) => ({ updates: s.updates.map((u) => ({ - values: u.values, - command: u.command, - as_node: u.asNode - })) })), - ttl: ttlPayload - }, - signal: payload?.signal - }); - } - async copy(threadId, options) { - return this.fetch(`/threads/${threadId}/copy`, { - method: "POST", - signal: options?.signal - }); - } - async update(threadId, payload) { - const ttlPayload = typeof payload?.ttl === "number" ? { - ttl: payload.ttl, - strategy: "delete" - } : payload?.ttl; - return this.fetch(`/threads/${threadId}`, { - method: "PATCH", - headers: payload?.returnMinimal ? { Prefer: "return=minimal" } : undefined, - json: { - metadata: payload?.metadata, - ttl: ttlPayload - }, - signal: payload?.signal - }); - } - async delete(threadId, options) { - return this.fetch(`/threads/${threadId}`, { - method: "DELETE", - signal: options?.signal - }); - } - async prune(threadIds, options) { - return this.fetch("/threads/prune", { - method: "POST", - json: { - thread_ids: threadIds, - strategy: options?.strategy ?? "delete" - }, - signal: options?.signal - }); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/annotation.js +function createAgentState(hasStructuredResponse = true, stateSchema, middlewareList = []) { + const stateFields = { jumpTo: new UntrackedValue }; + const inputFields = {}; + const outputFields = {}; + const applySchema = (schema) => { + if (StateSchema.isInstance(schema)) { + for (const [key, field] of Object.entries(schema.fields)) + if (!(key in stateFields)) { + stateFields[key] = field; + if (key.startsWith("_")) + continue; + if (ReducedValue.isInstance(field)) { + inputFields[key] = field.inputSchema || field.valueSchema; + outputFields[key] = field.valueSchema; + } else { + inputFields[key] = field; + outputFields[key] = field; + } + } + return; } - async search(query3) { - return this.fetch("/threads/search", { - method: "POST", - json: { - metadata: query3?.metadata ?? undefined, - ids: query3?.ids ?? undefined, - limit: query3?.limit ?? 10, - offset: query3?.offset ?? 0, - status: query3?.status, - sort_by: query3?.sortBy, - sort_order: query3?.sortOrder, - select: query3?.select ?? undefined, - values: query3?.values ?? undefined, - extract: query3?.extract ?? undefined - }, - signal: query3?.signal - }); + const shape = getInteropZodObjectShape(schema); + for (const [key, fieldSchema] of Object.entries(shape)) { + const isPrivate = key.startsWith("_"); + if (!(key in stateFields)) { + if (isZodSchemaV4(fieldSchema)) { + const meta3 = schemaMetaRegistry.get(fieldSchema); + if (meta3?.reducer) { + if (meta3.reducer.schema) { + stateFields[key] = new ReducedValue(fieldSchema, { + inputSchema: meta3.reducer.schema, + reducer: meta3.reducer.fn + }); + if (!isPrivate) { + inputFields[key] = meta3.reducer.schema; + outputFields[key] = fieldSchema; + } + } else { + stateFields[key] = new ReducedValue(fieldSchema, { reducer: meta3.reducer.fn }); + if (!isPrivate) { + inputFields[key] = fieldSchema; + outputFields[key] = fieldSchema; + } + } + continue; + } + } + stateFields[key] = fieldSchema; + if (!isPrivate) { + inputFields[key] = fieldSchema; + outputFields[key] = fieldSchema; + } + } } - async count(query3) { - return this.fetch(`/threads/count`, { - method: "POST", - json: { - metadata: query3?.metadata ?? undefined, - values: query3?.values ?? undefined, - status: query3?.status ?? undefined - }, - signal: query3?.signal + }; + if (stateSchema && (StateSchema.isInstance(stateSchema) || isInteropZodObject(stateSchema))) + applySchema(stateSchema); + for (const middleware of middlewareList) + if (middleware.stateSchema && (StateSchema.isInstance(middleware.stateSchema) || isInteropZodObject(middleware.stateSchema))) + applySchema(middleware.stateSchema); + if (hasStructuredResponse) + outputFields.structuredResponse = new UntrackedValue; + return { + state: new StateSchema({ + messages: MessagesValue, + ...stateFields + }), + input: new StateSchema({ + messages: MessagesValue, + ...inputFields + }), + output: new StateSchema({ + messages: MessagesValue, + ...outputFields + }) + }; +} +var init_annotation2 = __esm(() => { + init_dist4(); + init_zod3(); + init_types3(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/utils.js +function parseMiddlewareState(stateSchema, state) { + if (StateSchema.isInstance(stateSchema)) { + const result = {}; + for (const key of Object.keys(stateSchema.fields)) + if (key in state) + result[key] = state[key]; + return result; + } + if (isInteropZodSchema(stateSchema)) + return interopParse(stateSchema, state); + throw new Error(`Invalid state schema type: ${typeof stateSchema}`); +} +function _addInlineAgentName(message) { + if (!AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) + return message; + if (!message.name) + return message; + const { name } = message; + if (typeof message.content === "string") + return new AIMessage({ + ...message.lc_kwargs, + content: `${name}${message.content}`, + name: undefined + }); + const updatedContent = []; + let textBlockCount = 0; + for (const contentBlock of message.content) + if (typeof contentBlock === "string") { + textBlockCount += 1; + updatedContent.push(`${name}${contentBlock}`); + } else if (typeof contentBlock === "object" && "type" in contentBlock && contentBlock.type === "text") { + textBlockCount += 1; + updatedContent.push({ + ...contentBlock, + text: `${name}${contentBlock.text}` }); + } else + updatedContent.push(contentBlock); + if (!textBlockCount) + updatedContent.unshift({ + type: "text", + text: `${name}` + }); + return new AIMessage({ + ...message.lc_kwargs, + content: updatedContent, + name: undefined + }); +} +function _removeInlineAgentName(message) { + if (!AIMessage.isInstance(message) || !message.content) + return message; + let updatedContent = []; + let updatedName; + if (Array.isArray(message.content)) + updatedContent = message.content.filter((block) => { + if (block.type === "text" && typeof block.text === "string") { + const nameMatch = block.text.match(NAME_PATTERN); + const contentMatch = block.text.match(CONTENT_PATTERN); + if (nameMatch && (!contentMatch || contentMatch[1] === "")) { + updatedName = nameMatch[1]; + return false; + } + return true; + } + return true; + }).map((block) => { + if (block.type === "text" && typeof block.text === "string") { + const nameMatch = block.text.match(NAME_PATTERN); + const contentMatch = block.text.match(CONTENT_PATTERN); + if (!nameMatch || !contentMatch) + return block; + updatedName = nameMatch[1]; + return { + ...block, + text: contentMatch[1] + }; + } + return block; + }); + else { + const content = message.content; + const nameMatch = content.match(NAME_PATTERN); + const contentMatch = content.match(CONTENT_PATTERN); + if (!nameMatch || !contentMatch) + return message; + updatedName = nameMatch[1]; + updatedContent = contentMatch[1]; + } + return new AIMessage({ + ...Object.keys(message.lc_kwargs ?? {}).length > 0 ? message.lc_kwargs : message, + content: updatedContent, + name: updatedName + }); +} +function isClientTool(tool2) { + return Runnable.isRunnable(tool2); +} +function _isChatModelWithBindTools(llm) { + if (!isBaseChatModel(llm)) + return false; + return "bindTools" in llm && typeof llm.bindTools === "function"; +} +function validateLLMHasNoBoundTools(llm) { + if (typeof llm === "function") + return; + let model = llm; + if (RunnableSequence.isRunnableSequence(model)) + model = model.steps.find((step) => RunnableBinding.isRunnableBinding(step)) || model; + if (isConfigurableModel(model)) + return; + if (RunnableBinding.isRunnableBinding(model)) { + const hasToolsInKwargs = model.kwargs != null && typeof model.kwargs === "object" && "tools" in model.kwargs && Array.isArray(model.kwargs.tools) && model.kwargs.tools.length > 0; + const hasToolsInConfig = model.config != null && typeof model.config === "object" && "tools" in model.config && Array.isArray(model.config.tools) && model.config.tools.length > 0; + if (hasToolsInKwargs || hasToolsInConfig) + throw new MultipleToolsBoundError; + } + if ("tools" in model && model.tools !== undefined && Array.isArray(model.tools) && model.tools.length > 0) + throw new MultipleToolsBoundError; +} +function hasToolCalls(message) { + return Boolean(AIMessage.isInstance(message) && message.tool_calls && message.tool_calls.length > 0); +} +function normalizeSystemPrompt(systemPrompt) { + if (systemPrompt == null) + return new SystemMessage(""); + if (SystemMessage.isInstance(systemPrompt)) + return systemPrompt; + if (typeof systemPrompt === "string") + return new SystemMessage({ content: [{ + type: "text", + text: systemPrompt + }] }); + throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof systemPrompt}`); +} +async function bindTools(llm, toolClasses, options = {}) { + const model = _simpleBindTools(llm, toolClasses, options); + if (model) + return model; + if (isConfigurableModel(llm)) { + const model2 = _simpleBindTools(await llm._getModelInstance(), toolClasses, options); + if (model2) + return model2; + } + if (RunnableSequence.isRunnableSequence(llm)) { + const modelStep = llm.steps.findIndex((step) => RunnableBinding.isRunnableBinding(step) || isBaseChatModel(step) || isConfigurableModel(step)); + if (modelStep >= 0) { + const model2 = _simpleBindTools(llm.steps[modelStep], toolClasses, options); + if (model2) { + const nextSteps = llm.steps.slice(); + nextSteps.splice(modelStep, 1, model2); + return RunnableSequence.from(nextSteps); + } } - async getState(threadId, checkpoint, options) { - if (checkpoint != null) { - if (typeof checkpoint !== "string") - return this.fetch(`/threads/${threadId}/state/checkpoint`, { - method: "POST", - json: { - checkpoint, - subgraphs: options?.subgraphs - }, - signal: options?.signal - }); - return this.fetch(`/threads/${threadId}/state/${checkpoint}`, { - params: { subgraphs: options?.subgraphs }, - signal: options?.signal + } + throw new Error(`llm ${llm} must define bindTools method.`); +} +function chainToolCallHandlers(handlers) { + if (handlers.length === 0) + return; + if (handlers.length === 1) + return handlers[0]; + function composeTwo(outer, inner) { + return async (request, handler) => { + const innerHandler = async (passedRequest) => { + return inner(passedRequest, handler); + }; + return outer(request, innerHandler); + }; + } + let result = handlers[handlers.length - 1]; + for (let i = handlers.length - 2;i >= 0; i--) + result = composeTwo(handlers[i], result); + return result; +} +function wrapToolCall(middleware) { + const middlewareWithWrapToolCall = middleware.filter((m) => m.wrapToolCall); + if (middlewareWithWrapToolCall.length === 0) + return; + return chainToolCallHandlers(middlewareWithWrapToolCall.map((m) => { + const originalHandler = m.wrapToolCall; + const wrappedHandler = async (request, handler) => { + const originalState = request.state; + const wrappedInnerHandler = async (passedRequest) => { + const mergedState = { + ...originalState, + ...passedRequest.state + }; + return handler({ + ...passedRequest, + state: mergedState }); + }; + try { + const result = await originalHandler({ + ...request, + state: { + messages: originalState.messages, + ...m.stateSchema ? parseMiddlewareState(m.stateSchema, { ...originalState }) : {} + } + }, wrappedInnerHandler); + if (!ToolMessage.isInstance(result) && !isCommand(result)) + throw new Error(`Invalid response from "wrapToolCall" in middleware "${m.name}": expected ToolMessage or Command, got ${typeof result}`); + return result; + } catch (error90) { + throw MiddlewareError.wrap(error90, m.name); } - return this.fetch(`/threads/${threadId}/state`, { - params: { subgraphs: options?.subgraphs }, - signal: options?.signal - }); - } - async updateState(threadId, options) { - return this.fetch(`/threads/${threadId}/state`, { - method: "POST", - json: { - values: options.values, - checkpoint: options.checkpoint, - checkpoint_id: options.checkpointId, - as_node: options?.asNode + }; + return wrappedHandler; + })); +} +var NAME_PATTERN, CONTENT_PATTERN, _simpleBindTools = (llm, toolClasses, options = {}) => { + if (_isChatModelWithBindTools(llm)) + return llm.bindTools(toolClasses, options); + if (RunnableBinding.isRunnableBinding(llm) && _isChatModelWithBindTools(llm.bound)) { + const newBound = llm.bound.bindTools(toolClasses, options); + if (RunnableBinding.isRunnableBinding(newBound)) + return new RunnableBinding({ + bound: newBound.bound, + config: { + ...llm.config, + ...newBound.config }, - signal: options?.signal - }); - } - async patchState(threadIdOrConfig, metadata, options) { - let threadId; - if (typeof threadIdOrConfig !== "string") { - if (typeof threadIdOrConfig.configurable?.thread_id !== "string") - throw new Error("Thread ID is required when updating state with a config."); - threadId = threadIdOrConfig.configurable.thread_id; - } else - threadId = threadIdOrConfig; - return this.fetch(`/threads/${threadId}/state`, { - method: "PATCH", - json: { metadata }, - signal: options?.signal - }); - } - async getHistory(threadId, options) { - return this.fetch(`/threads/${threadId}/history`, { - method: "POST", - json: { - limit: options?.limit ?? 10, - before: options?.before, - metadata: options?.metadata, - checkpoint: options?.checkpoint + kwargs: { + ...llm.kwargs, + ...newBound.kwargs }, - signal: options?.signal + configFactories: newBound.configFactories ?? llm.configFactories }); + return new RunnableBinding({ + bound: newBound, + config: llm.config, + kwargs: llm.kwargs, + configFactories: llm.configFactories + }); + } + return null; +}; +var init_utils12 = __esm(() => { + init_model(); + init_errors8(); + init_messages(); + init_runnables(); + init_dist4(); + init_types3(); + NAME_PATTERN = /(.*?)<\/name>/s; + CONTENT_PATTERN = /(.*?)<\/content>/s; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/utils.js +async function initializeMiddlewareStates(middlewareList, state) { + const middlewareStates = {}; + for (const middleware of middlewareList) { + if (!middleware.stateSchema) + continue; + let zodSchema = middleware.stateSchema; + if (StateSchema.isInstance(middleware.stateSchema)) { + const zodShape = {}; + for (const [key, field] of Object.entries(middleware.stateSchema.fields)) + if (ReducedValue.isInstance(field)) + zodShape[key] = field.inputSchema || field.valueSchema; + else + zodShape[key] = field; + zodSchema = exports_external3.object(zodShape); } - async* joinStream(threadId, options) { - yield* this.streamWithRetry({ - endpoint: `/threads/${threadId}/stream`, - method: "GET", - signal: options?.signal, - headers: options?.lastEventId ? { "Last-Event-ID": options.lastEventId } : undefined, - params: options?.streamMode ? { stream_mode: options.streamMode } : undefined - }); + const parseResult = await interopSafeParseAsync(interopZodObjectMakeFieldsOptional(zodSchema, (key) => key.startsWith("_")), state); + if (parseResult.success) { + Object.assign(middlewareStates, parseResult.data); + continue; } - stream(threadIdOrOptions, maybeOptions) { - const { threadId, options } = typeof threadIdOrOptions === "string" ? { - threadId: threadIdOrOptions, - options: maybeOptions - } : { - threadId: v7_default2(), - options: threadIdOrOptions - }; - let transport; - if (options.transport != null && typeof options.transport !== "string") - transport = options.transport; + const requiredFields = parseResult.error.issues.filter((issue3) => issue3.code === "invalid_type").map((issue3) => ` - ${issue3.path.join(".")}: Required`).join(` +`); + throw new Error(`Middleware "${middleware.name}" has required state fields that must be initialized: +${requiredFields} + +To fix this, either: +1. Provide default values in your middleware's state schema using .default(): + stateSchema: z.object({ + myField: z.string().default("default value") + }) + +2. Or make the fields optional using .optional(): + stateSchema: z.object({ + myField: z.string().optional() + }) + +3. Or ensure you pass these values when invoking the agent: + agent.invoke({ + messages: [...], + ${parseResult.error.issues[0]?.path.join(".")}: "value" + })`); + } + return middlewareStates; +} +function derivePrivateState(stateSchema) { + const builtInStateSchema = { + messages: exports_external3.custom(() => []), + structuredResponse: exports_external3.any().optional() + }; + if (!stateSchema) + return exports_external3.object(builtInStateSchema); + let shape; + if (StateSchema.isInstance(stateSchema)) { + shape = {}; + for (const [key, field] of Object.entries(stateSchema.fields)) + if (ReducedValue.isInstance(field)) + shape[key] = field.inputSchema || field.valueSchema; else - transport = (options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse")) === "websocket" ? new ProtocolWebSocketTransportAdapter({ - apiUrl: this.apiUrl, - threadId, - defaultHeaders: this.defaultHeaders, - onRequest: this.onRequest, - webSocketFactory: options.webSocketFactory - }) : new ProtocolSseTransportAdapter({ - apiUrl: this.apiUrl, - threadId, - defaultHeaders: this.defaultHeaders, - onRequest: this.onRequest, - fetch: options.fetch - }); - return new ThreadStream(transport, options); + shape[key] = field; + } else + shape = getInteropZodObjectShape(stateSchema); + const privateShape = { ...builtInStateSchema }; + for (const [key, value] of Object.entries(shape)) + if (key.startsWith("_")) + privateShape[key] = value.optional(); + else + privateShape[key] = value; + return exports_external3.object(privateShape); +} +function toPartialZodObject(schema) { + if (isInteropZodObject(schema)) + return interopZodObjectPartial(schema); + if (StateSchema.isInstance(schema)) { + const partialShape = {}; + for (const [key, field] of Object.entries(schema.fields)) { + let fieldSchema; + if (ReducedValue.isInstance(field)) + fieldSchema = field.inputSchema || field.valueSchema; + else + fieldSchema = field; + partialShape[key] = isZodSchemaV4(fieldSchema) ? fieldSchema.optional() : exports_external3.any().optional(); } - }; + return exports_external3.object(partialShape); + } + return exports_external3.object({}); +} +function parseJumpToTarget(target) { + if (!target) + return; + if ([ + "model_request", + "tools", + END + ].includes(target)) + return target; + if (target === "model") + return "model_request"; + if (target === "tools") + return "tools"; + if (target === "end") + return END; + throw new Error(`Invalid jump target: ${target}, must be "model", "tools" or "end".`); +} +function mergeAbortSignals(...signals) { + return AbortSignal.any(signals.filter((maybeSignal) => maybeSignal !== null && maybeSignal !== undefined && typeof maybeSignal === "object" && ("aborted" in maybeSignal) && typeof maybeSignal.aborted === "boolean")); +} +var init_utils13 = __esm(() => { + init_dist4(); + init_types3(); + init_v43(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/runs/index.js -var RunsClient; -var init_runs = __esm(() => { - init_base16(); - RunsClient = class extends BaseClient { - async* stream(threadId, assistantId, payload) { - const json2 = { - input: payload?.input, - command: payload?.command, - config: payload?.config, - context: payload?.context, - metadata: payload?.metadata, - stream_mode: payload?.streamMode, - stream_subgraphs: payload?.streamSubgraphs, - stream_resumable: payload?.streamResumable, - feedback_keys: payload?.feedbackKeys, - assistant_id: assistantId, - interrupt_before: payload?.interruptBefore, - interrupt_after: payload?.interruptAfter, - checkpoint: payload?.checkpoint, - webhook: payload?.webhook, - multitask_strategy: payload?.multitaskStrategy, - on_completion: payload?.onCompletion, - on_disconnect: payload?.onDisconnect, - after_seconds: payload?.afterSeconds, - if_not_exists: payload?.ifNotExists, - checkpoint_during: payload?.checkpointDuring, - durability: payload?.durability - }; - yield* this.streamWithRetry({ - endpoint: threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`, - method: "POST", - json: json2, - signal: payload?.signal, - onInitialResponse: (response) => { - const runMetadata = getRunMetadataFromResponse(response); - if (runMetadata) - payload?.onRunCreated?.(runMetadata); - } - }); - } - async create(threadId, assistantId, payload) { - const json2 = { - input: payload?.input, - command: payload?.command, - config: payload?.config, - context: payload?.context, - metadata: payload?.metadata, - stream_mode: payload?.streamMode, - stream_subgraphs: payload?.streamSubgraphs, - stream_resumable: payload?.streamResumable, - feedback_keys: payload?.feedbackKeys, - assistant_id: assistantId, - interrupt_before: payload?.interruptBefore, - interrupt_after: payload?.interruptAfter, - webhook: payload?.webhook, - checkpoint: payload?.checkpoint, - checkpoint_id: payload?.checkpointId, - multitask_strategy: payload?.multitaskStrategy, - after_seconds: payload?.afterSeconds, - if_not_exists: payload?.ifNotExists, - checkpoint_during: payload?.checkpointDuring, - durability: payload?.durability, - on_completion: payload?.onCompletion, - langsmith_tracer: payload?._langsmithTracer ? { - project_name: payload?._langsmithTracer?.projectName, - example_id: payload?._langsmithTracer?.exampleId - } : undefined - }; - const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`; - const [run2, response] = await this.fetch(endpoint, { - method: "POST", - json: json2, - signal: payload?.signal, - withResponse: true - }); - const runMetadata = getRunMetadataFromResponse(response); - if (runMetadata) - payload?.onRunCreated?.(runMetadata); - return run2; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/RunnableCallable.js +var RunnableCallable2; +var init_RunnableCallable = __esm(() => { + init_runnables(); + init_singletons(); + RunnableCallable2 = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + #state; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : undefined; + this.recurse = fields.recurse ?? this.recurse; } - async createBatch(payloads, options) { - const filteredPayloads = payloads.map((payload) => ({ - ...payload, - assistant_id: payload.assistantId - })).map((payload) => { - return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== undefined)); - }); - return this.fetch("/runs/batch", { - method: "POST", - json: filteredPayloads, - signal: options?.signal - }); + getState() { + return this.#state; } - async wait(threadId, assistantId, payload) { - const json2 = { - input: payload?.input, - command: payload?.command, - config: payload?.config, - context: payload?.context, - metadata: payload?.metadata, - assistant_id: assistantId, - interrupt_before: payload?.interruptBefore, - interrupt_after: payload?.interruptAfter, - checkpoint: payload?.checkpoint, - checkpoint_id: payload?.checkpointId, - webhook: payload?.webhook, - multitask_strategy: payload?.multitaskStrategy, - on_completion: payload?.onCompletion, - on_disconnect: payload?.onDisconnect, - after_seconds: payload?.afterSeconds, - if_not_exists: payload?.ifNotExists, - checkpoint_during: payload?.checkpointDuring, - durability: payload?.durability, - langsmith_tracer: payload?._langsmithTracer ? { - project_name: payload?._langsmithTracer?.projectName, - example_id: payload?._langsmithTracer?.exampleId - } : undefined + setState(state) { + this.#state = { + ...this.#state, + ...state }; - const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`; - const [run2, response] = await this.fetch(endpoint, { - method: "POST", - json: json2, - timeoutMs: null, - signal: payload?.signal, - withResponse: true - }); - const runMetadata = getRunMetadataFromResponse(response); - if (runMetadata) - payload?.onRunCreated?.(runMetadata); - if ((payload?.raiseError !== undefined ? payload.raiseError : true) && "__error__" in run2 && typeof run2.__error__ === "object" && run2.__error__ && "error" in run2.__error__ && "message" in run2.__error__) - throw new Error(`${run2.__error__?.error}: ${run2.__error__?.message}`); - return run2; - } - async list(threadId, options) { - return this.fetch(`/threads/${threadId}/runs`, { - params: { - limit: options?.limit ?? 10, - offset: options?.offset ?? 0, - status: options?.status ?? undefined, - select: options?.select ?? undefined - }, - signal: options?.signal - }); - } - async get(threadId, runId, options) { - return this.fetch(`/threads/${threadId}/runs/${runId}`, { signal: options?.signal }); - } - async cancel(threadId, runId, wait = false, action = "interrupt", options = {}) { - return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, { - method: "POST", - params: { - wait: wait ? "1" : "0", - action - }, - signal: options?.signal - }); - } - async cancelMany(options) { - return this.fetch(`/runs/cancel`, { - method: "POST", - json: { - thread_id: options.threadId, - run_ids: options.runIds, - status: options.status - }, - params: { action: options.action }, - signal: options.signal - }); } - async join(threadId, runId, options) { - return this.fetch(`/threads/${threadId}/runs/${runId}/join`, { - timeoutMs: null, - params: { cancel_on_disconnect: options?.cancelOnDisconnect ? "1" : "0" }, - signal: options?.signal - }); - } - async* joinStream(threadId, runId, options) { - const opts = typeof options === "object" && options != null && options instanceof AbortSignal ? { signal: options } : options; - yield* this.streamWithRetry({ - endpoint: threadId != null ? `/threads/${threadId}/runs/${runId}/stream` : `/runs/${runId}/stream`, - method: "GET", - signal: opts?.signal, - headers: opts?.lastEventId ? { "Last-Event-ID": opts.lastEventId } : undefined, - params: { - cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0", - stream_mode: opts?.streamMode - } - }); - } - async delete(threadId, runId, options) { - return this.fetch(`/threads/${threadId}/runs/${runId}`, { - method: "DELETE", - signal: options?.signal - }); + async invoke(input, options) { + const mergedConfig = mergeConfigs(this.config, options); + const returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) + return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + this.#state = returnValue; + return returnValue; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/crons/index.js -var CronsClient; -var init_crons = __esm(() => { - init_base16(); - CronsClient = class extends BaseClient { - async createForThread(threadId, assistantId, payload) { - const json2 = { - schedule: payload?.schedule, - input: payload?.input, - config: payload?.config, - context: payload?.context, - metadata: payload?.metadata, - assistant_id: assistantId, - interrupt_before: payload?.interruptBefore, - interrupt_after: payload?.interruptAfter, - webhook: payload?.webhook, - multitask_strategy: payload?.multitaskStrategy, - checkpoint_during: payload?.checkpointDuring, - durability: payload?.durability, - enabled: payload?.enabled, - timezone: payload?.timezone, - stream_mode: payload?.streamMode, - stream_subgraphs: payload?.streamSubgraphs, - stream_resumable: payload?.streamResumable, - end_time: payload?.endTime, - on_run_completed: payload?.onRunCompleted - }; - return this.fetch(`/threads/${threadId}/runs/crons`, { - method: "POST", - json: json2, - signal: payload?.signal +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/withAgentName.js +function withAgentName(model, agentNameMode) { + let processInputMessage; + let processOutputMessage; + if (agentNameMode === "inline") { + processInputMessage = _addInlineAgentName; + processOutputMessage = _removeInlineAgentName; + } else + throw new Error(`Invalid agent name mode: ${agentNameMode}. Needs to be one of: "inline"`); + function processInputMessages(messages) { + return messages.map(processInputMessage); + } + return RunnableSequence.from([ + RunnableLambda.from(processInputMessages), + model, + RunnableLambda.from(processOutputMessage) + ]); +} +var init_withAgentName = __esm(() => { + init_utils12(); + init_runnables(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/AgentNode.js +function isInternalModelResponse(response) { + return AIMessage.isInstance(response) || isCommand(response) || typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response; +} +var AGENT_NODE_NAME = "model_request", AgentNode; +var init_AgentNode = __esm(() => { + init_universal(); + init_model(); + init_errors8(); + init_utils12(); + init_RunnableCallable(); + init_utils13(); + init_withAgentName(); + init_responses(); + init_messages(); + init_runnables(); + init_dist4(); + init_types3(); + AgentNode = class extends RunnableCallable2 { + #options; + #systemMessage; + constructor(options) { + super({ + name: options.name ?? "model", + func: (input, config3) => this.#run(input, config3) }); + this.#options = options; + this.#systemMessage = options.systemMessage; } - async create(assistantId, payload) { - const json2 = { - schedule: payload?.schedule, - input: payload?.input, - config: payload?.config, - context: payload?.context, - metadata: payload?.metadata, - assistant_id: assistantId, - interrupt_before: payload?.interruptBefore, - interrupt_after: payload?.interruptAfter, - webhook: payload?.webhook, - on_run_completed: payload?.onRunCompleted, - multitask_strategy: payload?.multitaskStrategy, - checkpoint_during: payload?.checkpointDuring, - durability: payload?.durability, - enabled: payload?.enabled, - timezone: payload?.timezone, - stream_mode: payload?.streamMode, - stream_subgraphs: payload?.streamSubgraphs, - stream_resumable: payload?.streamResumable, - end_time: payload?.endTime + async#getResponseFormat(model, responseFormat = this.#options.responseFormat) { + if (!responseFormat) + return; + let resolvedModel; + if (isConfigurableModel(model)) + resolvedModel = await model._getModelInstance(); + else if (typeof model !== "string") + resolvedModel = model; + const strategies = transformResponseFormat(responseFormat, undefined, resolvedModel); + if (strategies.length === 0) + return; + if (!strategies.every((format3) => format3 instanceof ProviderStrategy)) + return { + type: "tool", + tools: strategies.filter((format3) => format3 instanceof ToolStrategy).reduce((acc, format3) => { + acc[format3.name] = format3; + return acc; + }, {}) + }; + return { + type: "native", + strategy: strategies[0] }; - return this.fetch(`/runs/crons`, { - method: "POST", - json: json2, - signal: payload?.signal - }); } - async update(cronId, payload) { - const json2 = {}; - if (payload?.schedule !== undefined) - json2.schedule = payload.schedule; - if (payload?.timezone !== undefined) - json2.timezone = payload.timezone; - if (payload?.endTime !== undefined) - json2.end_time = payload.endTime; - if (payload?.input !== undefined) - json2.input = payload.input; - if (payload?.metadata !== undefined) - json2.metadata = payload.metadata; - if (payload?.config !== undefined) - json2.config = payload.config; - if (payload?.context !== undefined) - json2.context = payload.context; - if (payload?.webhook !== undefined) - json2.webhook = payload.webhook; - if (payload?.interruptBefore !== undefined) - json2.interrupt_before = payload.interruptBefore; - if (payload?.interruptAfter !== undefined) - json2.interrupt_after = payload.interruptAfter; - if (payload?.onRunCompleted !== undefined) - json2.on_run_completed = payload.onRunCompleted; - if (payload?.enabled !== undefined) - json2.enabled = payload.enabled; - if (payload?.streamMode !== undefined) - json2.stream_mode = payload.streamMode; - if (payload?.streamSubgraphs !== undefined) - json2.stream_subgraphs = payload.streamSubgraphs; - if (payload?.streamResumable !== undefined) - json2.stream_resumable = payload.streamResumable; - if (payload?.durability !== undefined) - json2.durability = payload.durability; - return this.fetch(`/runs/crons/${cronId}`, { - method: "PATCH", - json: json2, - signal: payload?.signal - }); - } - async delete(cronId, options) { - await this.fetch(`/runs/crons/${cronId}`, { - method: "DELETE", - signal: options?.signal - }); - } - async search(query3) { - return this.fetch("/runs/crons/search", { - method: "POST", - json: { - assistant_id: query3?.assistantId ?? undefined, - thread_id: query3?.threadId ?? undefined, - enabled: query3?.enabled ?? undefined, - limit: query3?.limit ?? 10, - offset: query3?.offset ?? 0, - sort_by: query3?.sortBy ?? undefined, - sort_order: query3?.sortOrder ?? undefined, - select: query3?.select ?? undefined, - metadata: query3?.metadata ?? undefined - }, - signal: query3?.signal - }); + async#run(state, config3) { + const lastMessage = state.messages.at(-1); + if (lastMessage && ToolMessage.isInstance(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name)) + return [new Command({ update: { messages: [] } })]; + const { response, lastAiMessage, collectedCommands } = await this.#invokeModel(state, config3); + if (typeof response === "object" && response !== null && "structuredResponse" in response && "messages" in response) { + const { structuredResponse, messages } = response; + return { + messages: [...state.messages, ...messages], + structuredResponse + }; + } + const commands = []; + const aiMessage = AIMessage.isInstance(response) ? response : lastAiMessage; + if (aiMessage) { + aiMessage.name = this.name; + aiMessage.lc_kwargs.name = this.name; + if (this.#areMoreStepsNeeded(state, aiMessage)) + commands.push(new Command({ update: { messages: [new AIMessage({ + content: "Sorry, need more steps to process this request.", + name: this.name, + id: aiMessage.id + })] } })); + else + commands.push(new Command({ update: { messages: [aiMessage] } })); + } + if (isCommand(response) && !collectedCommands.includes(response)) + commands.push(response); + commands.push(...collectedCommands); + return commands; } - async count(query3) { - return this.fetch(`/runs/crons/count`, { - method: "POST", - json: { - assistant_id: query3?.assistantId ?? undefined, - thread_id: query3?.threadId ?? undefined, - metadata: query3?.metadata ?? undefined - }, - signal: query3?.signal - }); + #deriveModel() { + if (typeof this.#options.model === "string") + return initChatModel(this.#options.model); + if (this.#options.model) + return this.#options.model; + throw new Error("No model option was provided, either via `model` option."); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/store/index.js -var StoreClient; -var init_store = __esm(() => { - init_base16(); - StoreClient = class extends BaseClient { - async putItem(namespace, key, value, options) { - namespace.forEach((label) => { - if (label.includes(".")) - throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); - }); - const payload = { - namespace, - key, - value, - index: options?.index, - ttl: options?.ttl + async#invokeModel(state, config3, options = {}) { + const model = await this.#deriveModel(); + const lgConfig = config3; + let currentSystemMessage = this.#systemMessage; + let lastAiMessage = null; + const collectedCommands = []; + const baseHandler = async (request) => { + validateLLMHasNoBoundTools(request.model); + const structuredResponseFormat = await this.#getResponseFormat(request.model, request.responseFormat); + const modelWithTools = await this.#bindTools(request.model, request, structuredResponseFormat); + const messages = [...currentSystemMessage.text === "" ? [] : [currentSystemMessage], ...request.messages]; + const signal = mergeAbortSignals(this.#options.signal, config3.signal); + const response = await raceWithSignal(modelWithTools.invoke(messages, { + ...config3, + signal + }), signal); + lastAiMessage = response; + if (structuredResponseFormat?.type === "native") { + const structuredResponse = structuredResponseFormat.strategy.parse(response); + if (structuredResponse) + return { + structuredResponse, + messages: [response] + }; + if (!response.tool_calls || response.tool_calls.length === 0) + throw new StructuredOutputParsingError(typeof structuredResponseFormat.strategy.schema?.title === "string" ? structuredResponseFormat.strategy.schema.title : "providerStrategy", ["Model output did not satisfy the provided response schema."]); + return response; + } + if (!structuredResponseFormat || !response.tool_calls) + return response; + const toolCalls = response.tool_calls.filter((call3) => (call3.name in structuredResponseFormat.tools)); + if (toolCalls.length === 0) + return response; + if (toolCalls.length > 1) + return this.#handleMultipleStructuredOutputs(response, toolCalls, structuredResponseFormat); + const toolMessageContent = structuredResponseFormat.tools[toolCalls[0].name]?.options?.toolMessageContent; + return this.#handleSingleStructuredOutput(response, toolCalls[0], structuredResponseFormat, toolMessageContent ?? options.lastMessage); }; - return this.fetch("/store/items", { - method: "PUT", - json: payload, - signal: options?.signal - }); - } - async getItem(namespace, key, options) { - namespace.forEach((label) => { - if (label.includes(".")) - throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); - }); - const params = { - namespace: namespace.join("."), - key + const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? []; + let wrappedHandler = baseHandler; + for (let i = wrapperMiddleware.length - 1;i >= 0; i--) { + const middlewareEntry = wrapperMiddleware[i]; + const middleware = Array.isArray(middlewareEntry) ? middlewareEntry[0] : middlewareEntry; + if (middleware.wrapModelCall) { + const innerHandler = wrappedHandler; + const currentMiddleware = middleware; + wrappedHandler = async (request) => { + const baselineSystemMessage = currentSystemMessage; + const context2 = currentMiddleware.contextSchema ? interopParse(currentMiddleware.contextSchema, lgConfig?.context || {}) : lgConfig?.context; + const runtime = Object.freeze({ + context: context2, + store: lgConfig.store, + configurable: lgConfig.configurable, + writer: lgConfig.writer, + interrupt: lgConfig.interrupt, + signal: lgConfig.signal + }); + const requestWithStateAndRuntime = { + ...request, + state: { + ...middleware.stateSchema ? interopParse(toPartialZodObject(middleware.stateSchema), state) : {}, + messages: state.messages + }, + runtime + }; + const handlerWithValidation = async (req) => { + currentSystemMessage = baselineSystemMessage; + const modifiedTools = req.tools ?? []; + const registeredToolsByName = new Map(this.#options.toolClasses.filter(isClientTool).map((t) => [t.name, t])); + const addedClientTools = modifiedTools.filter((tool2) => isClientTool(tool2) && !registeredToolsByName.has(tool2.name)); + const replacedClientTools = modifiedTools.filter((tool2) => { + if (!isClientTool(tool2)) + return false; + const original = registeredToolsByName.get(tool2.name); + return original != null && original !== tool2; + }); + if (addedClientTools.length > 0) { + if (!this.#options.middleware?.some((m) => m.wrapToolCall != null)) + throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${addedClientTools.map((tool2) => tool2.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`); + } + if (replacedClientTools.length > 0) + throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${currentMiddleware.name}": ${replacedClientTools.map((tool2) => tool2.name).join(", ")}. This is not supported.`); + let normalizedReq = req; + const hasSystemPromptChanged = req.systemPrompt !== currentSystemMessage.text; + const hasSystemMessageChanged = req.systemMessage !== currentSystemMessage; + if (hasSystemPromptChanged && hasSystemMessageChanged) + throw new Error("Cannot change both systemPrompt and systemMessage in the same request."); + if (hasSystemPromptChanged) { + currentSystemMessage = new SystemMessage({ content: [{ + type: "text", + text: req.systemPrompt + }] }); + normalizedReq = { + ...req, + systemPrompt: currentSystemMessage.text, + systemMessage: currentSystemMessage + }; + } + if (hasSystemMessageChanged) { + currentSystemMessage = new SystemMessage({ ...req.systemMessage }); + normalizedReq = { + ...req, + systemPrompt: currentSystemMessage.text, + systemMessage: currentSystemMessage + }; + } + const innerHandlerResult = await innerHandler(normalizedReq); + if (isCommand(innerHandlerResult) && lastAiMessage) { + if (!collectedCommands.includes(innerHandlerResult)) + collectedCommands.push(innerHandlerResult); + return lastAiMessage; + } + return innerHandlerResult; + }; + if (!currentMiddleware.wrapModelCall) + return handlerWithValidation(requestWithStateAndRuntime); + try { + const middlewareResponse = await currentMiddleware.wrapModelCall(requestWithStateAndRuntime, handlerWithValidation); + if (!isInternalModelResponse(middlewareResponse)) + throw new Error(`Invalid response from "wrapModelCall" in middleware "${currentMiddleware.name}": expected AIMessage or Command, got ${typeof middlewareResponse}`); + if (AIMessage.isInstance(middlewareResponse)) + lastAiMessage = middlewareResponse; + else if (isCommand(middlewareResponse)) + collectedCommands.push(middlewareResponse); + return middlewareResponse; + } catch (error90) { + throw MiddlewareError.wrap(error90, currentMiddleware.name); + } + }; + } + } + currentSystemMessage = this.#systemMessage; + const initialRequest = { + model, + responseFormat: this.#options.responseFormat, + systemPrompt: currentSystemMessage?.text, + systemMessage: currentSystemMessage, + messages: state.messages, + tools: this.#options.toolClasses, + state, + runtime: Object.freeze({ + context: lgConfig?.context, + store: lgConfig.store, + configurable: lgConfig.configurable, + writer: lgConfig.writer, + interrupt: lgConfig.interrupt, + signal: lgConfig.signal + }) + }; + return { + response: await wrappedHandler(initialRequest), + lastAiMessage, + collectedCommands }; - if (options?.refreshTtl !== undefined) - params.refresh_ttl = options.refreshTtl; - const response = await this.fetch("/store/items", { - params, - signal: options?.signal - }); - return response ? { - ...response, - createdAt: response.created_at, - updatedAt: response.updated_at - } : null; } - async deleteItem(namespace, key, options) { - namespace.forEach((label) => { - if (label.includes(".")) - throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); - }); - return this.fetch("/store/items", { - method: "DELETE", - json: { - namespace, - key - }, - signal: options?.signal - }); + #handleMultipleStructuredOutputs(response, toolCalls, responseFormat) { + const multipleStructuredOutputsError = new MultipleStructuredOutputsError(toolCalls.map((call3) => call3.name)); + return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0], responseFormat); } - async searchItems(namespacePrefix, options) { - const payload = { - namespace_prefix: namespacePrefix, - filter: options?.filter, - limit: options?.limit ?? 10, - offset: options?.offset ?? 0, - query: options?.query, - refresh_ttl: options?.refreshTtl - }; - return { items: (await this.fetch("/store/items/search", { - method: "POST", - json: payload, - signal: options?.signal - })).items.map((item) => ({ - ...item, - createdAt: item.created_at, - updatedAt: item.updated_at - })) }; + #handleSingleStructuredOutput(response, toolCall, responseFormat, lastMessage) { + const tool2 = responseFormat.tools[toolCall.name]; + try { + const structuredResponse = tool2.parse(toolCall.args); + return { + structuredResponse, + messages: [ + response, + new ToolMessage({ + tool_call_id: toolCall.id ?? "", + content: JSON.stringify(structuredResponse), + name: toolCall.name + }), + new AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`) + ] + }; + } catch (error90) { + return this.#handleToolStrategyError(error90, response, toolCall, responseFormat); + } } - async listNamespaces(options) { - const payload = { - prefix: options?.prefix, - suffix: options?.suffix, - max_depth: options?.maxDepth, - limit: options?.limit ?? 100, - offset: options?.offset ?? 0 - }; - return this.fetch("/store/namespaces", { - method: "POST", - json: payload, - signal: options?.signal + async#handleToolStrategyError(error90, response, toolCall, responseFormat) { + const errorHandler2 = Object.values(responseFormat.tools).at(0)?.options?.handleError; + const toolCallId = toolCall.id; + if (!toolCallId) + throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID."); + if (errorHandler2 === false) + throw error90; + if (errorHandler2 === undefined || typeof errorHandler2 === "boolean" && errorHandler2 || Array.isArray(errorHandler2) && errorHandler2.some((h) => h instanceof MultipleStructuredOutputsError)) + return new Command({ + update: { messages: [response, new ToolMessage({ + content: error90.message, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + if (typeof errorHandler2 === "string") + return new Command({ + update: { messages: [response, new ToolMessage({ + content: errorHandler2, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + if (typeof errorHandler2 === "function") { + const content = await errorHandler2(error90); + if (typeof content !== "string") + throw new Error("Error handler must return a string."); + return new Command({ + update: { messages: [response, new ToolMessage({ + content, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME + }); + } + return new Command({ + update: { messages: [response, new ToolMessage({ + content: error90.message, + tool_call_id: toolCallId + })] }, + goto: AGENT_NODE_NAME }); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/ui-internal/index.js -var UiClient; -var init_ui_internal = __esm(() => { - init_base16(); - UiClient = class UiClient2 extends BaseClient { - static promiseCache = {}; - static getOrCached(key, fn) { - if (UiClient2.promiseCache[key] != null) - return UiClient2.promiseCache[key]; - const promise2 = fn(); - UiClient2.promiseCache[key] = promise2; - return promise2; + #areMoreStepsNeeded(state, response) { + const allToolsReturnDirect = AIMessage.isInstance(response) && response.tool_calls?.every((call3) => this.#options.shouldReturnDirect.has(call3.name)); + const remainingSteps = "remainingSteps" in state ? state.remainingSteps : undefined; + return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && hasToolCalls(state.messages.at(-1)))); } - async getComponent(assistantId, agentName) { - return UiClient2.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => { - let [url2, init] = this.prepareFetchOptions(`/ui/${assistantId}`, { - headers: { - Accept: "text/html", - "Content-Type": "application/json" + async#bindTools(model, preparedOptions, structuredResponseFormat) { + const options = {}; + const structuredTools = Object.values(structuredResponseFormat && "tools" in structuredResponseFormat ? structuredResponseFormat.tools : {}); + const allTools = [...preparedOptions?.tools ?? this.#options.toolClasses, ...structuredTools.map((toolStrategy) => toolStrategy.tool)]; + const toolChoice = preparedOptions?.toolChoice || (structuredTools.length > 0 ? "any" : undefined); + if (structuredResponseFormat?.type === "native") { + const resolvedStrict = preparedOptions?.modelSettings?.strict ?? structuredResponseFormat?.strategy?.strict ?? true; + const jsonSchemaParams = { + name: structuredResponseFormat.strategy.schema?.name ?? "extract", + description: getSchemaDescription(structuredResponseFormat.strategy.schema), + schema: structuredResponseFormat.strategy.schema, + strict: resolvedStrict + }; + Object.assign(options, { + response_format: { + type: "json_schema", + json_schema: jsonSchemaParams }, - method: "POST", - json: { name: agentName } + outputConfig: { format: { + type: "json_schema", + schema: structuredResponseFormat.strategy.schema + } }, + responseSchema: structuredResponseFormat.strategy.schema, + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: structuredResponseFormat.strategy.schema + }, + strict: resolvedStrict }); - if (this.onRequest != null) - init = await this.onRequest(url2, init); - return (await this.asyncCaller.fetch(url2.toString(), init)).text(); + } + const modelWithTools = await bindTools(model, allTools, { + ...options, + ...preparedOptions?.modelSettings, + tool_choice: toolChoice }); + return this.#options.includeAgentName === "inline" ? withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools; + } + getState() { + const state = super.getState(); + return { + messages: [], + ...state && !isCommand(state) ? state : {} + }; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/index.js -var init_transport = __esm(() => { - init_http(); - init_websocket(); - init_agent_server(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client/index.js -var Client2 = class { - assistants; - threads; - runs; - crons; - store; - "~ui"; - "~configHash"; - constructor(config2) { - this["~configHash"] = JSON.stringify({ - apiUrl: config2?.apiUrl, - apiKey: config2?.apiKey, - timeoutMs: config2?.timeoutMs, - defaultHeaders: config2?.defaultHeaders, - streamProtocol: config2?.streamProtocol, - maxConcurrency: config2?.callerOptions?.maxConcurrency, - maxRetries: config2?.callerOptions?.maxRetries, - callbacks: { - onFailedResponseHook: config2?.callerOptions?.onFailedResponseHook != null, - onRequest: config2?.onRequest != null, - fetch: config2?.callerOptions?.fetch != null - } +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/ToolNode.js +function defaultHandleToolErrors(error90, toolCall) { + if (error90 instanceof ToolInvocationError) + return new ToolMessage({ + content: error90.message, + tool_call_id: toolCall.id, + name: toolCall.name }); - this.assistants = new AssistantsClient(config2); - this.threads = new ThreadsClient(config2); - this.runs = new RunsClient(config2); - this.crons = new CronsClient(config2); - this.store = new StoreClient(config2); - this["~ui"] = new UiClient(config2); - } -}; -var init_client2 = __esm(() => { - init_base16(); - init_assistants(); - init_subscription(); - init_tools4(); - init_messages5(); - init_media(); - init_subgraphs2(); - init_subagents(); - init_error4(); - init_stream8(); - init_http(); - init_websocket(); - init_threads(); - init_runs(); - init_crons(); - init_store(); - init_ui_internal(); - init_agent_server(); - init_transport(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/client.js -var init_client3 = __esm(() => { - init_base16(); - init_assistants(); - init_subscription(); - init_messages5(); - init_media(); - init_error4(); - init_stream8(); - init_http(); - init_websocket(); - init_threads(); - init_runs(); - init_crons(); - init_store(); - init_agent_server(); - init_client2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/store.js -var StreamStore = class { - #snapshot; - #listeners = /* @__PURE__ */ new Set; - constructor(initial) { - this.#snapshot = initial; - } - subscribe = (listener) => { - this.#listeners.add(listener); - return () => { - this.#listeners.delete(listener); - }; - }; - getSnapshot = () => this.#snapshot; - setValue = (next) => { - if (Object.is(next, this.#snapshot)) - return; - this.#snapshot = next; - for (const listener of this.#listeners) - listener(); - }; - setState = (updater) => { - this.setValue(updater(this.#snapshot)); - }; -}; -var init_store2 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/channel-registry.js -async function tryDispose(runtime) { - try { - await runtime.dispose(); - } catch {} + return new ToolMessage({ + content: `${error90} + Please fix your mistakes.`, + tool_call_id: toolCall.id, + name: toolCall.name + }); } -var ChannelRegistry = class { - #thread; - #rootBus; - #entries = /* @__PURE__ */ new Map; - constructor(rootBus) { - this.#rootBus = rootBus; - } - bind(thread) { - if (this.#thread === thread) - return; - const previous = this.#thread; - this.#thread = thread; - for (const entry of this.#entries.values()) { - if (entry.runtime != null && previous != null) - tryDispose(entry.runtime); - entry.runtime = undefined; - entry.store.setValue(entry.initial); - if (thread != null) - entry.runtime = entry.open({ - thread, - store: entry.store, - rootBus: this.#rootBus +function isSend(x) { + return x instanceof Send; +} +var getInvalidToolError = (toolName, availableTools) => `Error: ${toolName} is not a valid tool, try one of [${availableTools.join(", ")}].`, TOOLS_NODE_NAME = "tools", isBaseMessageArray = (input) => Array.isArray(input) && input.every(BaseMessage.isInstance), isMessagesState = (input) => typeof input === "object" && input != null && ("messages" in input) && isBaseMessageArray(input.messages), isSendInput = (input) => typeof input === "object" && input != null && ("lg_tool_call" in input), ToolNode; +var init_ToolNode = __esm(() => { + init_errors8(); + init_RunnableCallable(); + init_utils13(); + init_messages(); + init_tools2(); + init_dist4(); + ToolNode = class extends RunnableCallable2 { + tools; + trace = false; + signal; + handleToolErrors = defaultHandleToolErrors; + wrapToolCall; + constructor(tools, options) { + const { name, tags, handleToolErrors, signal, wrapToolCall: wrapToolCall2 } = options ?? {}; + super({ + name, + tags, + func: (state, config3) => this.run(state, config3) + }); + this.options = options; + this.tools = tools; + this.handleToolErrors = handleToolErrors ?? this.handleToolErrors; + this.signal = signal; + this.wrapToolCall = wrapToolCall2; + } + #handleError(error90, call3, isMiddlewareError) { + if (isGraphInterrupt(error90)) + throw error90; + if (this.signal?.aborted) + throw error90; + if (isMiddlewareError && this.handleToolErrors !== true) + throw error90; + if (!this.handleToolErrors) + throw error90; + if (typeof this.handleToolErrors === "function") { + const result = this.handleToolErrors(error90, call3); + if (result && ToolMessage.isInstance(result)) + return result; + throw error90; + } else if (this.handleToolErrors) + return new ToolMessage({ + name: call3.name, + content: `${error90} + Please fix your mistakes.`, + tool_call_id: call3.id }); + throw error90; } - } - get thread() { - return this.#thread; - } - acquire(spec) { - let entry = this.#entries.get(spec.key); - if (entry == null) { - const store = new StreamStore(spec.initial); - const newEntry = { - key: spec.key, - store, - initial: spec.initial, - open: spec.open, - refCount: 0, - runtime: undefined + async runTool(call3, config3, state) { + const lgConfig = config3; + const runtime = { + context: lgConfig?.context, + store: lgConfig?.store, + configurable: lgConfig?.configurable, + writer: lgConfig?.writer, + interrupt: lgConfig?.interrupt, + signal: lgConfig?.signal }; - if (this.#thread != null) - newEntry.runtime = spec.open({ - thread: this.#thread, - store, - rootBus: this.#rootBus + const registeredTool = this.tools.find((t) => t.name === call3.name); + const baseHandler = async (request2) => { + const { toolCall, tool: requestTool } = request2; + const tool2 = requestTool ?? this.tools.find((t) => t.name === toolCall.name); + if (tool2 === undefined) { + const availableTools = this.tools.map((t) => t.name); + return new ToolMessage({ + content: getInvalidToolError(toolCall.name, availableTools), + tool_call_id: toolCall.id, + name: toolCall.name, + status: "error" + }); + } + const invokableTool = tool2; + try { + const output = await invokableTool.invoke({ + ...toolCall, + type: "tool_call" + }, { + ...config3, + config: config3, + toolCallId: toolCall.id, + state: config3.configurable?.__pregel_scratchpad?.currentTaskInput, + signal: mergeAbortSignals(this.signal, config3.signal) + }); + if (ToolMessage.isInstance(output) || isCommand(output)) + return output; + return new ToolMessage({ + name: invokableTool.name, + content: typeof output === "string" ? output : JSON.stringify(output), + tool_call_id: toolCall.id + }); + } catch (e) { + if (e instanceof ToolInputParsingException) + throw new ToolInvocationError(e, toolCall); + throw e; + } + }; + const request = { + toolCall: call3, + tool: registeredTool, + state, + runtime + }; + if (this.wrapToolCall) + try { + return await this.wrapToolCall(request, baseHandler); + } catch (e) { + return this.#handleError(e, call3, true); + } + if (!registeredTool) { + const availableTools = this.tools.map((t) => t.name); + return new ToolMessage({ + content: getInvalidToolError(call3.name, availableTools), + tool_call_id: call3.id, + name: call3.name, + status: "error" }); - this.#entries.set(spec.key, newEntry); - entry = newEntry; + } + try { + return await baseHandler(request); + } catch (e) { + return this.#handleError(e, call3, false); + } } - entry.refCount += 1; - let released = false; - return { - store: entry.store, - release: () => { - if (released) - return; - released = true; - const current = this.#entries.get(spec.key); - if (current == null) - return; - current.refCount -= 1; - if (current.refCount <= 0) { - this.#entries.delete(spec.key); - if (current.runtime != null) - tryDispose(current.runtime); + async run(state, config3) { + let outputs; + if (isSendInput(state)) { + const { lg_tool_call: _, jumpTo: __, ...newState } = state; + outputs = [await this.runTool(state.lg_tool_call, config3, newState)]; + } else { + let messages; + if (isBaseMessageArray(state)) + messages = state; + else if (isMessagesState(state)) + messages = state.messages; + else + throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input."); + const toolMessageIds = new Set(messages.filter((msg) => msg.getType() === "tool").map((msg) => msg.tool_call_id)); + let aiMessage; + for (let i = messages.length - 1;i >= 0; i -= 1) { + const message = messages[i]; + if (AIMessage.isInstance(message)) { + aiMessage = message; + break; + } } + if (!AIMessage.isInstance(aiMessage)) + throw new Error("ToolNode only accepts AIMessages as input."); + outputs = await Promise.all(aiMessage.tool_calls?.filter((call3) => call3.id == null || !toolMessageIds.has(call3.id)).map((call3) => this.runTool(call3, config3, state)) ?? []); } - }; - } - async dispose() { - this.#thread = undefined; - const entries = [...this.#entries.values()]; - this.#entries.clear(); - await Promise.all(entries.map(async (entry) => { - if (entry.runtime != null) - await tryDispose(entry.runtime); - })); - } - get size() { - return this.#entries.size; - } -}; -var init_channel_registry = __esm(() => { - init_store2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/namespace.js -function namespaceKey2(namespace) { - return namespace.join("\x00"); -} -function isRootNamespace(namespace) { - return namespace.length === 0; -} -function isToolNamespaceSegment(segment) { - return segment.startsWith("tools:"); -} -function isTaskNamespaceSegment(segment) { - return segment.startsWith("task:"); -} -function isInternalWorkNamespace(namespace) { - return namespace.some((segment) => isTaskNamespaceSegment(segment) || isToolNamespaceSegment(segment)); -} -function isLegacySubagentNamespace(namespace) { - return namespace.some(isTaskNamespaceSegment); -} -function isConcreteToolNamespace(namespace) { - const last = namespace.at(-1); - return last != null && isToolNamespaceSegment(last); -} -var init_namespace2 = __esm(() => { - init_constants5(); + if (!outputs.some(isCommand)) + return Array.isArray(state) ? outputs : { messages: outputs }; + const combinedOutputs = []; + let parentCommand = null; + for (const output of outputs) + if (isCommand(output)) + if (output.graph === Command.PARENT && Array.isArray(output.goto) && output.goto.every((send) => isSend(send))) + if (parentCommand) + parentCommand.goto.push(...output.goto); + else + parentCommand = new Command({ + graph: Command.PARENT, + goto: output.goto + }); + else + combinedOutputs.push(output); + else + combinedOutputs.push(Array.isArray(state) ? [output] : { messages: [output] }); + if (parentCommand) + combinedOutputs.push(parentCommand); + return combinedOutputs; + } + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/discovery/subagents.js -function shouldPromoteToObservedNamespace(entry) { - return entry.name === "fanout-worker" || /^Worker worker-\d+/i.test(entry.taskInput ?? ""); -} -function taskWorkNamespace(toolCallId, eventNamespace) { - const last = eventNamespace.at(-1); - if (last != null && isToolNamespaceSegment(last)) - return [...eventNamespace]; - return [`tools:${toolCallId}`]; -} -function toSnapshot(entry) { - return { - id: entry.id, - name: entry.name, - namespace: entry.namespace, - parentId: entry.parentId, - depth: entry.depth, - status: entry.status, - taskInput: entry.taskInput, - output: entry.output, - error: entry.error, - startedAt: entry.startedAt, - completedAt: entry.completedAt - }; -} -function parseTaskInput(raw2) { - if (raw2 == null) - return {}; - if (typeof raw2 === "string") - try { - const parsed = JSON.parse(raw2); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/middleware.js +var AgentContext = class { +}, AgentRuntime = class { +}, MiddlewareNode; +var init_middleware2 = __esm(() => { + init_RunnableCallable(); + init_utils13(); + init_utils10(); + init_types3(); + MiddlewareNode = class extends RunnableCallable2 { + constructor(fields) { + super(fields); + } + async invokeMiddleware(invokeState, config3) { + let filteredContext = {}; + if (this.middleware.contextSchema) { + const schemaShape = this.middleware.contextSchema?.shape; + if (schemaShape) { + const relevantContext = {}; + const invokeContext = config3?.context || {}; + for (const key of Object.keys(schemaShape)) + if (key in invokeContext) + relevantContext[key] = invokeContext[key]; + filteredContext = interopParse(this.middleware.contextSchema, relevantContext); + } + } + const state = { + ...invokeState, + messages: invokeState.messages + }; + const runtime = { + context: filteredContext, + store: config3?.store, + configurable: config3?.configurable, + writer: config3?.writer, + interrupt: config3?.interrupt, + signal: config3?.signal + }; + const result = await this.runHook(state, Object.freeze(Object.assign(new AgentRuntime, { + ...runtime, + context: Object.freeze(Object.assign(new AgentContext, filteredContext)) + }))); + if (!result) + return { jumpTo: undefined }; + let jumpToConstraint; + let constraint; + if (this.name?.startsWith("BeforeAgentNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.beforeAgent); + constraint = "beforeAgent.canJumpTo"; + } else if (this.name?.startsWith("BeforeModelNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.beforeModel); + constraint = "beforeModel.canJumpTo"; + } else if (this.name?.startsWith("AfterAgentNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.afterAgent); + constraint = "afterAgent.canJumpTo"; + } else if (this.name?.startsWith("AfterModelNode_")) { + jumpToConstraint = getHookConstraint(this.middleware.afterModel); + constraint = "afterModel.canJumpTo"; + } + if (typeof result.jumpTo === "string" && !jumpToConstraint?.includes(result.jumpTo)) { + const suggestion = jumpToConstraint && jumpToConstraint.length > 0 ? `must be one of: ${jumpToConstraint?.join(", ")}.` : constraint ? `no ${constraint} defined in middleware ${this.middleware.name}` : ""; + throw new Error(`Invalid jump target: ${result.jumpTo}, ${suggestion}.`); + } + if (typeof result === "object" && "type" in result) { + if (result.type === "terminate") { + if (result.error) + throw result.error; + return { + ...state, + ...result.result || {}, + jumpTo: result.jumpTo + }; + } + throw new Error(`Invalid control action: ${JSON.stringify(result)}`); + } return { - description: typeof parsed.description === "string" ? parsed.description : undefined, - subagent_type: typeof parsed.subagent_type === "string" ? parsed.subagent_type : undefined + ...state, + ...result, + jumpTo: result.jumpTo }; - } catch { - return {}; } - if (typeof raw2 === "object" && !Array.isArray(raw2)) { - const obj = raw2; - return { - description: typeof obj.description === "string" ? obj.description : undefined, - subagent_type: typeof obj.subagent_type === "string" ? obj.subagent_type : undefined - }; - } - return {}; -} -function getTaskToolCalls(message) { - if (message == null || typeof message !== "object" || Array.isArray(message)) - return []; - const record2 = message; - const toolCalls = record2.tool_calls ?? record2.kwargs?.tool_calls ?? record2.lc_kwargs?.tool_calls; - if (!Array.isArray(toolCalls)) - return []; - const result = []; - for (const toolCall of toolCalls) { - if (toolCall == null || typeof toolCall !== "object" || Array.isArray(toolCall)) - continue; - const record3 = toolCall; - if (typeof record3.id !== "string" || record3.name !== "task") - continue; - result.push({ - id: record3.id, - input: parseTaskInput(record3.args) - }); - } - return result; -} -function getToolMessageCallId(message) { - if (message == null || typeof message !== "object" || Array.isArray(message)) - return; - const record2 = message; - const id = record2.tool_call_id ?? record2.kwargs?.tool_call_id ?? record2.lc_kwargs?.tool_call_id; - return typeof id === "string" && id.length > 0 ? id : undefined; -} -function lineageFromNamespace(namespace) { - if (isRootNamespace(namespace)) - return { - parentId: null, - depth: 1 - }; - const last = namespace[namespace.length - 1]; - if (last == null) - return { - parentId: null, - depth: 1 - }; - const trimmed = last.split(":").filter((part) => part.length > 0).slice(1); - const depth = Math.max(1, trimmed.length); - return { - parentId: (trimmed.length >= 2 ? trimmed[trimmed.length - 2] : null) ?? null, - depth + get nodeOptions() { + return { input: derivePrivateState(this.middleware.stateSchema) }; + } }; -} -var SubagentDiscovery = class { - store = new StreamStore(/* @__PURE__ */ new Map); - #map = /* @__PURE__ */ new Map; - #taskIdByObservedNamespace = /* @__PURE__ */ new Map; - #observedOwnNamespaces = /* @__PURE__ */ new Set; - push(event) { - if (event.method === "tools") - this.#onToolEvent(event); - else if (event.method === "values") - this.#onValuesEvent(event); - } - get snapshot() { - return this.store.getSnapshot(); - } - discoverFromMessage(message, namespace) { - let changed = false; - for (const toolCall of getTaskToolCalls(message)) - changed = this.#upsertTaskToolCall(toolCall.id, toolCall.input, namespace) || changed; - if (changed) - this.#commit(); - } - #commit() { - this.store.setValue(new Map([...this.#map.values()].map((entry) => [entry.id, toSnapshot(entry)]))); - } - #onToolEvent(event) { - const data = event.params.data; - const toolCallId = data.tool_call_id; - const toolName = data.tool_name; - if (data.event === "tool-started" && toolName === "task") { - const input = parseTaskInput(data.input); - if (toolCallId == null) - return; - this.#upsertTaskToolCall(toolCallId, input, event.params.namespace); - this.#commit(); - return; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/BeforeAgentNode.js +var BeforeAgentNode; +var init_BeforeAgentNode = __esm(() => { + init_utils10(); + init_middleware2(); + BeforeAgentNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "beforeAgentNodes" + ]; + constructor(middleware) { + super({ + name: `BeforeAgentNode_${middleware.name}`, + func: async (state, config3) => this.invokeMiddleware(state, config3) + }); + this.middleware = middleware; } - if (toolCallId == null) - return; - const entry = this.#map.get(toolCallId); - if (entry == null) - return; - if (data.event === "tool-finished") { - entry.status = "complete"; - entry.output = data.output; - entry.completedAt = /* @__PURE__ */ new Date; - this.#commit(); - return; + runHook(state, runtime) { + return getHookFunction(this.middleware.beforeAgent)(state, runtime); } - if (data.event === "tool-error") { - entry.status = "error"; - entry.error = data.message ?? "Subagent failed"; - entry.completedAt = /* @__PURE__ */ new Date; - this.#commit(); + }; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/BeforeModelNode.js +var BeforeModelNode; +var init_BeforeModelNode = __esm(() => { + init_utils10(); + init_middleware2(); + BeforeModelNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "beforeModelNodes" + ]; + constructor(middleware) { + super({ + name: `BeforeModelNode_${middleware.name}`, + func: async (state, config3) => this.invokeMiddleware(state, config3) + }); + this.middleware = middleware; } - } - #onValuesEvent(event) { - const data = event.params.data; - if (data == null || typeof data !== "object" || Array.isArray(data)) - return; - const messages = data.messages; - if (!Array.isArray(messages)) - return; - let changed = this.#recordObservedWorkNamespace(event.params.namespace); - for (const message of messages) { - for (const toolCall of getTaskToolCalls(message)) - changed = this.#upsertTaskToolCall(toolCall.id, toolCall.input, event.params.namespace) || changed; - const toolCallId = getToolMessageCallId(message); - if (toolCallId == null) - continue; - const existing = this.#map.get(toolCallId); - if (existing == null) - continue; - existing.status = "complete"; - existing.output = message; - existing.completedAt = /* @__PURE__ */ new Date; - changed = true; + runHook(state, runtime) { + return getHookFunction(this.middleware.beforeModel)(state, runtime); } - if (changed) - this.#commit(); - } - #upsertTaskToolCall(toolCallId, input, eventNamespace) { - const namespace = taskWorkNamespace(toolCallId, eventNamespace); - const existing = this.#map.get(toolCallId); - if (existing != null) { - let changed = false; - this.#recordTaskNamespaceCandidate(toolCallId, eventNamespace); - const nextName = input.subagent_type ?? existing.name; - const nextTaskInput = input.description ?? existing.taskInput; - if (existing.name !== nextName) { - existing.name = nextName; - changed = true; + }; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/AfterModelNode.js +var AfterModelNode; +var init_AfterModelNode = __esm(() => { + init_utils10(); + init_middleware2(); + AfterModelNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "afterModelNodes" + ]; + constructor(middleware) { + super({ + name: `AfterModelNode_${middleware.name}`, + func: async (state, config3) => this.invokeMiddleware(state, config3) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.afterModel)(state, runtime); + } + }; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/nodes/AfterAgentNode.js +var AfterAgentNode; +var init_AfterAgentNode = __esm(() => { + init_utils10(); + init_middleware2(); + AfterAgentNode = class extends MiddlewareNode { + lc_namespace = [ + "langchain", + "agents", + "afterAgentNodes" + ]; + constructor(middleware) { + super({ + name: `AfterAgentNode_${middleware.name}`, + func: async (state, config3) => this.invokeMiddleware(state, config3) + }); + this.middleware = middleware; + } + runHook(state, runtime) { + return getHookFunction(this.middleware.afterAgent)(state, runtime); + } + }; +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/ReactAgent.js +var ReactAgent = class ReactAgent2 { + #graph; + #toolBehaviorVersion = "v2"; + #agentNode; + #defaultConfig; + constructor(options, defaultConfig) { + this.options = options; + this.#defaultConfig = mergeConfigs(defaultConfig ?? {}, { + metadata: { ls_integration: "langchain_create_agent" }, + configurable: { ls_agent_type: "root" } + }); + if (options.name) + this.#defaultConfig = mergeConfigs(this.#defaultConfig, { metadata: { lc_agent_name: options.name } }); + this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion; + if (!options.model) + throw new Error("`model` option is required to create an agent."); + if (typeof options.model !== "string") + validateLLMHasNoBoundTools(options.model); + const middlewareTools = this.options.middleware?.filter((m) => m.tools).flatMap((m) => m.tools) ?? []; + const toolClasses = [...options.tools ?? [], ...middlewareTools]; + const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool2) => ("returnDirect" in tool2) && tool2.returnDirect).map((tool2) => tool2.name)); + const hasDynamicStructuredResponse = Boolean(this.options.middleware?.some((middleware2) => middleware2.wrapModelCall)); + const { state, input, output } = createAgentState(this.options.responseFormat !== undefined || hasDynamicStructuredResponse, this.options.stateSchema, this.options.middleware); + const allNodeWorkflows = new StateGraph(state, { + input, + output, + context: this.options.contextSchema + }); + const beforeAgentNodes = []; + const beforeModelNodes = []; + const afterModelNodes = []; + const afterAgentNodes = []; + const wrapModelCallHookMiddleware = []; + this.#agentNode = new AgentNode({ + model: this.options.model, + systemMessage: normalizeSystemPrompt(this.options.systemPrompt), + includeAgentName: this.options.includeAgentName, + name: this.options.name, + responseFormat: this.options.responseFormat, + middleware: this.options.middleware, + toolClasses, + shouldReturnDirect, + signal: this.options.signal, + wrapModelCallHookMiddleware + }); + const middlewareNames = /* @__PURE__ */ new Set; + const middleware = this.options.middleware ?? []; + for (let i = 0;i < middleware.length; i++) { + let beforeAgentNode; + let beforeModelNode; + let afterModelNode; + let afterAgentNode; + const m = middleware[i]; + if (middlewareNames.has(m.name)) + throw new Error(`Middleware ${m.name} is defined multiple times`); + middlewareNames.add(m.name); + if (m.beforeAgent) { + beforeAgentNode = new BeforeAgentNode(m); + const name = `${m.name}.before_agent`; + beforeAgentNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.beforeAgent) + }); + allNodeWorkflows.addNode(name, beforeAgentNode, beforeAgentNode.nodeOptions); } - if (existing.taskInput !== nextTaskInput) { - existing.taskInput = nextTaskInput; - changed = true; + if (m.beforeModel) { + beforeModelNode = new BeforeModelNode(m); + const name = `${m.name}.before_model`; + beforeModelNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.beforeModel) + }); + allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions); } - const namespaceKeyed = namespaceKey2(existing.namespace); - const ownNamespaceKey = `tools:${toolCallId}`; - const nextNamespaceKey = namespaceKey2(namespace); - if (isConcreteToolNamespace(eventNamespace) || namespaceKeyed === ownNamespaceKey) { - if (namespaceKeyed === ownNamespaceKey && nextNamespaceKey !== ownNamespaceKey && this.#observedOwnNamespaces.has(toolCallId)) - return changed; - if (namespaceKeyed !== nextNamespaceKey) { - existing.namespace = namespace; - changed = true; - } + if (m.afterModel) { + afterModelNode = new AfterModelNode(m); + const name = `${m.name}.after_model`; + afterModelNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.afterModel) + }); + allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions); } - if (existing.status !== "complete" && existing.status !== "error") { - if (existing.status !== "running") { - existing.status = "running"; - changed = true; - } + if (m.afterAgent) { + afterAgentNode = new AfterAgentNode(m); + const name = `${m.name}.after_agent`; + afterAgentNodes.push({ + index: i, + name, + allowed: getHookConstraint(m.afterAgent) + }); + allNodeWorkflows.addNode(name, afterAgentNode, afterAgentNode.nodeOptions); } - return changed; + if (m.wrapModelCall) + wrapModelCallHookMiddleware.push(m); } - const { parentId, depth } = lineageFromNamespace(eventNamespace); - this.#recordTaskNamespaceCandidate(toolCallId, eventNamespace); - this.#map.set(toolCallId, { - id: toolCallId, - name: input.subagent_type ?? "unknown", - namespace, - parentId, - depth, - status: "running", - taskInput: input.description, - output: undefined, - error: undefined, - startedAt: /* @__PURE__ */ new Date, - completedAt: null + allNodeWorkflows.addNode(AGENT_NODE_NAME, this.#agentNode); + const hasWrapToolCallMiddleware = middleware.some((m) => m.wrapToolCall); + const clientTools = toolClasses.filter(isClientTool); + if (clientTools.length > 0 || hasWrapToolCallMiddleware) { + const toolNode = new ToolNode(clientTools, { + signal: this.options.signal, + wrapToolCall: wrapToolCall(middleware) + }); + allNodeWorkflows.addNode(TOOLS_NODE_NAME, toolNode); + } + let entryNode; + if (beforeAgentNodes.length > 0) + entryNode = beforeAgentNodes[0].name; + else if (beforeModelNodes.length > 0) + entryNode = beforeModelNodes[0].name; + else + entryNode = AGENT_NODE_NAME; + const loopEntryNode = beforeModelNodes.length > 0 ? beforeModelNodes[0].name : AGENT_NODE_NAME; + const exitNode = afterAgentNodes.length > 0 ? afterAgentNodes[afterAgentNodes.length - 1].name : END; + allNodeWorkflows.addEdge(START, entryNode); + const hasToolsAvailable = clientTools.length > 0 || hasWrapToolCallMiddleware; + for (let i = 0;i < beforeAgentNodes.length; i++) { + const node = beforeAgentNodes[i]; + const current = node.name; + const nextDefault = i === beforeAgentNodes.length - 1 ? loopEntryNode : beforeAgentNodes[i + 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(new Set([nextDefault, ...allowedMapped.map((dest) => dest === END ? exitNode : dest)])); + allNodeWorkflows.addConditionalEdges(current, this.#createBeforeAgentRouter(clientTools, nextDefault, exitNode, hasToolsAvailable), destinations); + } else + allNodeWorkflows.addEdge(current, nextDefault); + } + for (let i = 0;i < beforeModelNodes.length; i++) { + const node = beforeModelNodes[i]; + const current = node.name; + const nextDefault = i === beforeModelNodes.length - 1 ? AGENT_NODE_NAME : beforeModelNodes[i + 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createBeforeModelRouter(clientTools, nextDefault, hasToolsAvailable), destinations); + } else + allNodeWorkflows.addEdge(current, nextDefault); + } + const lastAfterModelNode = afterModelNodes.at(-1); + if (afterModelNodes.length > 0 && lastAfterModelNode) + allNodeWorkflows.addEdge(AGENT_NODE_NAME, lastAfterModelNode.name); + else { + const destinations = this.#getModelPaths(clientTools, false, hasToolsAvailable).map((p) => p === END ? exitNode : p); + if (destinations.length === 1) + allNodeWorkflows.addEdge(AGENT_NODE_NAME, destinations[0]); + else + allNodeWorkflows.addConditionalEdges(AGENT_NODE_NAME, this.#createModelRouter(exitNode), destinations); + } + for (let i = afterModelNodes.length - 1;i > 0; i--) { + const node = afterModelNodes[i]; + const current = node.name; + const nextDefault = afterModelNodes[i - 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); + } else + allNodeWorkflows.addEdge(current, nextDefault); + } + if (afterModelNodes.length > 0) { + const firstAfterModel = afterModelNodes[0]; + const firstAfterModelNode = firstAfterModel.name; + const modelPaths = this.#getModelPaths(clientTools, true, hasToolsAvailable).filter((p) => p !== "tools" || hasToolsAvailable); + const allowJump = Boolean(firstAfterModel.allowed && firstAfterModel.allowed.length > 0); + const destinations = modelPaths.map((p) => p === END ? exitNode : p); + allNodeWorkflows.addConditionalEdges(firstAfterModelNode, this.#createAfterModelRouter(clientTools, allowJump, exitNode, hasToolsAvailable), destinations); + } + for (let i = afterAgentNodes.length - 1;i > 0; i--) { + const node = afterAgentNodes[i]; + const current = node.name; + const nextDefault = afterAgentNodes[i - 1].name; + if (node.allowed && node.allowed.length > 0) { + const allowedMapped = node.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(new Set([nextDefault, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(current, this.#createAfterModelSequenceRouter(clientTools, node.allowed, nextDefault, hasToolsAvailable), destinations); + } else + allNodeWorkflows.addEdge(current, nextDefault); + } + if (afterAgentNodes.length > 0) { + const firstAfterAgent = afterAgentNodes[0]; + const firstAfterAgentNode = firstAfterAgent.name; + if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) { + const allowedMapped = firstAfterAgent.allowed.map((t) => parseJumpToTarget(t)).filter((dest) => dest !== "tools" || hasToolsAvailable); + const destinations = Array.from(new Set([END, ...allowedMapped])); + allNodeWorkflows.addConditionalEdges(firstAfterAgentNode, this.#createAfterModelSequenceRouter(clientTools, firstAfterAgent.allowed, END, hasToolsAvailable), destinations); + } else + allNodeWorkflows.addEdge(firstAfterAgentNode, END); + } + if (hasToolsAvailable) { + const toolReturnTarget = loopEntryNode; + if (shouldReturnDirect.size > 0) + allNodeWorkflows.addConditionalEdges(TOOLS_NODE_NAME, this.#createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget), [toolReturnTarget, exitNode]); + else + allNodeWorkflows.addEdge(TOOLS_NODE_NAME, toolReturnTarget); + } + const compileTransformers = [createToolCallTransformer([]), ...this.options.streamTransformers ?? []]; + this.#graph = allNodeWorkflows.compile({ + checkpointer: this.options.checkpointer, + store: this.options.store, + name: this.options.name, + description: this.options.description, + transformers: compileTransformers }); - return true; } - #recordObservedWorkNamespace(namespace) { - if (!isConcreteToolNamespace(namespace)) - return false; - const last = namespace.at(-1); - if (last == null) - return false; - const namespaceKeyed = namespaceKey2(namespace); - const toolCallId = this.#taskIdByObservedNamespace.get(namespaceKeyed) ?? last.slice(6); - const existing = this.#map.get(toolCallId); - if (existing == null) - return false; - if (namespaceKeyed === `tools:${toolCallId}`) - this.#observedOwnNamespaces.add(toolCallId); - else if (this.#observedOwnNamespaces.has(toolCallId) || !this.#taskIdByObservedNamespace.has(namespaceKeyed) && !shouldPromoteToObservedNamespace(existing)) - return false; - if (namespaceKey2(existing.namespace) === namespaceKeyed) - return false; - existing.namespace = [...namespace]; - return true; + get graph() { + return this.#graph; } - #recordTaskNamespaceCandidate(toolCallId, namespace) { - if (!isConcreteToolNamespace(namespace)) - return; - this.#taskIdByObservedNamespace.set(namespaceKey2(namespace), toolCallId); + get checkpointer() { + return this.#graph.checkpointer; } -}; -var init_subagents2 = __esm(() => { - init_store2(); - init_namespace2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/discovery/subgraphs.js -function parseNodeName(segment) { - const colon = segment.indexOf(":"); - return colon === -1 ? segment : segment.slice(0, colon); -} -var SubgraphDiscovery = class { - store = new StreamStore(/* @__PURE__ */ new Map); - byNodeStore = new StreamStore(/* @__PURE__ */ new Map); - #shadow = /* @__PURE__ */ new Map; - #promoted = /* @__PURE__ */ new Set; - push(event) { - if (event.method === "values") { - this.#onValuesEvent(event); - return; - } - if (event.method !== "lifecycle") - return; - const lifecycle = event; - const namespace = lifecycle.params.namespace; - if (isRootNamespace(namespace)) - return; - const id = namespaceKey2(namespace); - const data = lifecycle.params.data; - const nodeName = parseNodeName(namespace[namespace.length - 1] ?? ""); - let touched = false; - for (let depth = 1;depth < namespace.length; depth += 1) { - const ancestorId = namespaceKey2(namespace.slice(0, depth)); - if (!this.#promoted.has(ancestorId)) { - this.#promoted.add(ancestorId); - if (this.#shadow.has(ancestorId)) - touched = true; + set checkpointer(value) { + this.#graph.checkpointer = value; + } + get store() { + return this.#graph.store; + } + set store(value) { + this.#graph.store = value; + } + withConfig(config3) { + return new ReactAgent2(this.options, mergeConfigs(this.#defaultConfig, config3)); + } + #getModelPaths(toolClasses, includeModelRequest = false, hasToolsAvailable = toolClasses.length > 0) { + const paths = []; + if (hasToolsAvailable) + paths.push(TOOLS_NODE_NAME); + if (includeModelRequest) + paths.push(AGENT_NODE_NAME); + paths.push(END); + return paths; + } + #createToolsRouter(shouldReturnDirect, exitNode, toolReturnTarget) { + return (state) => { + const messages = state.messages; + const lastMessage = messages[messages.length - 1]; + if (ToolMessage.isInstance(lastMessage) && lastMessage.name && shouldReturnDirect.has(lastMessage.name)) + return this.options.responseFormat ? toolReturnTarget : exitNode; + return toolReturnTarget; + }; + } + #createModelRouter(exitNode = END) { + return (state) => { + const lastMessage = state.messages.at(-1); + if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) + return exitNode; + if (lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-"))) + return exitNode; + if (this.#toolBehaviorVersion === "v1") + return TOOLS_NODE_NAME; + const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); + if (regularToolCalls.length === 0) + return exitNode; + return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + }; + } + #createAfterModelRouter(toolClasses, allowJump, exitNode, hasToolsAvailable = toolClasses.length > 0) { + const hasStructuredResponse = Boolean(this.options.responseFormat); + return (state) => { + const builtInState = state; + const messages = builtInState.messages; + const lastMessage = messages.at(-1); + if (AIMessage.isInstance(lastMessage) && (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)) + return exitNode; + if (allowJump && builtInState.jumpTo) { + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === END) + return exitNode; + if (destination === "tools") { + if (!hasToolsAvailable) + return exitNode; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: undefined + }); + } + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: undefined + }); } - } - if (data.event === "started") { - if (!this.#shadow.has(id)) { - this.#shadow.set(id, { - id, - namespace: [...namespace], - nodeName, - status: "running", - startedAt: /* @__PURE__ */ new Date, - completedAt: null + const toolMessages = messages.filter(ToolMessage.isInstance); + const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1); + const pendingToolCalls = lastAiMessage?.tool_calls?.filter((call3) => !toolMessages.some((m) => m.tool_call_id === call3.id)); + if (pendingToolCalls && pendingToolCalls.length > 0) { + if (this.#toolBehaviorVersion === "v1") + return TOOLS_NODE_NAME; + return pendingToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + } + const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some((toolCall) => toolCall.name.startsWith("extract-")); + if (pendingToolCalls && pendingToolCalls.length === 0 && !hasStructuredResponseCalls && hasStructuredResponse) + return AGENT_NODE_NAME; + if (!AIMessage.isInstance(lastMessage) || !lastMessage.tool_calls || lastMessage.tool_calls.length === 0) + return exitNode; + const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every((toolCall) => toolCall.name.startsWith("extract-")); + const hasRegularToolCalls = lastMessage.tool_calls.some((toolCall) => !toolCall.name.startsWith("extract-")); + if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) + return exitNode; + if (this.#toolBehaviorVersion === "v1") + return TOOLS_NODE_NAME; + const regularToolCalls = lastMessage.tool_calls.filter((toolCall) => !toolCall.name.startsWith("extract-")); + if (regularToolCalls.length === 0) + return exitNode; + return regularToolCalls.map((toolCall) => new Send(TOOLS_NODE_NAME, { + ...state, + lg_tool_call: toolCall + })); + }; + } + #createAfterModelSequenceRouter(toolClasses, allowed, nextDefault, hasToolsAvailable = toolClasses.length > 0) { + const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t))); + return (state) => { + const builtInState = state; + if (builtInState.jumpTo) { + const dest = parseJumpToTarget(builtInState.jumpTo); + if (dest === END && allowedSet.has(END)) + return END; + if (dest === "tools" && allowedSet.has("tools")) { + if (!hasToolsAvailable) + return END; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: undefined + }); + } + if (dest === "model_request" && allowedSet.has("model_request")) + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: undefined + }); + } + return nextDefault; + }; + } + #createBeforeAgentRouter(toolClasses, nextDefault, exitNode, hasToolsAvailable = toolClasses.length > 0) { + return (state) => { + const builtInState = state; + if (!builtInState.jumpTo) + return nextDefault; + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === END) + return exitNode; + if (destination === "tools") { + if (!hasToolsAvailable) + return exitNode; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: undefined }); - if (this.#promoted.has(id)) - touched = true; } - } else if (data.event === "completed" || data.event === "interrupted" || data.event === "failed") { - const entry = this.#ensureShadow(id, namespace, nodeName); - if (data.event === "failed") - entry.status = "error"; - else - entry.status = "complete"; - entry.completedAt = /* @__PURE__ */ new Date; - if (this.#promoted.has(id)) - touched = true; - } - if (touched) - this.#commit(); + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: undefined + }); + }; } - #onValuesEvent(event) { - const namespace = event.params.namespace; - if (isRootNamespace(namespace)) - return; - if (isInternalWorkNamespace(namespace)) - return; - const data = event.params.data; - if (data == null || typeof data !== "object" || Array.isArray(data)) - return; - const id = namespaceKey2(namespace); - const nodeName = parseNodeName(namespace[namespace.length - 1] ?? ""); - const entry = this.#ensureShadow(id, namespace, nodeName); - entry.status = "running"; - if (!this.#promoted.has(id)) - this.#promoted.add(id); - this.#commit(); + #createBeforeModelRouter(toolClasses, nextDefault, hasToolsAvailable = toolClasses.length > 0) { + return (state) => { + const builtInState = state; + if (!builtInState.jumpTo) + return nextDefault; + const destination = parseJumpToTarget(builtInState.jumpTo); + if (destination === END) + return END; + if (destination === "tools") { + if (!hasToolsAvailable) + return END; + return new Send(TOOLS_NODE_NAME, { + ...state, + jumpTo: undefined + }); + } + return new Send(AGENT_NODE_NAME, { + ...state, + jumpTo: undefined + }); + }; } - get snapshot() { - return this.store.getSnapshot(); + async#initializeMiddlewareStates(state, config3) { + if (!this.options.middleware || this.options.middleware.length === 0 || state instanceof Command || !state) + return state; + const defaultStates = await initializeMiddlewareStates(this.options.middleware, state); + const updatedState = { + ...(await this.#graph.getState(config3).catch(() => ({ values: {} }))).values, + ...state + }; + if (!updatedState) + return updatedState; + for (const [key, value] of Object.entries(defaultStates)) + if (!(key in updatedState)) + updatedState[key] = value; + return updatedState; } - get byNodeSnapshot() { - return this.byNodeStore.getSnapshot(); + async invoke(state, config3) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config3); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return this.#graph.invoke(initializedState, mergedConfig); } - #ensureShadow(id, namespace, nodeName) { - let entry = this.#shadow.get(id); - if (entry == null) { - entry = { - id, - namespace: [...namespace], - nodeName, - status: "running", - startedAt: /* @__PURE__ */ new Date, - completedAt: null - }; - this.#shadow.set(id, entry); - } - return entry; + async stream(state, config3) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config3); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return this.#graph.stream(initializedState, mergedConfig); } - #commit() { - const snapshots = []; - for (const id of this.#promoted) { - const entry = this.#shadow.get(id); - if (entry == null) - continue; - snapshots.push({ ...entry }); - } - this.store.setValue(new Map(snapshots.map((s) => [s.id, s]))); - const byNode = /* @__PURE__ */ new Map; - for (const snap of snapshots) { - const bucket = byNode.get(snap.nodeName); - if (bucket == null) - byNode.set(snap.nodeName, [snap]); - else - bucket.push(snap); + streamEvents(state, config3, streamOptions) { + if (config3?.version !== "v3" || streamOptions != null) { + const mergedConfig = mergeConfigs(this.#defaultConfig, config3); + const version6 = config3?.version === "v1" || config3?.version === "v2" ? config3.version : "v2"; + return this.#graph.streamEvents(state, { + ...mergedConfig, + version: version6 + }, streamOptions); } - this.byNodeStore.setValue(byNode); - } -}; -var init_subgraphs3 = __esm(() => { - init_store2(); - init_namespace2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/assembled-to-message.js -function assembledToBaseMessage(input) { - const { id, role, blocks: blocks2, toolCallId, usage } = input; - const textContent = extractContentString(blocks2); - const toolCalls = extractToolCalls(blocks2); - const toolCallChunks = extractToolCallChunks(blocks2); - const additionalKwargs = usage != null ? { usage } : undefined; - switch (role) { - case "human": - return new HumanMessage({ - ...id != null ? { id } : {}, - content: textContent, - ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {} - }); - case "system": - return new SystemMessage({ - ...id != null ? { id } : {}, - content: textContent, - ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {} - }); - case "tool": - return new ToolMessage({ - ...id != null ? { id } : {}, - content: textContent, - tool_call_id: toolCallId ?? "" + return (async () => { + const { transformers: callSiteTransformers, version: _version, ...restConfig } = config3 ?? {}; + const mergedConfig = mergeConfigs(this.#defaultConfig, restConfig); + const initializedState = await this.#initializeMiddlewareStates(state, mergedConfig); + return await this.#graph.streamEvents(initializedState, { + ...mergedConfig, + version: "v3", + transformers: callSiteTransformers }); - default: { - const payload = { - ...id != null ? { id } : {}, - content: cloneContentBlocks(blocks2), - ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}, - ...toolCallChunks.length > 0 ? { tool_call_chunks: toolCallChunks } : {}, - ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {}, - response_metadata: { output_version: "v1" } - }; - return toolCallChunks.length > 0 ? new AIMessageChunk(payload) : new AIMessage(payload); - } + })(); } -} -function assembledMessageToBaseMessage(assembled, role, extras = {}) { - return assembledToBaseMessage({ - id: assembled.id, - role, - blocks: assembled.blocks, - toolCallId: extras.toolCallId, - usage: assembled.usage - }); -} -function extractContentString(blocks2) { - let out = ""; - for (const block of blocks2) - if (block.type === "text" && typeof block.text === "string") - out += block.text; - return out; -} -function cloneContentBlocks(blocks2) { - return blocks2.map((block) => structuredClone(block)); -} -function extractToolCalls(blocks2) { - const out = []; - for (const block of blocks2) { - if (block.type !== "tool_call" && block.type !== "tool_use") - continue; - const tc = block; - out.push({ - id: tc.id ?? "", - name: tc.name ?? "", - args: normalizeToolCallArgs2(tc.args ?? tc.input), - type: "tool_call" - }); + async drawMermaidPng(params) { + const arrayBuffer = await (await (await this.#graph.getGraphAsync()).drawMermaidPng(params)).arrayBuffer(); + return new Uint8Array(arrayBuffer); } - return out; -} -function extractToolCallChunks(blocks2) { - const out = []; - for (const block of blocks2) { - if (block.type !== "tool_call_chunk") - continue; - const tc = block; - out.push({ - id: tc.id, - name: tc.name, - args: tc.args, - index: tc.index, - type: "tool_call_chunk" - }); + async drawMermaid(params) { + return (await this.#graph.getGraphAsync()).drawMermaid(params); } - return out; -} -function normalizeToolCallArgs2(value) { - if (value != null && typeof value === "object" && !Array.isArray(value)) - return value; - if (typeof value === "string" && value.length > 0) - try { - const parsed = JSON.parse(value); - if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) - return parsed; - } catch {} - return {}; -} -var init_assembled_to_message = __esm(() => { - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/message-metadata-tracker.js -var EMPTY_METADATA_MAP, MessageMetadataTracker = class { - store = new StreamStore(EMPTY_METADATA_MAP); - #pendingCheckpointByNamespace = /* @__PURE__ */ new Map; - reset() { - this.#pendingCheckpointByNamespace.clear(); - this.store.setState(() => EMPTY_METADATA_MAP); + getGraphAsync(config3) { + return this.#graph.getGraphAsync(config3); } - bufferCheckpoint(namespace, data) { - if (data == null || typeof data.id !== "string") - return; - const envelope = { id: data.id }; - if (typeof data.parent_id === "string") - envelope.parent_id = data.parent_id; - this.#pendingCheckpointByNamespace.set(namespaceKey2(namespace), envelope); + getState(config3, options) { + return this.#graph.getState(config3, options); } - consumeCheckpoint(namespace) { - const key = namespaceKey2(namespace); - const checkpoint = this.#pendingCheckpointByNamespace.get(key); - if (checkpoint != null) - this.#pendingCheckpointByNamespace.delete(key); - return checkpoint; + getStateHistory(config3, options) { + return this.#graph.getStateHistory(config3, options); } - recordMessages(messages, metadata) { - const current = this.store.getSnapshot(); - let changed = false; - const next = new Map(current); - for (const msg of messages) { - const id = msg?.id; - if (typeof id !== "string" || id.length === 0) - continue; - const prev = next.get(id); - if (prev != null && prev.parentCheckpointId === metadata.parentCheckpointId) - continue; - next.set(id, { - ...prev, - ...metadata - }); - changed = true; - } - if (changed) - this.store.setState(() => next); + getSubgraphs(namespace, recurse) { + return this.#graph.getSubgraphs(namespace, recurse); } -}; -var init_message_metadata_tracker = __esm(() => { - init_store2(); - init_namespace2(); - EMPTY_METADATA_MAP = /* @__PURE__ */ new Map; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/lifecycle-loading-tracker.js -var LifecycleLoadingTracker = class { - #store; - #isDisposed; - #lastTerminalLifecycleSeq = -1; - constructor(params) { - this.#store = params.store; - this.#isDisposed = params.isDisposed; + getSubgraphsAsync(namespace, recurse) { + return this.#graph.getSubgraphsAsync(namespace, recurse); } - listener = (event) => { - this.handle(event); - }; - reset() { - this.#lastTerminalLifecycleSeq = -1; + updateState(inputConfig, values, asNode) { + return this.#graph.updateState(inputConfig, values, asNode); } - handle(event) { - if (event.method !== "lifecycle") - return; - if (!isRootNamespace(event.params.namespace)) - return; - const lifecycle = event.params.data; - const seq = typeof event.seq === "number" ? event.seq : undefined; - if (lifecycle?.event === "running") { - if (seq != null && seq <= this.#lastTerminalLifecycleSeq) - return; - this.#store.setState((s) => s.isLoading ? s : { - ...s, - isLoading: true - }); - return; - } - if (lifecycle?.event === "completed" || lifecycle?.event === "failed" || lifecycle?.event === "interrupted" || lifecycle?.event === "cancelled") { - if (seq != null) - this.#lastTerminalLifecycleSeq = Math.max(this.#lastTerminalLifecycleSeq, seq); - setTimeout(() => { - if (this.#isDisposed()) - return; - this.#store.setState((s) => s.isLoading ? { - ...s, - isLoading: false - } : s); - }, 0); - } + get builder() { + return this.#graph.builder; } }; -var init_lifecycle_loading_tracker = __esm(() => { - init_namespace2(); +var init_ReactAgent = __esm(() => { + init_annotation2(); + init_utils12(); + init_utils13(); + init_AgentNode(); + init_ToolNode(); + init_utils10(); + init_BeforeAgentNode(); + init_BeforeModelNode(); + init_AfterModelNode(); + init_AfterAgentNode(); + init_stream6(); + init_messages(); + init_runnables(); + init_dist4(); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/message-reconciliation.js -function reconcileMessagesFromValues({ valueMessages, currentMessages, currentIndexById, previousValueMessageIds, streamedMessageIds, preferValuesMessage }) { - const valueMessageIds = /* @__PURE__ */ new Set; - const merged = []; - for (const valuesMessage of valueMessages) { - const id = normalizedMessageId(valuesMessage); - if (id == null) { - merged.push(valuesMessage); - continue; - } - valueMessageIds.add(id); - const streamIdx = currentIndexById.get(id); - const streamedMessage = streamIdx != null && (streamedMessageIds == null || streamedMessageIds.has(id)) ? currentMessages[streamIdx] : undefined; - if (streamedMessage != null && preferValuesMessage?.(valuesMessage, streamedMessage) !== true) - merged.push(streamedMessage); - else - merged.push(valuesMessage); - } - for (const existing of currentMessages) { - const id = normalizedMessageId(existing); - if (id == null) - continue; - if (valueMessageIds.has(id)) - continue; - if (previousValueMessageIds.has(id)) - continue; - if (streamedMessageIds != null && !streamedMessageIds.has(id)) - continue; - merged.push(existing); - } - return { - messages: messagesEqualList(currentMessages, merged) ? currentMessages : merged, - valueMessageIds - }; -} -function buildMessageIndex(messages) { - const index2 = /* @__PURE__ */ new Map; - messages.forEach((message, idx) => { - const id = normalizedMessageId(message); - if (id != null) - index2.set(id, idx); - }); - return index2; -} -function shouldPreferValuesMessageForToolCalls(valuesMessage, streamedMessage) { - const valuesToolCalls = getMessageToolCalls(valuesMessage); - if (valuesToolCalls.length === 0) - return false; - const streamedToolCalls = getMessageToolCalls(streamedMessage); - if (streamedToolCalls.length < valuesToolCalls.length) - return true; - const streamedIds = new Set(streamedToolCalls.map((toolCall) => toolCall.id).filter((id) => typeof id === "string" && id.length > 0)); - if (valuesToolCalls.some((toolCall) => { - return typeof toolCall.id === "string" && !streamedIds.has(toolCall.id); - })) - return true; - return valuesToolCalls.some((valuesToolCall) => { - const streamedToolCall = streamedToolCalls.find((candidate) => typeof valuesToolCall.id === "string" && candidate.id === valuesToolCall.id); - return streamedToolCall != null && hasMeaningfulArgs(valuesToolCall.args) && !jsonishEqual(valuesToolCall.args, streamedToolCall.args); - }); -} -function hasMeaningfulArgs(args) { - if (args == null) - return false; - if (typeof args === "string") - return args.length > 0; - if (typeof args === "object") - return Object.keys(args).length > 0; - return true; -} -function messagesEqualList(previous, next) { - if (previous === next) - return true; - if (previous.length !== next.length) - return false; - for (let i = 0;i < previous.length; i += 1) - if (!messagesEqual(previous[i], next[i])) - return false; - return true; -} -function messagesEqual(previous, next) { - if (previous === next) - return true; - if (previous == null || next == null) - return false; - const previousRecord = previous; - const nextRecord = next; - const previousType = typeof previous.getType === "function" ? previous.getType() : previousRecord.type; - const nextType = typeof next.getType === "function" ? next.getType() : nextRecord.type; - return previous.id === next.id && previousType === nextType && jsonishEqual(previous.content, next.content) && previousRecord.tool_call_id === nextRecord.tool_call_id && previousRecord.status === nextRecord.status && jsonishEqual(previousRecord.additional_kwargs, nextRecord.additional_kwargs) && jsonishEqual(previousRecord.response_metadata, nextRecord.response_metadata) && jsonishEqual(previousRecord.tool_calls, nextRecord.tool_calls) && jsonishEqual(previousRecord.tool_call_chunks, nextRecord.tool_call_chunks) && jsonishEqual(previousRecord.usage_metadata, nextRecord.usage_metadata); -} -function normalizedMessageId(message) { - return typeof message.id === "string" && message.id.length > 0 ? message.id : undefined; -} -function getMessageToolCalls(message) { - const raw2 = message.tool_calls; - if (!Array.isArray(raw2)) - return []; - return raw2.filter((toolCall) => toolCall != null && typeof toolCall === "object"); -} -function jsonishEqual(previous, next) { - return jsonishEqualAtDepth(previous, next, 0); -} -function jsonishEqualAtDepth(previous, next, depth) { - if (Object.is(previous, next)) - return true; - if (previous == null || next == null) - return false; - if (typeof previous !== "object" || typeof next !== "object") - return false; - if (depth >= 4) - return false; - if (Array.isArray(previous) || Array.isArray(next)) { - if (!Array.isArray(previous) || !Array.isArray(next)) - return false; - if (previous.length !== next.length) - return false; - for (let i = 0;i < previous.length; i += 1) - if (!jsonishEqualAtDepth(previous[i], next[i], depth + 1)) - return false; - return true; - } - const previousRecord = previous; - const nextRecord = next; - const previousKeys = Object.keys(previousRecord).filter((key) => typeof previousRecord[key] !== "function"); - const nextKeys = Object.keys(nextRecord).filter((key) => typeof nextRecord[key] !== "function"); - if (previousKeys.length !== nextKeys.length) - return false; - for (const key of previousKeys) { - if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) - return false; - if (!jsonishEqualAtDepth(previousRecord[key], nextRecord[key], depth + 1)) - return false; - } - return true; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/index.js +function createAgent(params) { + return new ReactAgent(params); } -var init_message_reconciliation = () => {}; +var init_agents2 = __esm(() => { + init_errors8(); + init_responses(); + init_stream6(); + init_ReactAgent(); + init_types10(); + init_middleware(); + init_utils11(); +}); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/root-message-projection.js -function syncMessagesIntoValues(values, messagesKey, messages) { - const record2 = values; - const current = record2[messagesKey]; - if (Array.isArray(current) && messagesEqualList2(current, messages)) - return values; - return { - ...record2, - [messagesKey]: messages - }; -} -function messagesEqualList2(previous, next) { - if (previous === next) - return true; - if (previous.length !== next.length) - return false; - for (let i = 0;i < previous.length; i += 1) - if (!messagesEqual(previous[i], next[i])) - return false; - return true; -} -function stateValuesShallowEqual(previous, next, messagesKey) { - if (previous === next) - return true; - const previousRecord = previous; - const nextRecord = next; - const previousKeys = Object.keys(previousRecord); - const nextKeys = Object.keys(nextRecord); - if (previousKeys.length !== nextKeys.length) - return false; - for (const key of previousKeys) { - if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) - return false; - const previousValue = previousRecord[key]; - const nextValue = nextRecord[key]; - if (key === messagesKey && Array.isArray(previousValue) && Array.isArray(nextValue)) - continue; - if (!Object.is(previousValue, nextValue)) - return false; - } - return true; -} -var RootMessageProjection = class { - #messagesKey; - #store; - #subagents; - #assembler = new MessageAssembler; - #roles = /* @__PURE__ */ new Map; - #indexById = /* @__PURE__ */ new Map; - #valuesMessageIds = /* @__PURE__ */ new Set; - #toolCallIdByNamespace = /* @__PURE__ */ new Map; - constructor(params) { - this.#messagesKey = params.messagesKey; - this.#store = params.store; - this.#subagents = params.subagents; - } - reset() { - this.#assembler = new MessageAssembler; - this.#roles.clear(); - this.#indexById.clear(); - this.#valuesMessageIds = /* @__PURE__ */ new Set; - this.#toolCallIdByNamespace.clear(); - } - recordToolCallNamespace(namespace, toolCallId) { - this.#toolCallIdByNamespace.set(namespaceKey2(namespace), toolCallId); - } - handleMessage(event) { - const data = event.params.data; - if (data.event === "message-start") { - const startData = data; - const role = startData.role ?? "ai"; - const extendedRole = startData.role ?? role; - let toolCallId = startData.tool_call_id; - if (extendedRole === "tool" && toolCallId == null) { - const messageId = startData.id; - if (messageId != null) { - const match2 = /-tool-(.+)$/.exec(messageId); - if (match2 != null) - toolCallId = match2[1]; - } - if (toolCallId == null) - toolCallId = this.#toolCallIdByNamespace.get(namespaceKey2(event.params.namespace)); - } - if (startData.id != null) - this.#roles.set(startData.id, { - role: extendedRole, - toolCallId - }); - } - const update = this.#assembler.consume(event); - if (update == null) - return; - const id = update.message.id; - if (id == null) - return; - const captured = this.#roles.get(id) ?? { role: "ai" }; - const base = assembledMessageToBaseMessage(update.message, captured.role, { toolCallId: captured.toolCallId }); - this.#subagents.discoverFromMessage(base, event.params.namespace); - this.#store.setState((s) => { - const existingIdx = this.#indexById.get(id); - let messages; - if (existingIdx == null) { - this.#indexById.set(id, s.messages.length); - messages = [...s.messages, base]; - } else if (messagesEqual(s.messages[existingIdx], base)) - return s; - else { - messages = s.messages.slice(); - messages[existingIdx] = base; - } - const values = syncMessagesIntoValues(s.values, this.#messagesKey, messages); - return values === s.values ? { - ...s, - messages - } : { - ...s, - messages, - values +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/hitl.js +function humanInTheLoopMiddleware(options) { + const createActionAndConfig = async (toolCall, config3, state, runtime) => { + const toolName = toolCall.name; + const toolArgs = toolCall.args; + const descriptionValue = config3.description; + let description; + if (typeof descriptionValue === "function") + description = await descriptionValue(toolCall, state, runtime); + else if (descriptionValue !== undefined) + description = descriptionValue; + else + description = `${options.descriptionPrefix ?? "Tool execution requires approval"} + +Tool: ${toolName} +Args: ${JSON.stringify(toolArgs, null, 2)}`; + const actionRequest = { + name: toolName, + args: toolArgs, + description + }; + const reviewConfig = { + actionName: toolName, + allowedDecisions: config3.allowedDecisions + }; + if (config3.argsSchema) + reviewConfig.argsSchema = config3.argsSchema; + return { + actionRequest, + reviewConfig + }; + }; + const processDecision = (decision, toolCall, config3) => { + const allowedDecisions = config3.allowedDecisions; + if (decision.type === "approve" && allowedDecisions.includes("approve")) + return { + revisedToolCall: toolCall, + toolMessage: null }; - }); - } - applyValues(nextValues, nextMessages) { - this.#store.setState((s) => { - if (nextMessages.length === 0) - return stateValuesShallowEqual(s.values, nextValues, this.#messagesKey) ? s : { - ...s, - values: nextValues - }; - const reconciliation = reconcileMessagesFromValues({ - valueMessages: nextMessages, - currentMessages: s.messages, - currentIndexById: this.#indexById, - previousValueMessageIds: this.#valuesMessageIds, - preferValuesMessage: shouldPreferValuesMessageForToolCalls - }); - this.#valuesMessageIds = reconciliation.valueMessageIds; - const messages = reconciliation.messages; - const values = { - ...nextValues, - [this.#messagesKey]: messages - }; - if (messages === s.messages && stateValuesShallowEqual(s.values, values, this.#messagesKey)) - return s; - this.#indexById.clear(); - for (const [id, idx] of buildMessageIndex(messages)) - this.#indexById.set(id, idx); + if (decision.type === "edit" && allowedDecisions.includes("edit")) { + const editedAction = decision.editedAction; + if (!editedAction || typeof editedAction.name !== "string") + throw new Error(`Invalid edited action for tool "${toolCall.name}": name must be a string`); + if (!editedAction.args || typeof editedAction.args !== "object") + throw new Error(`Invalid edited action for tool "${toolCall.name}": args must be an object`); return { - ...s, - values, - messages + revisedToolCall: { + type: "tool_call", + name: editedAction.name, + args: editedAction.args, + id: toolCall.id + }, + toolMessage: null }; - }); - } -}; -var init_root_message_projection = __esm(() => { - init_messages5(); - init_namespace2(); - init_assembled_to_message(); - init_message_reconciliation(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/submit-coordinator.js -function bindThreadConfig(config2, threadId) { - const base = config2 != null && typeof config2 === "object" ? config2 : {}; - const configurable = base.configurable != null && typeof base.configurable === "object" ? base.configurable : {}; - return { - ...base, - configurable: { - ...configurable, - thread_id: threadId - } - }; -} -var EMPTY_QUEUE, SubmitCoordinator = class { - #options; - #rootStore; - #queueStore; - #getDisposed; - #getCurrentThreadId; - #setCurrentThreadId; - #rememberSelfCreatedThreadId; - #hydrate; - #ensureThread; - #waitForRootPumpReady; - #awaitNextTerminal; - #latestUnresolvedInterrupt; - #markInterruptResolved; - #runAbort; - constructor(params) { - this.#options = params.options; - this.#rootStore = params.rootStore; - this.#queueStore = params.queueStore; - this.#getDisposed = params.getDisposed; - this.#getCurrentThreadId = params.getCurrentThreadId; - this.#setCurrentThreadId = params.setCurrentThreadId; - this.#rememberSelfCreatedThreadId = params.rememberSelfCreatedThreadId; - this.#hydrate = params.hydrate; - this.#ensureThread = params.ensureThread; - this.#waitForRootPumpReady = params.waitForRootPumpReady; - this.#awaitNextTerminal = params.awaitNextTerminal; - this.#latestUnresolvedInterrupt = params.latestUnresolvedInterrupt; - this.#markInterruptResolved = params.markInterruptResolved; - } - async submit(input, options) { - if (this.#getDisposed()) - return; - const overrideThreadId = options?.threadId; - if (overrideThreadId !== undefined && overrideThreadId !== this.#getCurrentThreadId()) - await this.#hydrate(overrideThreadId); - if (this.#getCurrentThreadId() == null) { - const threadId = v7_default2(); - this.#setCurrentThreadId(threadId); - this.#rememberSelfCreatedThreadId(threadId); - this.#options.onThreadId?.(threadId); - this.#rootStore.setState((s) => ({ - ...s, - threadId - })); } - const currentThreadId = this.#getCurrentThreadId(); - if (currentThreadId == null) - return; - const thread = this.#ensureThread(currentThreadId); - const activeThreadId = currentThreadId; - await this.#waitForRootPumpReady(); - const strategy = options?.multitaskStrategy ?? "rollback"; - const hasActiveRun = this.#runAbort != null && !this.#runAbort.signal.aborted; - if (hasActiveRun && strategy === "reject") - throw new Error("submit() rejected: a run is already in flight and multitaskStrategy is 'reject'."); - if (hasActiveRun && strategy === "enqueue") { - this.#enqueueSubmission(input, options); - return; + if (decision.type === "reject" && allowedDecisions.includes("reject")) { + if (decision.message !== undefined && typeof decision.message !== "string") + throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof decision.message}`); + return { + revisedToolCall: toolCall, + toolMessage: new ToolMessage({ + content: decision.message ?? `User rejected the tool call for \`${toolCall.name}\` with id ${toolCall.id}`, + name: toolCall.name, + tool_call_id: toolCall.id, + status: "error" + }) + }; } - this.#runAbort?.abort(); - const abort = new AbortController; - this.#runAbort = abort; - const resumeCommand = options?.command?.resume; - const isResume = resumeCommand !== undefined; - this.#rootStore.setState((s) => ({ - ...s, - interrupts: [], - interrupt: undefined, - error: undefined, - isLoading: true - })); - const boundConfig = bindThreadConfig(options?.config, currentThreadId); - const terminalPromise = this.#awaitNextTerminal(abort.signal); - let terminalSettled = false; - const reportError = (error51) => { - if (abort.signal.aborted) - return; - this.#rootStore.setState((s) => ({ - ...s, - error: error51 - })); - try { - options?.onError?.(error51); - } catch {} - }; - try { - let terminal; - if (isResume) { - const target = this.#latestUnresolvedInterrupt(); - if (target == null) - throw new Error("submit({ command: { resume } }) called but no pending protocol interrupt is available."); - const commandPromise = thread.respondInput({ - namespace: target.namespace, - interrupt_id: target.interruptId, - response: resumeCommand - }); - this.#markInterruptResolved(target.interruptId); - const first = await Promise.race([terminalPromise.then((value) => ({ - type: "terminal", - value - })), commandPromise.then(() => ({ type: "command" }), (error51) => ({ - type: "error", - error: error51 - }))]); - if (first.type === "error") - throw first.error; - if (first.type === "terminal") { - terminal = first.value; - terminalSettled = true; - commandPromise.catch((error51) => { - if (!terminalSettled) - reportError(error51); - }); + const msg = `Unexpected human decision: ${JSON.stringify(decision)}. Decision type '${decision.type}' is not allowed for tool '${toolCall.name}'. Expected one of ${JSON.stringify(allowedDecisions)} based on the tool's configuration.`; + throw new Error(msg); + }; + return createMiddleware({ + name: "HumanInTheLoopMiddleware", + contextSchema, + afterModel: { + canJumpTo: ["model"], + hook: async (state, runtime) => { + const config3 = interopParse(contextSchema, { + ...options, + ...runtime.context || {} + }); + if (!config3) + return; + const { messages } = state; + if (!messages.length) + return; + const lastMessage = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); + if (!lastMessage || !lastMessage.tool_calls?.length) + return; + if (!config3.interruptOn) + return; + const resolvedConfigs = {}; + for (const [toolName, toolConfig] of Object.entries(config3.interruptOn)) + if (typeof toolConfig === "boolean") { + if (toolConfig === true) + resolvedConfigs[toolName] = { allowedDecisions: [...ALLOWED_DECISIONS] }; + } else if (toolConfig.allowedDecisions) + resolvedConfigs[toolName] = toolConfig; + const interruptToolCalls = []; + const autoApprovedToolCalls = []; + for (const toolCall of lastMessage.tool_calls) + if (toolCall.name in resolvedConfigs) + interruptToolCalls.push(toolCall); + else + autoApprovedToolCalls.push(toolCall); + if (!interruptToolCalls.length) + return; + const actionRequests = []; + const reviewConfigs = []; + for (const toolCall of interruptToolCalls) { + const interruptConfig = resolvedConfigs[toolCall.name]; + const { actionRequest, reviewConfig } = await createActionAndConfig(toolCall, interruptConfig, state, runtime); + actionRequests.push(actionRequest); + reviewConfigs.push(reviewConfig); } - } else { - const commandPromise = thread.submitRun({ - input: input ?? null, - config: boundConfig, - metadata: options?.metadata ?? undefined, - forkFrom: options?.forkFrom, - multitaskStrategy: options?.multitaskStrategy === "enqueue" ? "enqueue" : options?.multitaskStrategy - }); - const notifyCreated = (result) => { - this.#options.onCreated?.({ - run_id: result.run_id, - thread_id: activeThreadId - }); - }; - const first = await Promise.race([terminalPromise.then((value) => ({ - type: "terminal", - value - })), commandPromise.then((result) => ({ - type: "command", - result - }), (error51) => ({ - type: "error", - error: error51 - }))]); - if (first.type === "error") - throw first.error; - if (first.type === "command") - notifyCreated(first.result); - else { - terminal = first.value; - terminalSettled = true; - commandPromise.then(notifyCreated).catch((error51) => { - if (!terminalSettled) - reportError(error51); - }); + const decisions = (await interrupt({ + actionRequests, + reviewConfigs + })).decisions; + if (!decisions || !Array.isArray(decisions)) + throw new Error("Invalid HITLResponse: decisions must be a non-empty array"); + if (decisions.length !== interruptToolCalls.length) + throw new Error(`Number of human decisions (${decisions.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`); + const revisedToolCalls = [...autoApprovedToolCalls]; + const artificialToolMessages = []; + const hasRejectedToolCalls = decisions.some((decision) => decision.type === "reject"); + for (let i = 0;i < decisions.length; i++) { + const decision = decisions[i]; + const toolCall = interruptToolCalls[i]; + const interruptConfig = resolvedConfigs[toolCall.name]; + const { revisedToolCall, toolMessage } = processDecision(decision, toolCall, interruptConfig); + if (revisedToolCall && (!hasRejectedToolCalls || decision.type === "reject")) + revisedToolCalls.push(revisedToolCall); + if (toolMessage) + artificialToolMessages.push(toolMessage); } + if (AIMessage.isInstance(lastMessage)) + lastMessage.tool_calls = revisedToolCalls; + const jumpTo = hasRejectedToolCalls ? "model" : undefined; + return { + messages: [lastMessage, ...artificialToolMessages], + jumpTo + }; } - terminal ??= await terminalPromise; - terminalSettled = true; - if (terminal.event === "failed" && !abort.signal.aborted) { - const runError = new Error(terminal.error ?? "Run failed with no error message"); - this.#rootStore.setState((s) => ({ - ...s, - error: runError - })); - try { - options?.onError?.(runError); - } catch {} - } - } catch (error51) { - reportError(error51); - } finally { - this.#rootStore.setState((s) => ({ - ...s, - isLoading: false - })); - if (this.#runAbort === abort) - this.#runAbort = undefined; - setTimeout(() => this.#drainQueue(), 0); } - } - async stop() { - this.abortActiveRun(); - this.#rootStore.setState((s) => ({ - ...s, - isLoading: false - })); - } - abortActiveRun() { - this.#runAbort?.abort(); - this.#runAbort = undefined; - } - async cancelQueued(id) { - const current = this.#queueStore.getSnapshot(); - const next = current.filter((entry) => entry.id !== id); - if (next.length === current.length) - return false; - this.#queueStore.setState(() => next); - return true; - } - async clearQueue() { - this.#queueStore.setState(() => EMPTY_QUEUE); - } - #enqueueSubmission(input, options) { - const entry = { - id: v7_default2(), - values: input ?? undefined, - options, - createdAt: /* @__PURE__ */ new Date - }; - this.#queueStore.setState((current) => [...current, entry]); - } - #drainQueue() { - if (this.#getDisposed()) - return; - if (this.#runAbort != null && !this.#runAbort.signal.aborted) - return; - const current = this.#queueStore.getSnapshot(); - if (current.length === 0) - return; - const [next, ...rest] = current; - this.#queueStore.setState(() => rest); - const nextOptions = { - ...next.options ?? {}, - multitaskStrategy: undefined - }; - this.submit(next.values, nextOptions).catch(() => {}); - } -}; -var init_submit_coordinator = __esm(() => { - init_dist_node(); - EMPTY_QUEUE = Object.freeze([]); + }); +} +var DescriptionFunctionSchema, ALLOWED_DECISIONS, DecisionType, InterruptOnConfigSchema, contextSchema; +var init_hitl = __esm(() => { + init_middleware(); + init_messages(); + init_dist4(); + init_types3(); + init_v3(); + DescriptionFunctionSchema = exports_external2.function().args(exports_external2.custom(), exports_external2.custom(), exports_external2.custom()).returns(exports_external2.union([exports_external2.string(), exports_external2.promise(exports_external2.string())])); + ALLOWED_DECISIONS = [ + "approve", + "edit", + "reject" + ]; + DecisionType = exports_external2.enum(ALLOWED_DECISIONS); + InterruptOnConfigSchema = exports_external2.object({ + allowedDecisions: exports_external2.array(DecisionType), + description: exports_external2.union([exports_external2.string(), DescriptionFunctionSchema]).optional(), + argsSchema: exports_external2.record(exports_external2.any()).optional() + }); + contextSchema = exports_external2.object({ + interruptOn: exports_external2.record(exports_external2.union([exports_external2.boolean(), InterruptOnConfigSchema])).optional(), + descriptionPrefix: exports_external2.string().default("Tool execution requires approval") + }); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/tool-calls.js -function upsertToolCall(current, next) { - const idx = current.findIndex((toolCall) => toolCall.callId === next.callId); - if (idx < 0) - return [...current, next]; - const updated = current.slice(); - updated[idx] = next; - return updated; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/summarization.js +function getProfileLimits(input) { + if ("profile" in input && typeof input.profile === "object" && input.profile && "maxInputTokens" in input.profile && (typeof input.profile.maxInputTokens === "number" || input.profile.maxInputTokens == null)) + return input.profile.maxInputTokens ?? undefined; + if ("model" in input && typeof input.model === "string") + return getModelContextSize(input.model); + if ("modelName" in input && typeof input.modelName === "string") + return getModelContextSize(input.modelName); } -var init_tool_calls = () => {}; +var DEFAULT_SUMMARY_PROMPT = ` +Context Extraction Assistant + -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/controller.js -function isAbortLikeError(error51) { - if (error51 == null || typeof error51 !== "object") - return false; - const maybeError = error51; - return maybeError.name === "AbortError" || typeof maybeError.message === "string" && maybeError.message.includes("aborted"); -} -function extractAndCoerceMessages(values, messagesKey) { - const raw2 = values[messagesKey]; - if (!Array.isArray(raw2)) - return []; - return ensureMessageInstances(raw2); -} -var ROOT_NAMESPACE, ROOT_PUMP_CHANNELS, StreamController = class { - rootStore; - subagentStore; - subgraphStore; - subgraphByNodeStore; - messageMetadataStore; - queueStore; - registry; - #options; - #messagesKey; - #subagents = new SubagentDiscovery; - #subgraphs = new SubgraphDiscovery; - #messageMetadata = new MessageMetadataTracker; - #thread; - #currentThreadId; - #rootSubscription; - #rootPump; - #rootPumpReady; - #threadEventUnsubscribe; - #disposed = false; - #pendingDisposeTimer = null; - #resolvedInterrupts = /* @__PURE__ */ new Set; - #selfCreatedThreadIds = /* @__PURE__ */ new Set; - #rootEventListeners = /* @__PURE__ */ new Set; - #rootBus; - #hydrationPromise; - #resolveHydration; - #rejectHydration; - #rootToolAssembler = new ToolCallAssembler; - #rootMessages; - #lifecycleLoading; - #submitter; - #threadListeners = /* @__PURE__ */ new Set; - constructor(options) { - this.#options = options; - this.#messagesKey = options.messagesKey ?? "messages"; - this.#currentThreadId = options.threadId ?? null; - this.#rootBus = { - channels: ROOT_PUMP_CHANNELS, - subscribe: (listener) => { - this.#rootEventListeners.add(listener); - return () => { - this.#rootEventListeners.delete(listener); - }; - } - }; - this.registry = new ChannelRegistry(this.#rootBus); - this.subagentStore = this.#subagents.store; - this.subgraphStore = this.#subgraphs.store; - this.subgraphByNodeStore = this.#subgraphs.byNodeStore; - this.rootStore = new StreamStore(this.#createInitialSnapshot()); - this.#rootMessages = new RootMessageProjection({ - messagesKey: this.#messagesKey, - store: this.rootStore, - subagents: this.#subagents - }); - this.#lifecycleLoading = new LifecycleLoadingTracker({ - store: this.rootStore, - isDisposed: () => this.#disposed - }); - this.messageMetadataStore = this.#messageMetadata.store; - this.queueStore = new StreamStore(EMPTY_QUEUE); - this.#submitter = new SubmitCoordinator({ - options: this.#options, - rootStore: this.rootStore, - queueStore: this.queueStore, - getDisposed: () => this.#disposed, - getCurrentThreadId: () => this.#currentThreadId, - setCurrentThreadId: (threadId) => { - this.#currentThreadId = threadId; - }, - rememberSelfCreatedThreadId: (threadId) => { - this.#selfCreatedThreadIds.add(threadId); - }, - hydrate: (threadId) => this.hydrate(threadId), - ensureThread: (threadId) => this.#ensureThread(threadId), - waitForRootPumpReady: () => this.#rootPumpReady, - awaitNextTerminal: (signal) => this.#awaitNextTerminal(signal), - latestUnresolvedInterrupt: () => this.#latestUnresolvedInterrupt(), - markInterruptResolved: (interruptId) => { - this.#resolvedInterrupts.add(interruptId); - } - }); - this.#hydrationPromise = this.#createHydrationPromise(); - this.#hydrationPromise.catch(() => { - return; - }); - if (this.#currentThreadId != null) - this.hydrate(this.#currentThreadId); - else - this.#resolveHydration(); - } - get hydrationPromise() { - return this.#hydrationPromise; - } - #createHydrationPromise() { - return new Promise((resolve2, reject) => { - this.#resolveHydration = resolve2; - this.#rejectHydration = reject; - }); - } - #resetHydrationPromise() { - this.#hydrationPromise.catch(() => { - return; - }); - this.#hydrationPromise = this.#createHydrationPromise(); + +Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below. + + + +You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history. +This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal. + + + +The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history. +You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal. + + +The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved: + +With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history. +Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context. + + +Messages to summarize: +{messages} +`, tokenCounterSchema, contextSizeSchema, keepSchema, contextSchema2; +var init_summarization = __esm(() => { + init_universal(); + init_utils12(); + init_utils10(); + init_middleware(); + init_messages(); + init_runnables(); + init_dist4(); + init_types3(); + init_v3(); + init_uuid(); + init_base5(); + tokenCounterSchema = exports_external2.function().args(exports_external2.array(exports_external2.custom())).returns(exports_external2.union([exports_external2.number(), exports_external2.promise(exports_external2.number())])); + contextSizeSchema = exports_external2.object({ + fraction: exports_external2.number().gt(0, "Fraction must be greater than 0").max(1, "Fraction must be less than or equal to 1").optional(), + tokens: exports_external2.number().positive("Tokens must be greater than 0").optional(), + messages: exports_external2.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional() + }).refine((data) => { + return [ + data.fraction, + data.tokens, + data.messages + ].filter((v) => v !== undefined).length >= 1; + }, { message: "At least one of fraction, tokens, or messages must be provided" }); + keepSchema = exports_external2.object({ + fraction: exports_external2.number().min(0, "Messages must be non-negative").max(1, "Fraction must be less than or equal to 1").optional(), + tokens: exports_external2.number().min(0, "Tokens must be greater than or equal to 0").optional(), + messages: exports_external2.number().int("Messages must be an integer").min(0, "Messages must be non-negative").optional() + }).refine((data) => { + return [ + data.fraction, + data.tokens, + data.messages + ].filter((v) => v !== undefined).length === 1; + }, { message: "Exactly one of fraction, tokens, or messages must be provided" }); + contextSchema2 = exports_external2.object({ + model: exports_external2.custom(), + trigger: exports_external2.union([contextSizeSchema, exports_external2.array(contextSizeSchema)]).optional(), + keep: keepSchema.optional(), + tokenCounter: tokenCounterSchema.optional(), + summaryPrompt: exports_external2.string().default(DEFAULT_SUMMARY_PROMPT), + trimTokensToSummarize: exports_external2.number().optional(), + summaryPrefix: exports_external2.string().optional(), + maxTokensBeforeSummary: exports_external2.number().optional(), + messagesToKeep: exports_external2.number().optional() + }); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/dynamicSystemPrompt.js +var init_dynamicSystemPrompt = __esm(() => { + init_middleware(); + init_messages(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/llmToolSelector.js +var LLMToolSelectorOptionsSchema; +var init_llmToolSelector = __esm(() => { + init_universal(); + init_middleware(); + init_messages(); + init_runnables(); + init_v3(); + init_base5(); + LLMToolSelectorOptionsSchema = exports_external2.object({ + model: exports_external2.string().or(exports_external2.instanceof(BaseLanguageModel)).optional(), + systemPrompt: exports_external2.string().optional(), + maxTools: exports_external2.number().optional(), + alwaysInclude: exports_external2.array(exports_external2.string()).optional() + }); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/pii.js +var contextSchema3; +var init_pii = __esm(() => { + init_middleware(); + init_messages(); + init_v3(); + init_hash2(); + contextSchema3 = exports_external2.object({ + applyToInput: exports_external2.boolean().optional(), + applyToOutput: exports_external2.boolean().optional(), + applyToToolResults: exports_external2.boolean().optional() + }); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/piiRedaction.js +var contextSchema4; +var init_piiRedaction = __esm(() => { + init_middleware(); + init_messages(); + init_v3(); + contextSchema4 = exports_external2.object({ rules: exports_external2.record(exports_external2.string(), exports_external2.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional() }); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/contextEditing.js +var DEFAULT_TOOL_PLACEHOLDER = "[cleared]", DEFAULT_TRIGGER_TOKENS = 1e5, DEFAULT_KEEP = 3, ClearToolUsesEdit = class { + #triggerConditions; + trigger; + keep; + clearToolInputs; + excludeTools; + placeholder; + model; + clearAtLeast; + constructor(config3 = {}) { + let trigger = config3.trigger; + if (config3.triggerTokens !== undefined) { + console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."); + if (trigger === undefined) + trigger = { tokens: config3.triggerTokens }; + } + let keep = config3.keep; + if (config3.keepMessages !== undefined) { + console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."); + if (keep === undefined) + keep = { messages: config3.keepMessages }; + } + if (trigger === undefined) + trigger = { tokens: DEFAULT_TRIGGER_TOKENS }; + if (keep === undefined) + keep = { messages: DEFAULT_KEEP }; + if (Array.isArray(trigger)) { + this.#triggerConditions = trigger.map((t) => contextSizeSchema.parse(t)); + this.trigger = this.#triggerConditions; + } else { + const validated = contextSizeSchema.parse(trigger); + this.#triggerConditions = [validated]; + this.trigger = validated; + } + const validatedKeep = keepSchema.parse(keep); + this.keep = validatedKeep; + if (config3.clearAtLeast !== undefined) + console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."); + this.clearAtLeast = config3.clearAtLeast ?? 0; + this.clearToolInputs = config3.clearToolInputs ?? false; + this.excludeTools = new Set(config3.excludeTools ?? []); + this.placeholder = config3.placeholder ?? DEFAULT_TOOL_PLACEHOLDER; } - async hydrate(threadId) { - if (this.#disposed) - return; - const target = threadId === undefined ? this.#currentThreadId : threadId; - const changed = target !== this.#currentThreadId; - this.#currentThreadId = target ?? null; - this.rootStore.setState((s) => ({ - ...s, - threadId: this.#currentThreadId - })); - if (changed) { - this.#resetHydrationPromise(); - await this.#teardownThread(); - this.rootStore.setState(() => ({ - ...this.#createInitialSnapshot(), - threadId: this.#currentThreadId - })); - this.queueStore.setState(() => EMPTY_QUEUE); + async apply(params) { + const { messages, model, countTokens } = params; + const tokens = await countTokens(messages); + const orphanedIndices = []; + for (let i = 0;i < messages.length; i++) { + const msg = messages[i]; + if (ToolMessage.isInstance(msg)) { + const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, i), msg.tool_call_id); + if (!aiMessage) + orphanedIndices.push(i); + else if (!aiMessage.tool_calls?.find((call3) => call3.id === msg.tool_call_id)) + orphanedIndices.push(i); + } } - if (this.#currentThreadId == null) { - this.rootStore.setState((s) => ({ - ...s, - isThreadLoading: false - })); - this.#resolveHydration(); + for (let i = orphanedIndices.length - 1;i >= 0; i--) + messages.splice(orphanedIndices[i], 1); + let currentTokens = tokens; + if (orphanedIndices.length > 0) + currentTokens = await countTokens(messages); + if (!this.#shouldEdit(messages, currentTokens, model)) return; + const candidates = []; + for (let i = 0;i < messages.length; i++) { + const msg = messages[i]; + if (ToolMessage.isInstance(msg)) + candidates.push({ + idx: i, + msg + }); } - if (this.#selfCreatedThreadIds.has(this.#currentThreadId)) { - this.rootStore.setState((s) => ({ - ...s, - isThreadLoading: false - })); - this.#resolveHydration(); + if (candidates.length === 0) return; - } - this.rootStore.setState((s) => ({ - ...s, - isThreadLoading: true - })); - let hydrationError; - try { - const state = await this.#options.client.threads.getState(this.#currentThreadId); - if (state?.values != null) { - const checkpointId = state.checkpoint?.checkpoint_id; - const parentCheckpointId = state.parent_checkpoint?.checkpoint_id ?? undefined; - const syntheticCheckpoint = typeof checkpointId === "string" ? { - id: checkpointId, - ...parentCheckpointId != null ? { parent_id: parentCheckpointId } : {} - } : undefined; - this.#applyValues(state.values, syntheticCheckpoint); + const keepCount = await this.#determineKeepCount(candidates, countTokens, model); + const candidatesToClear = keepCount >= candidates.length ? [] : keepCount > 0 ? candidates.slice(0, -keepCount) : candidates; + let clearedTokens = 0; + const initialCandidatesToClear = [...candidatesToClear]; + for (const { idx, msg: toolMessage } of initialCandidatesToClear) { + if (toolMessage.response_metadata?.context_editing?.cleared) + continue; + const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, idx), toolMessage.tool_call_id); + if (!aiMessage) + continue; + const toolCall = aiMessage.tool_calls?.find((call3) => call3.id === toolMessage.tool_call_id); + if (!toolCall) + continue; + const toolName = toolMessage.name || toolCall.name; + if (this.excludeTools.has(toolName)) + continue; + messages[idx] = new ToolMessage({ + tool_call_id: toolMessage.tool_call_id, + content: this.placeholder, + name: toolMessage.name, + artifact: undefined, + response_metadata: { + ...toolMessage.response_metadata, + context_editing: { + cleared: true, + strategy: "clear_tool_uses" + } + } + }); + if (this.clearToolInputs) { + const aiMsgIdx = messages.indexOf(aiMessage); + if (aiMsgIdx >= 0) + messages[aiMsgIdx] = this.#buildClearedToolInputMessage(aiMessage, toolMessage.tool_call_id); } - } catch (error51) { - if (error51?.status !== 404) { - hydrationError = error51; - this.rootStore.setState((s) => ({ - ...s, - error: error51 - })); + const newTokenCount = await countTokens(messages); + clearedTokens = Math.max(0, currentTokens - newTokenCount); + } + if (this.clearAtLeast > 0 && clearedTokens < this.clearAtLeast) { + const remainingCandidates = keepCount > 0 && keepCount < candidates.length ? candidates.slice(-keepCount) : []; + for (let i = remainingCandidates.length - 1;i >= 0; i--) { + if (clearedTokens >= this.clearAtLeast) + break; + const { idx, msg: toolMessage } = remainingCandidates[i]; + if (toolMessage.response_metadata?.context_editing?.cleared) + continue; + const aiMessage = this.#findAIMessageForToolCall(messages.slice(0, idx), toolMessage.tool_call_id); + if (!aiMessage) + continue; + const toolCall = aiMessage.tool_calls?.find((call3) => call3.id === toolMessage.tool_call_id); + if (!toolCall) + continue; + const toolName = toolMessage.name || toolCall.name; + if (this.excludeTools.has(toolName)) + continue; + messages[idx] = new ToolMessage({ + tool_call_id: toolMessage.tool_call_id, + content: this.placeholder, + name: toolMessage.name, + artifact: undefined, + response_metadata: { + ...toolMessage.response_metadata, + context_editing: { + cleared: true, + strategy: "clear_tool_uses" + } + } + }); + if (this.clearToolInputs) { + const aiMsgIdx = messages.indexOf(aiMessage); + if (aiMsgIdx >= 0) + messages[aiMsgIdx] = this.#buildClearedToolInputMessage(aiMessage, toolMessage.tool_call_id); + } + const newTokenCount = await countTokens(messages); + clearedTokens = Math.max(0, currentTokens - newTokenCount); } - } finally { - this.rootStore.setState((s) => ({ - ...s, - isThreadLoading: false - })); - if (hydrationError != null) - this.#rejectHydration(hydrationError); - else - this.#resolveHydration(); } - this.#ensureThread(this.#currentThreadId); - } - async submit(input, options) { - await this.#submitter.submit(input, options); - } - async stop() { - await this.#submitter.stop(); - } - async cancelQueued(id) { - return this.#submitter.cancelQueued(id); } - async clearQueue() { - await this.#submitter.clearQueue(); - } - async respond(response, target) { - if (this.#disposed || this.#thread == null) - throw new Error("No active thread to respond to."); - const resolved = target != null ? { - interruptId: target.interruptId, - namespace: target.namespace ?? [...ROOT_NAMESPACE] - } : this.#latestUnresolvedInterrupt(); - if (resolved == null) - throw new Error("No pending interrupt to respond to."); - try { - await this.#thread.respondInput({ - namespace: resolved.namespace, - interrupt_id: resolved.interruptId, - response - }); - this.#resolvedInterrupts.add(resolved.interruptId); - } catch (error51) { - if (this.#disposed && isAbortLikeError(error51)) - return; - throw error51; + #shouldEdit(messages, totalTokens, model) { + for (const trigger of this.#triggerConditions) { + let conditionMet = true; + let hasAnyProperty = false; + if (trigger.messages !== undefined) { + hasAnyProperty = true; + if (messages.length < trigger.messages) + conditionMet = false; + } + if (trigger.tokens !== undefined) { + hasAnyProperty = true; + if (totalTokens < trigger.tokens) + conditionMet = false; + } + if (trigger.fraction !== undefined) { + hasAnyProperty = true; + if (!model) + continue; + const maxInputTokens = getProfileLimits(model); + if (typeof maxInputTokens === "number") { + const threshold = Math.floor(maxInputTokens * trigger.fraction); + if (threshold <= 0) + continue; + if (totalTokens < threshold) + conditionMet = false; + } else + continue; + } + if (hasAnyProperty && conditionMet) + return true; } + return false; } - async dispose() { - if (this.#disposed) - return; - this.#cancelPendingDispose(); - this.#disposed = true; - this.#submitter.abortActiveRun(); - await this.#teardownThread(); - await this.registry.dispose(); - this.#threadListeners.clear(); - } - activate() { - this.#cancelPendingDispose(); - return () => { - if (this.#disposed) - return; - this.#pendingDisposeTimer = setTimeout(() => { - this.#pendingDisposeTimer = null; - this.dispose().catch(() => { - return; - }); - }, 0); - }; - } - #cancelPendingDispose() { - if (this.#pendingDisposeTimer != null) { - clearTimeout(this.#pendingDisposeTimer); - this.#pendingDisposeTimer = null; + async#determineKeepCount(candidates, countTokens, model) { + if ("messages" in this.keep && this.keep.messages !== undefined) + return this.keep.messages; + if ("tokens" in this.keep && this.keep.tokens !== undefined) { + const targetTokens = this.keep.tokens; + let tokenCount = 0; + let keepCount = 0; + for (let i = candidates.length - 1;i >= 0; i--) { + const candidate = candidates[i]; + const msgTokens = await countTokens([candidate.msg]); + if (tokenCount + msgTokens <= targetTokens) { + tokenCount += msgTokens; + keepCount++; + } else + break; + } + return keepCount; } + if ("fraction" in this.keep && this.keep.fraction !== undefined) { + if (!model) + return DEFAULT_KEEP; + const maxInputTokens = getProfileLimits(model); + if (typeof maxInputTokens === "number") { + const targetTokens = Math.floor(maxInputTokens * this.keep.fraction); + if (targetTokens <= 0) + return DEFAULT_KEEP; + let tokenCount = 0; + let keepCount = 0; + for (let i = candidates.length - 1;i >= 0; i--) { + const candidate = candidates[i]; + const msgTokens = await countTokens([candidate.msg]); + if (tokenCount + msgTokens <= targetTokens) { + tokenCount += msgTokens; + keepCount++; + } else + break; + } + return keepCount; + } + } + return DEFAULT_KEEP; } - getThread() { - return this.#thread; - } - subscribeThread(listener) { - this.#threadListeners.add(listener); - listener(this.#thread); - return () => { - this.#threadListeners.delete(listener); - }; - } - #createInitialSnapshot() { - const values = this.#options.initialValues ?? {}; - return { - values, - messages: extractAndCoerceMessages(values, this.#messagesKey), - toolCalls: [], - interrupts: [], - interrupt: undefined, - isLoading: false, - isThreadLoading: this.#currentThreadId != null && !this.#selfCreatedThreadIds.has(this.#currentThreadId), - error: undefined, - threadId: this.#currentThreadId - }; + #findAIMessageForToolCall(previousMessages, toolCallId) { + for (let i = previousMessages.length - 1;i >= 0; i--) { + const msg = previousMessages[i]; + if (AIMessage.isInstance(msg)) { + if (msg.tool_calls?.some((call3) => call3.id === toolCallId)) + return msg; + } + } + return null; } - #ensureThread(threadId) { - if (this.#thread != null) - return this.#thread; - this.#thread = this.#options.client.threads.stream(threadId, { - assistantId: this.#options.assistantId, - transport: this.#options.transport, - fetch: this.#options.fetch, - webSocketFactory: this.#options.webSocketFactory + #buildClearedToolInputMessage(message, toolCallId) { + const updatedToolCalls = message.tool_calls?.map((toolCall) => { + if (toolCall.id === toolCallId) + return { + ...toolCall, + args: {} + }; + return toolCall; }); - this.registry.bind(this.#thread); - this.#startRootPump(this.#thread); - this.#notifyThreadListeners(); - return this.#thread; - } - async#teardownThread() { - const thread = this.#thread; - this.#thread = undefined; - this.registry.bind(undefined); - this.#threadEventUnsubscribe?.(); - this.#threadEventUnsubscribe = undefined; - this.#rootEventListeners.delete(this.#lifecycleLoading.listener); - try { - await this.#rootSubscription?.unsubscribe(); - } catch {} - this.#rootSubscription = undefined; - this.#rootPumpReady = undefined; - try { - await this.#rootPump; - } catch {} - this.#rootPump = undefined; - this.#rootMessages.reset(); - this.#rootToolAssembler = new ToolCallAssembler; - this.#lifecycleLoading.reset(); - this.#messageMetadata.reset(); - this.queueStore.setState(() => EMPTY_QUEUE); - if (thread != null) { - try { - await thread.close(); - } catch {} - this.#notifyThreadListeners(); - } - } - #usesEventStreamTransport() { - const transport = this.#options.transport; - if (transport === "websocket") - return false; - if (transport == null || transport === "sse") - return true; - return typeof transport.openEventStream === "function"; - } - #startRootPump(thread) { - if (this.#rootPump != null) - return; - let resolveReady; - this.#rootPumpReady = new Promise((resolve2) => { - resolveReady = resolve2; - }); - this.#threadEventUnsubscribe = thread.onEvent((event) => this.#onWildcardEvent(event)); - this.#rootEventListeners.add(this.#lifecycleLoading.listener); - this.#rootPump = (async () => { - try { - const subscriptionPromise = thread.subscribe({ - channels: [...ROOT_PUMP_CHANNELS], - namespaces: [[]], - depth: 1 - }); - if (this.#usesEventStreamTransport()) - queueMicrotask(() => { - resolveReady?.(); - resolveReady = undefined; - }); - const subscription = await subscriptionPromise; - resolveReady?.(); - resolveReady = undefined; - this.#rootSubscription = subscription; - while (!this.#disposed) { - for await (const event of subscription) { - if (this.#disposed) - break; - try { - this.#onRootEvent(event); - } catch {} - } - if (this.#disposed) - break; - if (!subscription.isPaused) - break; - await subscription.waitForResume(); - } - } catch { - resolveReady?.(); - resolveReady = undefined; - } - })(); - } - #onWildcardEvent(event) { - try { - this.#subagents.push(event); - } catch {} - this.#subgraphs.push(event); - this.#lifecycleLoading.handle(event); - this.#recordRootInterrupt(event); - } - #onRootEvent(event) { - try { - this.#subagents.push(event); - } catch {} - if (this.#rootEventListeners.size > 0) - for (const listener of this.#rootEventListeners) - try { - listener(event); - } catch {} - const isInternalNamespace = isInternalWorkNamespace(event.params.namespace); - const hasLegacySubagentNamespace = isLegacySubagentNamespace(event.params.namespace); - if (event.method === "messages") { - if (!isInternalNamespace) - this.#rootMessages.handleMessage(event); - return; - } - if (event.method === "tools") { - if (event.params.namespace.length <= 1 && !hasLegacySubagentNamespace) { - const toolData = event.params.data; - if (toolData.event === "tool-started" && typeof toolData.tool_call_id === "string") - this.#rootMessages.recordToolCallNamespace(event.params.namespace, toolData.tool_call_id); - const tc = this.#rootToolAssembler.consume(event); - if (tc != null) - this.rootStore.setState((s) => ({ - ...s, - toolCalls: upsertToolCall(s.toolCalls, tc) - })); - } - return; - } - if (event.method === "checkpoints") { - const data = event.params.data; - this.#messageMetadata.bufferCheckpoint(event.params.namespace, data); - return; - } - if (!isRootNamespace(event.params.namespace)) - return; - if (event.method === "values") { - const valuesEvent = event; - const bufferedCheckpoint = this.#messageMetadata.consumeCheckpoint(event.params.namespace); - this.#applyValues(valuesEvent.params.data, bufferedCheckpoint); - return; - } - if (event.method === "input.requested") { - this.#recordRootInterrupt(event); - return; - } - if (event.method === "lifecycle") - event.params.data; - } - #applyValues(raw2, checkpoint) { - if (raw2 == null || typeof raw2 !== "object" || Array.isArray(raw2)) - return; - const state = raw2; - const parentCheckpointId = checkpoint?.parent_id; - if (parentCheckpointId != null && Array.isArray(state[this.#messagesKey])) - this.#messageMetadata.recordMessages(state[this.#messagesKey], { parentCheckpointId }); - const maybeMessages = state[this.#messagesKey]; - let nextValues; - let nextMessages; - if (Array.isArray(maybeMessages)) { - const coerced = ensureMessageInstances(maybeMessages); - nextValues = { - ...state, - [this.#messagesKey]: coerced - }; - nextMessages = coerced; - } else { - nextValues = state; - nextMessages = []; - } - this.#rootMessages.applyValues(nextValues, nextMessages); - } - #recordRootInterrupt(event) { - if (event.method !== "input.requested") - return; - if (!isRootNamespace(event.params.namespace)) - return; - const data = event.params.data; - const interruptId = data?.interrupt_id; - if (typeof interruptId !== "string" || this.#resolvedInterrupts.has(interruptId)) - return; - const interrupt2 = { - id: interruptId, - value: data.payload - }; - this.rootStore.setState((s) => { - if (s.interrupts.some((entry) => entry.id === interruptId)) - return s; - const interrupts = [...s.interrupts, interrupt2]; - return { - ...s, - interrupts, - interrupt: interrupts[0] - }; - }); - } - #awaitNextTerminal(signal) { - return new Promise((resolve2) => { - let settled = false; - function finish(result) { - if (settled) - return; - settled = true; - unsubscribeRoot?.(); - unsubscribeThread?.(); - signal.removeEventListener("abort", finishAborted); - resolve2(result); - } - const finishAborted = () => finish({ event: "aborted" }); - const onEvent = (event) => { - if (settled) - return; - if (event.method !== "lifecycle") - return; - if (!isRootNamespace(event.params.namespace)) - return; - const lifecycle = event.params.data; - if (lifecycle?.event === "completed") - setTimeout(() => finish({ event: "completed" }), 0); - else if (lifecycle?.event === "failed") - setTimeout(() => finish({ - event: "failed", - error: lifecycle.error - }), 0); - else if (lifecycle?.event === "interrupted") - setTimeout(() => finish({ event: "interrupted" }), 0); - }; - const unsubscribeRoot = this.#rootBus.subscribe(onEvent); - const unsubscribeThread = this.#thread?.onEvent(onEvent); - if (signal.aborted) - finishAborted(); - else - signal.addEventListener("abort", finishAborted, { once: true }); + const metadata = { ...message.response_metadata }; + const contextEntry = { ...metadata.context_editing }; + const clearedIds = new Set(contextEntry.cleared_tool_inputs); + clearedIds.add(toolCallId); + contextEntry.cleared_tool_inputs = Array.from(clearedIds).sort(); + metadata.context_editing = contextEntry; + return new AIMessage({ + content: message.content, + tool_calls: updatedToolCalls, + response_metadata: metadata, + id: message.id, + name: message.name, + additional_kwargs: message.additional_kwargs }); } - #latestUnresolvedInterrupt() { - const thread = this.#thread; - if (thread == null) - return null; - for (let i = thread.interrupts.length - 1;i >= 0; i -= 1) { - const entry = thread.interrupts[i]; - if (entry == null) - continue; - if (this.#resolvedInterrupts.has(entry.interruptId)) - continue; - return { - interruptId: entry.interruptId, - namespace: entry.namespace - }; - } - return null; - } - #notifyThreadListeners() { - for (const listener of this.#threadListeners) - listener(this.#thread); - } }; -var init_controller = __esm(() => { - init_messages6(); - init_tools4(); - init_store2(); - init_channel_registry(); - init_namespace2(); - init_subagents2(); - init_subgraphs3(); - init_message_metadata_tracker(); - init_lifecycle_loading_tracker(); - init_root_message_projection(); - init_submit_coordinator(); - init_tool_calls(); +var init_contextEditing = __esm(() => { + init_utils10(); + init_middleware(); + init_summarization(); init_messages(); - ROOT_NAMESPACE = []; - ROOT_PUMP_CHANNELS = [ - "values", - "checkpoints", - "lifecycle", - "input", - "messages", - "tools" +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/toolCallLimit.js +var VALID_EXIT_BEHAVIORS, DEFAULT_EXIT_BEHAVIOR = "continue", exitBehaviorSchema, stateSchema; +var init_toolCallLimit = __esm(() => { + init_middleware(); + init_messages(); + init_v3(); + VALID_EXIT_BEHAVIORS = [ + "continue", + "error", + "end" ]; + exitBehaviorSchema = exports_external2.enum(VALID_EXIT_BEHAVIORS).default(DEFAULT_EXIT_BEHAVIOR); + exports_external2.object({ + toolName: exports_external2.string().optional(), + threadLimit: exports_external2.number().optional(), + runLimit: exports_external2.number().optional(), + exitBehavior: exitBehaviorSchema + }); + stateSchema = exports_external2.object({ + threadToolCallCount: exports_external2.record(exports_external2.string(), exports_external2.number()).default({}), + runToolCallCount: exports_external2.record(exports_external2.string(), exports_external2.number()).default({}) + }); }); -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/runtime.js -var init_runtime3 = () => {}; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/todoListMiddleware.js +function todoListMiddleware(options) { + const writeTodos = tool(({ todos }, config3) => { + return new Command({ update: { + todos, + messages: [new ToolMessage({ + content: `Updated todo list to ${JSON.stringify(todos)}`, + tool_call_id: config3.toolCall?.id, + name: "write_todos" + })] + } }); + }, { + name: "write_todos", + description: options?.toolDescription ?? WRITE_TODOS_DESCRIPTION, + schema: exports_external2.object({ todos: exports_external2.array(TodoSchema).describe("List of todo items to update") }) + }); + return createMiddleware({ + name: "todoListMiddleware", + stateSchema: stateSchema2, + tools: [writeTodos], + wrapModelCall: (request, handler) => handler({ + ...request, + systemMessage: request.systemMessage.concat(` -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/messages.js -var init_messages7 = __esm(() => { - init_messages6(); - init_messages5(); - init_namespace2(); - init_assembled_to_message(); - init_message_reconciliation(); - init_runtime3(); -}); +${options?.systemPrompt ?? TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT}`) + }), + afterModel: (state) => { + const messages = state.messages; + if (!messages || messages.length === 0) + return; + const lastAiMsg = [...messages].reverse().find((msg) => AIMessage.isInstance(msg)); + if (!lastAiMsg || !lastAiMsg.tool_calls || lastAiMsg.tool_calls.length === 0) + return; + const writeTodosCalls = lastAiMsg.tool_calls.filter((tc) => tc.name === writeTodos.name); + if (writeTodosCalls.length > 1) + return { messages: writeTodosCalls.map((tc) => new ToolMessage({ + content: "Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.", + tool_call_id: tc.id, + name: "write_todos", + status: "error" + })) }; + } + }); +} +var WRITE_TODOS_DESCRIPTION = `Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. +It also helps the user understand the progress of the task and overall progress of their requests. +Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly. -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/tool-calls.js -var init_tool_calls2 = __esm(() => { - init_tools4(); - init_namespace2(); - init_tool_calls(); - init_runtime3(); -}); +## When to Use This Tool +Use this tool in these scenarios: -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/values.js -var init_values3 = __esm(() => { - init_messages6(); - init_namespace2(); - init_runtime3(); -}); +1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions +2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations +3. User explicitly requests todo list - When the user directly asks you to use the todo list +4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated) +5. The plan may need future revisions or updates based on results from the first few steps. Keeping track of this in a list is helpful. -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/extension.js -var init_extension = __esm(() => { - init_namespace2(); - init_runtime3(); -}); +## How to Use This Tool +1. When you start working on a task - Mark it as in_progress BEFORE beginning work. +2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation. +3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks. +4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress. -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/channel.js -var init_channel = __esm(() => { - init_namespace2(); - init_runtime3(); -}); +## When NOT to Use This Tool +It is important to skip using this tool when: +1. There is only a single, straightforward task +2. The task is trivial and tracking it provides no benefit +3. The task can be completed in less than 3 trivial steps +4. The task is purely conversational or informational -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/media.js -var init_media2 = __esm(() => { - init_media(); - init_namespace2(); - init_runtime3(); -}); +## Examples of When to Use the Todo List -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/projections/index.js -var init_projections = __esm(() => { - init_messages7(); - init_tool_calls2(); - init_values3(); - init_extension(); - init_channel(); - init_media2(); -}); + +User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done! +Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation. +*Creates todo list with the following items:* +1. Create dark mode toggle component in Settings page +2. Add dark mode state management (context/store) +3. Implement CSS-in-JS styles for dark theme +4. Update existing components to support theme switching +5. Run tests and build process, addressing any failures or errors that occur +*Begins working on the first task* -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/stream/index.js -var init_stream10 = __esm(() => { - init_media(); - init_constants5(); - init_store2(); - init_channel_registry(); - init_subagents2(); - init_subgraphs3(); - init_assembled_to_message(); - init_controller(); - init_messages7(); - init_tool_calls2(); - init_values3(); - init_extension(); - init_channel(); - init_media2(); - init_projections(); -}); + +The assistant used the todo list because: +1. Adding dark mode in it of itself is a multi-step feature requiring UI, state management, and styling changes +2. The assistant inferred that tests and build need to pass by adding "Ensure tests and build succeed" as the final task +3. Both of the user's requests are complex and require multiple steps to complete. + + + + +User: Help me plan a comprehensive marketing campaign for our new product launch, including social media, email marketing, and press releases. +Assistant: I'll help you plan a comprehensive marketing campaign for your product launch. Let me create a todo list to organize all the components. +*Creates todo list with the following items:* +1. Define target audience and key messaging +2. Create social media content calendar and posting schedule +3. Design email marketing sequence and automation flows +4. Draft press release and identify media contacts +5. Set up tracking and analytics for campaign performance +6. Create visual assets and brand materials +7. Coordinate launch timeline and deliverables +*Begins working on the first task* -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/ui/errors.js -var init_errors7 = () => {}; + +The assistant used the todo list because: +1. Marketing campaign planning involves multiple distinct channels and activities +2. Each component requires careful coordination and planning +3. The systematic approach ensures all aspects of the launch are covered + + -// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1__5khwfwl3ux64kniy2ex4qvsryu/node_modules/@langchain/langgraph-sdk/dist/index.js -var init_dist7 = __esm(() => { - init_fetch2(); - init_base16(); - init_messages5(); - init_media(); - init_error4(); - init_constants5(); - init_headless_tools(); - init_stream8(); - init_http(); - init_websocket(); - init_agent_server(); - init_client2(); - init_client3(); - init_stream10(); - init_errors7(); + +User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project +Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'. +*Uses search tools to locate all instances of getCwd in the codebase* +Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes. +*Creates todo list with specific items for each file that needs updating* + + +The assistant used the todo list because: +1. The assistant searched to understand the scope of the task +2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps (>3) +3. The todo list helps ensure every instance is tracked and updated systematically +4. This approach prevents missing any occurrences and maintains consistency. + + + + +User: I need help organizing my home office: decluttering the desk, setting up a filing system, organizing digital files, and creating a daily workflow. +Assistant: I'll help you organize your home office systematically. Let me create a todo list to track each area of organization. +*Creates todo list with items like: 1) Sort and declutter desk items, 2) Set up physical filing system for documents, 3) Organize digital files and folders, 4) Create daily workflow and productivity systems, 5) Establish maintenance routines* +Let's start with decluttering your desk space to create a clean foundation for the other organizational systems. + + +The assistant used the todo list because: +1. The user provided multiple distinct organizational tasks +2. Each area requires different approaches and careful planning +3. Home organization benefits from systematic, step-by-step completion +4. Progress tracking ensures all areas are addressed thoroughly + + + +## Examples of When NOT to Use the Todo List + + +User: How do I print 'Hello World' in Python? +Assistant: In Python, you can print "Hello World" with this simple code: + +\`\`\`python +print("Hello World") +\`\`\` + +This will output the text "Hello World" to the console when executed. + + +The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request. + + + + +User: What's the best way to water houseplants? +Assistant: The best way to water houseplants depends on the specific plant type, but here are some general guidelines: + +- Check soil moisture by inserting your finger about 1-2 inches into the soil +- Water thoroughly when the top inch feels dry, allowing water to drain from the bottom +- Use room temperature water and water in the morning when possible +- Avoid overwatering, which is more harmful than underwatering for most plants + +Different plants have different needs, so it's important to research your specific varieties for optimal care. + + +The assistant did not use the todo list because this is an informational request with no actual tasks to complete. The user is simply asking for advice and explanation, not for the assistant to perform multiple steps or activities. + + + + +User: Can you add a comment to the calculateTotal function to explain what it does? +Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does. +* Uses the Edit tool to add a comment to the calculateTotal function * + + +The assistant did not use the todo list because this is a single, straightforward task confined to one location. Adding a comment doesn't require tracking multiple steps or systematic organization. + + + + +User: What time is it in Tokyo right now? +Assistant: I'll check the current time in Tokyo for you. + +*Searches for current time in Tokyo* + +The current time in Tokyo, Japan is [current time]. Tokyo is in the Japan Standard Time (JST) zone, which is UTC+9. + + +The assistant did not use the todo list because this is a single information lookup with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward request. + + + + +User: I need to write a function that checks if a number is prime and then test it out. +Assistant: I'll help you write a function that checks if a number is prime and then test it out. +*Writes function that checks if a number is prime* +*Tests the function* + + +Even though this is a multi-step task, it is very straightforward and can be completed in two trivial steps (which is less than 3 steps!). Using the todo list here is overkill and wastes time and tokens. + + + + +User: I want you to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. +Assistant: I'll help you order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway. +*Orders a pizza from Dominos* +*Orders a burger from McDonald's* +*Orders a salad from Subway* + + +Even though this is a multi-step task, assuming the assistant has the ability to order from these restaurants, it is very straightforward and can be completed in three trivial tool calls. +Using the todo list here is overkill and wastes time and tokens. These three tool calls should be made in parallel, in fact. + + + + +## Task States and Management + +1. **Task States**: Use these states to track progress: + - pending: Task not yet started + - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel) + - completed: Task finished successfully + +2. **Task Management**: + - Update task status in real-time as you work + - Mark tasks complete IMMEDIATELY after finishing (don't batch completions) + - Complete current tasks before starting new ones + - Remove tasks that are no longer relevant from the list entirely + - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!. + - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress to show the user that you are working on something. + +3. **Task Completion Requirements**: + - ONLY mark a task as completed when you have FULLY accomplished it + - If you encounter errors, blockers, or cannot finish, keep the task as in_progress + - When blocked, create a new task describing what needs to be resolved + - Never mark a task as completed if: + - There are unresolved issues or errors + - Work is partial or incomplete + - You encountered blockers that prevent completion + - You couldn't find necessary resources or dependencies + - Quality standards haven't been met + +4. **Task Breakdown**: + - Create specific, actionable items + - Break complex tasks into smaller, manageable steps + - Use clear, descriptive task names + +Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully +Remember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.`, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = `## \`write_todos\` + +You have access to the \`write_todos\` tool to help you manage and plan complex objectives. +Use this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress. +This tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps. + +It is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed. +For simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool. +Writing todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests. + +## Important To-Do List Usage Notes to Remember +- The \`write_todos\` tool should never be called multiple times in parallel. +- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`, TodoStatus, TodoSchema, stateSchema2; +var init_todoListMiddleware = __esm(() => { + init_middleware(); + init_agents2(); + init_messages(); + init_tools2(); + init_dist4(); + init_v3(); + TodoStatus = exports_external2.enum([ + "pending", + "in_progress", + "completed" + ]).describe("Status of the todo"); + TodoSchema = exports_external2.object({ + content: exports_external2.string().describe("Content of the todo item"), + status: TodoStatus + }); + stateSchema2 = exports_external2.object({ todos: exports_external2.array(TodoSchema).default([]) }); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/array.js -var require_array = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.splitWhen = exports.flatten = undefined; - function flatten(items) { - return items.reduce((collection, item) => [].concat(collection, item), []); - } - exports.flatten = flatten; - function splitWhen(items, predicate) { - const result = [[]]; - let groupIndex = 0; - for (const item of items) { - if (predicate(item)) { - groupIndex++; - result[groupIndex] = []; - } else { - result[groupIndex].push(item); - } - } - return result; - } - exports.splitWhen = splitWhen; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/modelCallLimit.js +var contextSchema5, stateSchema3; +var init_modelCallLimit = __esm(() => { + init_middleware(); + init_messages(); + init_v3(); + contextSchema5 = exports_external2.object({ + threadLimit: exports_external2.number().optional(), + runLimit: exports_external2.number().optional(), + exitBehavior: exports_external2.enum(["error", "end"]).optional() + }); + stateSchema3 = exports_external2.object({ + threadModelCallCount: exports_external2.number().default(0), + runModelCallCount: exports_external2.number().default(0) + }); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/errno.js -var require_errno = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isEnoentCodeError = undefined; - function isEnoentCodeError(error51) { - return error51.code === "ENOENT"; - } - exports.isEnoentCodeError = isEnoentCodeError; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/modelFallback.js +var init_modelFallback = __esm(() => { + init_universal(); + init_middleware(); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/fs.js -var require_fs = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createDirentFromStats = undefined; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/constants.js +var RetrySchema; +var init_constants4 = __esm(() => { + init_v3(); + RetrySchema = exports_external2.object({ + maxRetries: exports_external2.number().min(0).default(2), + retryOn: exports_external2.union([exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.boolean()), exports_external2.array(exports_external2.custom())]).default(() => () => true), + backoffFactor: exports_external2.number().min(0).default(2), + initialDelayMs: exports_external2.number().min(0).default(1000), + maxDelayMs: exports_external2.number().min(0).default(60000), + jitter: exports_external2.boolean().default(true) + }); +}); - class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } - } - function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); - } - exports.createDirentFromStats = createDirentFromStats; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/error.js +var init_error2 = () => {}; + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/modelRetry.js +var ModelRetryMiddlewareOptionsSchema; +var init_modelRetry = __esm(() => { + init_utils10(); + init_middleware(); + init_constants4(); + init_error2(); + init_messages(); + init_v3(); + ModelRetryMiddlewareOptionsSchema = exports_external2.object({ onFailure: exports_external2.union([ + exports_external2.literal("error"), + exports_external2.literal("continue"), + exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.string()) + ]).default("continue") }).merge(RetrySchema); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/path.js -var require_path = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = undefined; - var os = __require("os"); - var path2 = __require("path"); - var IS_WINDOWS_PLATFORM = os.platform() === "win32"; - var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; - var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; - var WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; - var DOS_DEVICE_PATH_RE = /^\\\\([.?])/; - var WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; - function unixify(filepath) { - return filepath.replace(/\\/g, "/"); - } - exports.unixify = unixify; - function makeAbsolute(cwd, filepath) { - return path2.resolve(cwd, filepath); - } - exports.makeAbsolute = makeAbsolute; - function removeLeadingDotSegment(entry) { - if (entry.charAt(0) === ".") { - const secondCharactery = entry.charAt(1); - if (secondCharactery === "/" || secondCharactery === "\\") { - return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); - } - } - return entry; - } - exports.removeLeadingDotSegment = removeLeadingDotSegment; - exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; - function escapeWindowsPath(pattern) { - return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); - } - exports.escapeWindowsPath = escapeWindowsPath; - function escapePosixPath(pattern) { - return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); - } - exports.escapePosixPath = escapePosixPath; - exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; - function convertWindowsPathToPattern(filepath) { - return escapeWindowsPath(filepath).replace(DOS_DEVICE_PATH_RE, "//$1").replace(WINDOWS_BACKSLASHES_RE, "/"); - } - exports.convertWindowsPathToPattern = convertWindowsPathToPattern; - function convertPosixPathToPattern(filepath) { - return escapePosixPath(filepath); - } - exports.convertPosixPathToPattern = convertPosixPathToPattern; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/toolRetry.js +var ToolRetryMiddlewareOptionsSchema; +var init_toolRetry = __esm(() => { + init_utils10(); + init_middleware(); + init_constants4(); + init_error2(); + init_messages(); + init_v3(); + ToolRetryMiddlewareOptionsSchema = exports_external2.object({ + tools: exports_external2.array(exports_external2.union([ + exports_external2.custom(), + exports_external2.custom(), + exports_external2.string() + ])).optional(), + onFailure: exports_external2.union([ + exports_external2.literal("error"), + exports_external2.literal("continue"), + exports_external2.literal("raise"), + exports_external2.literal("return_message"), + exports_external2.function().args(exports_external2.instanceof(Error)).returns(exports_external2.string()) + ]).default("continue") + }).merge(RetrySchema); }); -// ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js -var require_is_extglob = __commonJS((exports, module) => { - /*! - * is-extglob - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ - module.exports = function isExtglob(str) { - if (typeof str !== "string" || str === "") { - return false; - } - var match2; - while (match2 = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { - if (match2[2]) - return true; - str = str.slice(match2.index + match2[0].length); - } - return false; - }; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/toolEmulator.js +var init_toolEmulator = __esm(() => { + init_universal(); + init_middleware(); + init_messages(); }); -// ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js -var require_is_glob = __commonJS((exports, module) => { - /*! - * is-glob - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - var isExtglob = require_is_extglob(); - var chars = { "{": "}", "(": ")", "[": "]" }; - var strictCheck = function(str) { - if (str[0] === "!") { - return true; - } - var index2 = 0; - var pipeIndex = -2; - var closeSquareIndex = -2; - var closeCurlyIndex = -2; - var closeParenIndex = -2; - var backSlashIndex = -2; - while (index2 < str.length) { - if (str[index2] === "*") { - return true; - } - if (str[index2 + 1] === "?" && /[\].+)]/.test(str[index2])) { - return true; - } - if (closeSquareIndex !== -1 && str[index2] === "[" && str[index2 + 1] !== "]") { - if (closeSquareIndex < index2) { - closeSquareIndex = str.indexOf("]", index2); - } - if (closeSquareIndex > index2) { - if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { - return true; - } - backSlashIndex = str.indexOf("\\", index2); - if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { - return true; - } - } - } - if (closeCurlyIndex !== -1 && str[index2] === "{" && str[index2 + 1] !== "}") { - closeCurlyIndex = str.indexOf("}", index2); - if (closeCurlyIndex > index2) { - backSlashIndex = str.indexOf("\\", index2); - if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { - return true; - } - } - } - if (closeParenIndex !== -1 && str[index2] === "(" && str[index2 + 1] === "?" && /[:!=]/.test(str[index2 + 2]) && str[index2 + 3] !== ")") { - closeParenIndex = str.indexOf(")", index2); - if (closeParenIndex > index2) { - backSlashIndex = str.indexOf("\\", index2); - if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { - return true; - } - } - } - if (pipeIndex !== -1 && str[index2] === "(" && str[index2 + 1] !== "|") { - if (pipeIndex < index2) { - pipeIndex = str.indexOf("|", index2); - } - if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") { - closeParenIndex = str.indexOf(")", pipeIndex); - if (closeParenIndex > pipeIndex) { - backSlashIndex = str.indexOf("\\", pipeIndex); - if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { - return true; - } - } - } - } - if (str[index2] === "\\") { - var open = str[index2 + 1]; - index2 += 2; - var close = chars[open]; - if (close) { - var n3 = str.indexOf(close, index2); - if (n3 !== -1) { - index2 = n3 + 1; - } - } - if (str[index2] === "!") { - return true; - } - } else { - index2++; - } - } - return false; - }; - var relaxedCheck = function(str) { - if (str[0] === "!") { - return true; - } - var index2 = 0; - while (index2 < str.length) { - if (/[*?{}()[\]]/.test(str[index2])) { - return true; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/provider/openai/moderation.js +var init_moderation = __esm(() => { + init_universal(); + init_middleware(); + init_messages(); +}); + +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/provider/anthropic/promptCaching.js +function anthropicPromptCachingMiddleware(middlewareOptions) { + return createMiddleware({ + name: "PromptCachingMiddleware", + contextSchema: contextSchema6, + wrapModelCall: (request, handler) => { + const enableCaching = request.runtime.context.enableCaching ?? middlewareOptions?.enableCaching ?? DEFAULT_ENABLE_CACHING; + const ttl = request.runtime.context.ttl ?? middlewareOptions?.ttl ?? DEFAULT_TTL; + const minMessagesToCache = request.runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache ?? DEFAULT_MIN_MESSAGES_TO_CACHE; + const unsupportedModelBehavior = request.runtime.context.unsupportedModelBehavior ?? middlewareOptions?.unsupportedModelBehavior ?? DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR; + if (!enableCaching || !request.model) + return handler(request); + if (!(request.model.getName() === "ChatAnthropic" || request.model.getName() === "ConfigurableModel" && request.model._defaultConfig?.modelProvider === "anthropic")) { + const modelName = request.model.getName(); + const baseMessage = `Unsupported model '${request.model.getName() === "ConfigurableModel" ? `${modelName} (${request.model._defaultConfig?.modelProvider})` : modelName}'. Prompt caching requires an Anthropic model`; + if (unsupportedModelBehavior === "raise") + throw new PromptCachingMiddlewareError(`${baseMessage} (e.g., 'anthropic:claude-4-0-sonnet').`); + else if (unsupportedModelBehavior === "warn") + console.warn(`PromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic model for caching benefits.`); + return handler(request); } - if (str[index2] === "\\") { - var open = str[index2 + 1]; - index2 += 2; - var close = chars[open]; - if (close) { - var n3 = str.indexOf(close, index2); - if (n3 !== -1) { - index2 = n3 + 1; + if (request.state.messages.length + (request.systemPrompt ? 1 : 0) < minMessagesToCache) + return handler(request); + return handler({ + ...request, + modelSettings: { + ...request.modelSettings, + cache_control: { + type: "ephemeral", + ttl } } - if (str[index2] === "!") { - return true; - } - } else { - index2++; - } - } - return false; - }; - module.exports = function isGlob(str, options) { - if (typeof str !== "string" || str === "") { - return false; - } - if (isExtglob(str)) { - return true; + }); } - var check2 = strictCheck; - if (options && options.strict === false) { - check2 = relaxedCheck; + }); +} +var DEFAULT_ENABLE_CACHING = true, DEFAULT_TTL = "5m", DEFAULT_MIN_MESSAGES_TO_CACHE = 3, DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR = "warn", contextSchema6, PromptCachingMiddlewareError; +var init_promptCaching = __esm(() => { + init_middleware(); + init_v3(); + contextSchema6 = exports_external2.object({ + enableCaching: exports_external2.boolean().optional(), + ttl: exports_external2.enum(["5m", "1h"]).optional(), + minMessagesToCache: exports_external2.number().optional(), + unsupportedModelBehavior: exports_external2.enum([ + "ignore", + "warn", + "raise" + ]).optional() + }); + PromptCachingMiddlewareError = class extends Error { + constructor(message) { + super(message); + this.name = "PromptCachingMiddlewareError"; } - return check2(str); }; }); -// ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js -var require_glob_parent = __commonJS((exports, module) => { - var isGlob = require_is_glob(); - var pathPosixDirname = __require("path").posix.dirname; - var isWin32 = __require("os").platform() === "win32"; - var slash = "/"; - var backslash = /\\/g; - var enclosure = /[\{\[].*[\}\]]$/; - var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; - var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; - module.exports = function globParent(str, opts) { - var options = Object.assign({ flipBackslashes: true }, opts); - if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { - str = str.replace(backslash, slash); - } - if (enclosure.test(str)) { - str += slash; - } - str += "a"; - do { - str = pathPosixDirname(str); - } while (isGlob(str) || globby.test(str)); - return str.replace(escaped, "$1"); - }; +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/agents/middleware/index.js +var init_middleware3 = __esm(() => { + init_utils10(); + init_hitl(); + init_summarization(); + init_dynamicSystemPrompt(); + init_llmToolSelector(); + init_pii(); + init_piiRedaction(); + init_contextEditing(); + init_toolCallLimit(); + init_todoListMiddleware(); + init_modelCallLimit(); + init_modelFallback(); + init_modelRetry(); + init_toolRetry(); + init_toolEmulator(); + init_moderation(); + init_promptCaching(); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/pattern.js -var require_pattern = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = undefined; - var path2 = __require("path"); - var globParent = require_glob_parent(); - var micromatch = require_micromatch(); - var GLOBSTAR = "**"; - var ESCAPE_SYMBOL = "\\"; - var COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; - var REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; - var REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; - var GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; - var BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; - var DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; - function isStaticPattern(pattern, options = {}) { - return !isDynamicPattern(pattern, options); +// ../../node_modules/.pnpm/langchain@1.4.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base_ggdpuwmlyx5veiduq5e3ilmlkm/node_modules/langchain/dist/index.js +var init_dist5 = __esm(() => { + init_runtime(); + init_universal(); + init_headless(); + init_errors8(); + init_responses(); + init_utils10(); + init_stream6(); + init_types10(); + init_middleware(); + init_utils11(); + init_agents2(); + init_hitl(); + init_summarization(); + init_dynamicSystemPrompt(); + init_llmToolSelector(); + init_pii(); + init_piiRedaction(); + init_contextEditing(); + init_toolCallLimit(); + init_todoListMiddleware(); + init_modelCallLimit(); + init_modelFallback(); + init_modelRetry(); + init_toolRetry(); + init_toolEmulator(); + init_moderation(); + init_promptCaching(); + init_middleware3(); + init_messages(); + init_tools2(); + init_context2(); + init_stores(); + init_documents(); + init_testing(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/setup/async_local_storage.js +import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks"; +function initializeAsyncLocalStorageSingleton2() { + AsyncLocalStorageProviderSingleton2.initializeGlobalInstance(new AsyncLocalStorage2); +} +var init_async_local_storage3 = __esm(() => { + init_singletons(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/constants.js +function _isSendInterface2(x) { + const operation = x; + return operation !== null && operation !== undefined && typeof operation.node === "string" && operation.args !== undefined; +} +function _isSend2(x) { + return x instanceof Send2; +} +function _getOverwriteValue2(value) { + if (typeof value === "object" && value !== null && "__overwrite__" in value) + return [true, value[OVERWRITE2]]; + return [false, undefined]; +} +function _isOverwriteValue2(value) { + return _getOverwriteValue2(value)[0]; +} +function isInterrupted2(values) { + if (!values || typeof values !== "object") + return false; + if (!("__interrupt__" in values)) + return false; + return Array.isArray(values[INTERRUPT3]); +} +function isCommand2(x) { + if (typeof x !== "object") + return false; + if (x === null || x === undefined) + return false; + if ("lg_name" in x && x.lg_name === "Command") + return true; + return false; +} +function _deserializeCommandSendObjectGraph2(x, seen = /* @__PURE__ */ new Map) { + if (x !== undefined && x !== null && typeof x === "object") { + if (seen.has(x)) + return seen.get(x); + let result; + if (Array.isArray(x)) { + result = []; + seen.set(x, result); + x.forEach((item, index2) => { + result[index2] = _deserializeCommandSendObjectGraph2(item, seen); + }); + } else if (isCommand2(x) && !(x instanceof Command2)) { + result = new Command2(x); + seen.set(x, result); + } else if (_isSendInterface2(x) && !(x instanceof Send2)) { + result = new Send2(x.node, x.args); + seen.set(x, result); + } else if (isCommand2(x) || _isSend2(x)) { + result = x; + seen.set(x, result); + } else if ("lc_serializable" in x && x.lc_serializable) { + result = x; + seen.set(x, result); + } else { + result = {}; + seen.set(x, result); + for (const [key, value] of Object.entries(x)) + result[key] = _deserializeCommandSendObjectGraph2(value, seen); + } + return result; } - exports.isStaticPattern = isStaticPattern; - function isDynamicPattern(pattern, options = {}) { - if (pattern === "") { - return false; + return x; +} +var START2 = "__start__", END2 = "__end__", INPUT2 = "__input__", ERROR4 = "__error__", CACHE_NS_WRITES2 = "__pregel_ns_writes", CONFIG_KEY_SEND2 = "__pregel_send", CONFIG_KEY_CALL2 = "__pregel_call", CONFIG_KEY_READ2 = "__pregel_read", CONFIG_KEY_CHECKPOINTER2 = "__pregel_checkpointer", CONFIG_KEY_RESUMING2 = "__pregel_resuming", CONFIG_KEY_TASK_ID2 = "__pregel_task_id", CONFIG_KEY_STREAM2 = "__pregel_stream", CONFIG_KEY_RESUME_VALUE2 = "__pregel_resume_value", CONFIG_KEY_RESUME_MAP2 = "__pregel_resume_map", CONFIG_KEY_SCRATCHPAD2 = "__pregel_scratchpad", CONFIG_KEY_PREVIOUS_STATE2 = "__pregel_previous", CONFIG_KEY_DURABILITY2 = "__pregel_durability", CONFIG_KEY_CHECKPOINT_ID2 = "checkpoint_id", CONFIG_KEY_CHECKPOINT_NS2 = "checkpoint_ns", CONFIG_KEY_NODE_FINISHED2 = "__pregel_node_finished", CONFIG_KEY_CHECKPOINT_MAP2 = "checkpoint_map", CONFIG_KEY_ABORT_SIGNALS2 = "__pregel_abort_signals", INTERRUPT3 = "__interrupt__", RESUME3 = "__resume__", NO_WRITES2 = "__no_writes__", RETURN2 = "__return__", PREVIOUS2 = "__previous__", TAG_HIDDEN2 = "langsmith:hidden", TASKS3 = "__pregel_tasks", PUSH2 = "__pregel_push", PULL2 = "__pregel_pull", NULL_TASK_ID2 = "00000000-0000-0000-0000-000000000000", RESERVED2, COMMAND_SYMBOL2, CommandInstance2, Send2 = class { + lg_name = "Send"; + node; + args; + constructor(node, args) { + this.node = node; + this.args = _deserializeCommandSendObjectGraph2(args); + } + toJSON() { + return { + lg_name: this.lg_name, + node: this.node, + args: this.args + }; + } +}, OVERWRITE2 = "__overwrite__", Command2; +var init_constants5 = __esm(() => { + RESERVED2 = [ + TAG_HIDDEN2, + INPUT2, + INTERRUPT3, + RESUME3, + ERROR4, + NO_WRITES2, + CONFIG_KEY_SEND2, + CONFIG_KEY_READ2, + CONFIG_KEY_CHECKPOINTER2, + CONFIG_KEY_DURABILITY2, + CONFIG_KEY_STREAM2, + CONFIG_KEY_RESUMING2, + CONFIG_KEY_TASK_ID2, + CONFIG_KEY_CALL2, + CONFIG_KEY_RESUME_VALUE2, + CONFIG_KEY_SCRATCHPAD2, + CONFIG_KEY_PREVIOUS_STATE2, + CONFIG_KEY_CHECKPOINT_MAP2, + CONFIG_KEY_CHECKPOINT_NS2, + CONFIG_KEY_CHECKPOINT_ID2 + ]; + COMMAND_SYMBOL2 = Symbol.for("langgraph.command"); + CommandInstance2 = class { + [COMMAND_SYMBOL2]; + constructor(args) { + this[COMMAND_SYMBOL2] = args; } - if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { - return true; + }; + Command2 = class extends CommandInstance2 { + lg_name = "Command"; + lc_direct_tool_output = true; + graph; + update; + resume; + goto = []; + static PARENT = "__parent__"; + constructor(args) { + super(args); + this.resume = args.resume; + this.graph = args.graph; + this.update = args.update; + if (args.goto) + this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph2(args.goto) : [_deserializeCommandSendObjectGraph2(args.goto)]; } - if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { - return true; + _updateAsTuples() { + if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) + return Object.entries(this.update); + else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) + return this.update; + else + return [["__root__", this.update]]; } - if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { - return true; + toJSON() { + let serializedGoto; + if (typeof this.goto === "string") + serializedGoto = this.goto; + else if (_isSend2(this.goto)) + serializedGoto = this.goto.toJSON(); + else + serializedGoto = this.goto?.map((innerGoto) => { + if (typeof innerGoto === "string") + return innerGoto; + else + return innerGoto.toJSON(); + }); + return { + lg_name: this.lg_name, + update: this.update, + resume: this.resume, + goto: serializedGoto + }; } - if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/errors.js +function isParentCommand2(e) { + return e !== undefined && e.name === ParentCommand2.unminifiable_name; +} +function isGraphBubbleUp2(e) { + return e !== undefined && e.is_bubble_up === true; +} +function isGraphInterrupt2(e) { + return e !== undefined && [GraphInterrupt2.unminifiable_name, NodeInterrupt2.unminifiable_name].includes(e.name); +} +var BaseLangGraphError2, GraphBubbleUp2, GraphRecursionError2, GraphValueError2, GraphInterrupt2, NodeInterrupt2, ParentCommand2, EmptyInputError2, EmptyChannelError2, InvalidUpdateError2; +var init_errors9 = __esm(() => { + BaseLangGraphError2 = class extends Error { + lc_error_code; + constructor(message, fields) { + let finalMessage = message ?? ""; + if (fields?.lc_error_code) + finalMessage = `${finalMessage} + +Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/ +`; + super(finalMessage); + this.lc_error_code = fields?.lc_error_code; + } + }; + GraphBubbleUp2 = class extends BaseLangGraphError2 { + get is_bubble_up() { return true; } - return false; - } - exports.isDynamicPattern = isDynamicPattern; - function hasBraceExpansion(pattern) { - const openingBraceIndex = pattern.indexOf("{"); - if (openingBraceIndex === -1) { - return false; + }; + GraphRecursionError2 = class extends BaseLangGraphError2 { + constructor(message, fields) { + super(message, fields); + this.name = "GraphRecursionError"; } - const closingBraceIndex = pattern.indexOf("}", openingBraceIndex + 1); - if (closingBraceIndex === -1) { - return false; + static get unminifiable_name() { + return "GraphRecursionError"; } - const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); - return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); - } - function convertToPositivePattern(pattern) { - return isNegativePattern(pattern) ? pattern.slice(1) : pattern; - } - exports.convertToPositivePattern = convertToPositivePattern; - function convertToNegativePattern(pattern) { - return "!" + pattern; - } - exports.convertToNegativePattern = convertToNegativePattern; - function isNegativePattern(pattern) { - return pattern.startsWith("!") && pattern[1] !== "("; - } - exports.isNegativePattern = isNegativePattern; - function isPositivePattern(pattern) { - return !isNegativePattern(pattern); - } - exports.isPositivePattern = isPositivePattern; - function getNegativePatterns(patterns) { - return patterns.filter(isNegativePattern); - } - exports.getNegativePatterns = getNegativePatterns; - function getPositivePatterns(patterns) { - return patterns.filter(isPositivePattern); - } - exports.getPositivePatterns = getPositivePatterns; - function getPatternsInsideCurrentDirectory(patterns) { - return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); - } - exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; - function getPatternsOutsideCurrentDirectory(patterns) { - return patterns.filter(isPatternRelatedToParentDirectory); - } - exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; - function isPatternRelatedToParentDirectory(pattern) { - return pattern.startsWith("..") || pattern.startsWith("./.."); - } - exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; - function getBaseDirectory(pattern) { - return globParent(pattern, { flipBackslashes: false }); - } - exports.getBaseDirectory = getBaseDirectory; - function hasGlobStar(pattern) { - return pattern.includes(GLOBSTAR); - } - exports.hasGlobStar = hasGlobStar; - function endsWithSlashGlobStar(pattern) { - return pattern.endsWith("/" + GLOBSTAR); - } - exports.endsWithSlashGlobStar = endsWithSlashGlobStar; - function isAffectDepthOfReadingPattern(pattern) { - const basename = path2.basename(pattern); - return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); - } - exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; - function expandPatternsWithBraceExpansion(patterns) { - return patterns.reduce((collection, pattern) => { - return collection.concat(expandBraceExpansion(pattern)); - }, []); - } - exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; - function expandBraceExpansion(pattern) { - const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); - patterns.sort((a, b) => a.length - b.length); - return patterns.filter((pattern2) => pattern2 !== ""); - } - exports.expandBraceExpansion = expandBraceExpansion; - function getPatternParts(pattern, options) { - let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); - if (parts.length === 0) { - parts = [pattern]; + }; + GraphValueError2 = class extends BaseLangGraphError2 { + constructor(message, fields) { + super(message, fields); + this.name = "GraphValueError"; } - if (parts[0].startsWith("/")) { - parts[0] = parts[0].slice(1); - parts.unshift(""); + static get unminifiable_name() { + return "GraphValueError"; } - return parts; - } - exports.getPatternParts = getPatternParts; - function makeRe(pattern, options) { - return micromatch.makeRe(pattern, options); - } - exports.makeRe = makeRe; - function convertPatternsToRe(patterns, options) { - return patterns.map((pattern) => makeRe(pattern, options)); - } - exports.convertPatternsToRe = convertPatternsToRe; - function matchAny(entry, patternsRe) { - return patternsRe.some((patternRe) => patternRe.test(entry)); - } - exports.matchAny = matchAny; - function removeDuplicateSlashes(pattern) { - return pattern.replace(DOUBLE_SLASH_RE, "/"); - } - exports.removeDuplicateSlashes = removeDuplicateSlashes; - function partitionAbsoluteAndRelative(patterns) { - const absolute = []; - const relative2 = []; - for (const pattern of patterns) { - if (isAbsolute2(pattern)) { - absolute.push(pattern); - } else { - relative2.push(pattern); - } + }; + GraphInterrupt2 = class extends GraphBubbleUp2 { + interrupts; + constructor(interrupts, fields) { + super(JSON.stringify(interrupts, null, 2), fields); + this.name = "GraphInterrupt"; + this.interrupts = interrupts ?? []; } - return [absolute, relative2]; - } - exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; - function isAbsolute2(pattern) { - return path2.isAbsolute(pattern); - } - exports.isAbsolute = isAbsolute2; -}); - -// ../../node_modules/.pnpm/merge2@1.4.1/node_modules/merge2/index.js -var require_merge2 = __commonJS((exports, module) => { - var Stream = __require("stream"); - var PassThrough = Stream.PassThrough; - var slice = Array.prototype.slice; - module.exports = merge2; - function merge2() { - const streamsQueue = []; - const args = slice.call(arguments); - let merging = false; - let options = args[args.length - 1]; - if (options && !Array.isArray(options) && options.pipe == null) { - args.pop(); - } else { - options = {}; + static get unminifiable_name() { + return "GraphInterrupt"; } - const doEnd = options.end !== false; - const doPipeError = options.pipeError === true; - if (options.objectMode == null) { - options.objectMode = true; + }; + NodeInterrupt2 = class extends GraphInterrupt2 { + constructor(message, fields) { + super([{ value: message }], fields); + this.name = "NodeInterrupt"; } - if (options.highWaterMark == null) { - options.highWaterMark = 64 * 1024; + static get unminifiable_name() { + return "NodeInterrupt"; } - const mergedStream = PassThrough(options); - function addStream() { - for (let i = 0, len = arguments.length;i < len; i++) { - streamsQueue.push(pauseStreams(arguments[i], options)); - } - mergeStream(); - return this; + }; + ParentCommand2 = class extends GraphBubbleUp2 { + command; + constructor(command) { + super(); + this.name = "ParentCommand"; + this.command = command; } - function mergeStream() { - if (merging) { - return; - } - merging = true; - let streams = streamsQueue.shift(); - if (!streams) { - process.nextTick(endStream); - return; - } - if (!Array.isArray(streams)) { - streams = [streams]; - } - let pipesCount = streams.length + 1; - function next() { - if (--pipesCount > 0) { - return; - } - merging = false; - mergeStream(); - } - function pipe2(stream2) { - function onend() { - stream2.removeListener("merge2UnpipeEnd", onend); - stream2.removeListener("end", onend); - if (doPipeError) { - stream2.removeListener("error", onerror); - } - next(); - } - function onerror(err) { - mergedStream.emit("error", err); - } - if (stream2._readableState.endEmitted) { - return next(); - } - stream2.on("merge2UnpipeEnd", onend); - stream2.on("end", onend); - if (doPipeError) { - stream2.on("error", onerror); - } - stream2.pipe(mergedStream, { end: false }); - stream2.resume(); - } - for (let i = 0;i < streams.length; i++) { - pipe2(streams[i]); - } - next(); + static get unminifiable_name() { + return "ParentCommand"; } - function endStream() { - merging = false; - mergedStream.emit("queueDrain"); - if (doEnd) { - mergedStream.end(); - } + }; + EmptyInputError2 = class extends BaseLangGraphError2 { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyInputError"; } - mergedStream.setMaxListeners(0); - mergedStream.add = addStream; - mergedStream.on("unpipe", function(stream2) { - stream2.emit("merge2UnpipeEnd"); - }); - if (args.length) { - addStream.apply(null, args); + static get unminifiable_name() { + return "EmptyInputError"; } - return mergedStream; - } - function pauseStreams(streams, options) { - if (!Array.isArray(streams)) { - if (!streams._readableState && streams.pipe) { - streams = streams.pipe(PassThrough(options)); - } - if (!streams._readableState || !streams.pause || !streams.pipe) { - throw new Error("Only readable stream can be merged."); - } - streams.pause(); - } else { - for (let i = 0, len = streams.length;i < len; i++) { - streams[i] = pauseStreams(streams[i], options); - } + }; + EmptyChannelError2 = class extends BaseLangGraphError2 { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyChannelError"; } - return streams; - } -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/stream.js -var require_stream = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.merge = undefined; - var merge2 = require_merge2(); - function merge3(streams) { - const mergedStream = merge2(streams); - streams.forEach((stream2) => { - stream2.once("error", (error51) => mergedStream.emit("error", error51)); - }); - mergedStream.once("close", () => propagateCloseEventToSources(streams)); - mergedStream.once("end", () => propagateCloseEventToSources(streams)); - return mergedStream; - } - exports.merge = merge3; - function propagateCloseEventToSources(streams) { - streams.forEach((stream2) => stream2.emit("close")); - } -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/string.js -var require_string2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isEmpty = exports.isString = undefined; - function isString2(input) { - return typeof input === "string"; - } - exports.isString = isString2; - function isEmpty2(input) { - return input === ""; - } - exports.isEmpty = isEmpty2; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/index.js -var require_utils3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = undefined; - var array2 = require_array(); - exports.array = array2; - var errno = require_errno(); - exports.errno = errno; - var fs = require_fs(); - exports.fs = fs; - var path2 = require_path(); - exports.path = path2; - var pattern = require_pattern(); - exports.pattern = pattern; - var stream2 = require_stream(); - exports.stream = stream2; - var string4 = require_string2(); - exports.string = string4; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/managers/tasks.js -var require_tasks = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = undefined; - var utils = require_utils3(); - function generate(input, settings) { - const patterns = processPatterns(input, settings); - const ignore = processPatterns(settings.ignore, settings); - const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); - const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); - const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); - const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, false); - const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, true); - return staticTasks.concat(dynamicTasks); - } - exports.generate = generate; - function processPatterns(input, settings) { - let patterns = input; - if (settings.braceExpansion) { - patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + static get unminifiable_name() { + return "EmptyChannelError"; } - if (settings.baseNameMatch) { - patterns = patterns.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`); + }; + InvalidUpdateError2 = class extends BaseLangGraphError2 { + constructor(message, fields) { + super(message, fields); + this.name = "InvalidUpdateError"; } - return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); - } - function convertPatternsToTasks(positive, negative, dynamic) { - const tasks = []; - const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); - const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); - const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); - const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); - tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); - if ("." in insideCurrentDirectoryGroup) { - tasks.push(convertPatternGroupToTask(".", patternsInsideCurrentDirectory, negative, dynamic)); - } else { - tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + static get unminifiable_name() { + return "InvalidUpdateError"; } - return tasks; - } - exports.convertPatternsToTasks = convertPatternsToTasks; - function getPositivePatterns(patterns) { - return utils.pattern.getPositivePatterns(patterns); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/base.js +function isBaseChannel2(obj) { + return obj != null && obj.lg_is_channel === true; +} +function getOnlyChannels2(channels) { + if (channels[IS_ONLY_BASE_CHANNEL2] === true) + return channels; + const newChannels = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) + continue; + const value = channels[k]; + if (isBaseChannel2(value)) + newChannels[k] = value; } - exports.getPositivePatterns = getPositivePatterns; - function getNegativePatternsAsPositive(patterns, ignore) { - const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); - const positive = negative.map(utils.pattern.convertToPositivePattern); - return positive; + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL2]: true }); + return newChannels; +} +function emptyChannels2(channels, checkpoint) { + const filteredChannels = getOnlyChannels2(channels); + const newChannels = {}; + for (const k in filteredChannels) { + if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) + continue; + const channelValue = checkpoint.channel_values[k]; + newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); } - exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; - function groupPatternsByBaseDirectory(patterns) { - const group = {}; - return patterns.reduce((collection, pattern) => { - const base = utils.pattern.getBaseDirectory(pattern); - if (base in collection) { - collection[base].push(pattern); - } else { - collection[base] = [pattern]; + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL2]: true }); + return newChannels; +} +function createCheckpoint2(checkpoint, channels, step, options) { + let values; + if (channels === undefined) + values = checkpoint.channel_values; + else { + values = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) + continue; + try { + values[k] = channels[k].checkpoint(); + } catch (error90) { + if (error90.name === EmptyChannelError2.unminifiable_name) {} else + throw error90; } - return collection; - }, group); - } - exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; - function convertPatternGroupsToTasks(positive, negative, dynamic) { - return Object.keys(positive).map((base) => { - return convertPatternGroupToTask(base, positive[base], negative, dynamic); - }); + } } - exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; - function convertPatternGroupToTask(base, positive, negative, dynamic) { - return { - dynamic, - positive, - negative, - base, - patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) - }; + return { + v: 4, + id: options?.id ?? uuid63(step), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: values, + channel_versions: checkpoint.channel_versions, + versions_seen: checkpoint.versions_seen + }; +} +var BaseChannel2 = class { + ValueType; + UpdateType; + lg_is_channel = true; + consume() { + return false; } - exports.convertPatternGroupToTask = convertPatternGroupToTask; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/providers/async.js -var require_async = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.read = undefined; - function read(path2, settings, callback) { - settings.fs.lstat(path2, (lstatError, lstat) => { - if (lstatError !== null) { - callFailureCallback(callback, lstatError); - return; - } - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - callSuccessCallback(callback, lstat); - return; - } - settings.fs.stat(path2, (statError, stat4) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - callFailureCallback(callback, statError); - return; - } - callSuccessCallback(callback, lstat); - return; - } - if (settings.markSymbolicLink) { - stat4.isSymbolicLink = () => true; - } - callSuccessCallback(callback, stat4); - }); - }); + finish() { + return false; } - exports.read = read; - function callFailureCallback(callback, error51) { - callback(error51); + isAvailable() { + try { + this.get(); + return true; + } catch (error90) { + if (error90.name === EmptyChannelError2.unminifiable_name) + return false; + throw error90; + } } - function callSuccessCallback(callback, result) { - callback(null, result); + equals(other) { + return this === other; } +}, IS_ONLY_BASE_CHANNEL2; +var init_base16 = __esm(() => { + init_errors9(); + init_dist3(); + IS_ONLY_BASE_CHANNEL2 = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); }); -// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/providers/sync.js -var require_sync = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.read = undefined; - function read(path2, settings) { - const lstat = settings.fs.lstatSync(path2); - if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { - return lstat; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/binop.js +var isBinaryOperatorAggregate2 = (value) => { + return value != null && value.lc_graph_name === "BinaryOperatorAggregate"; +}, BinaryOperatorAggregate3; +var init_binop2 = __esm(() => { + init_constants5(); + init_errors9(); + init_base16(); + BinaryOperatorAggregate3 = class BinaryOperatorAggregate4 extends BaseChannel2 { + lc_graph_name = "BinaryOperatorAggregate"; + value; + operator; + initialValueFactory; + constructor(operator, initialValueFactory) { + super(); + this.operator = operator; + this.initialValueFactory = initialValueFactory; + this.value = initialValueFactory?.(); } - try { - const stat4 = settings.fs.statSync(path2); - if (settings.markSymbolicLink) { - stat4.isSymbolicLink = () => true; - } - return stat4; - } catch (error51) { - if (!settings.throwErrorOnBrokenSymbolicLink) { - return lstat; + fromCheckpoint(checkpoint) { + const empty = new BinaryOperatorAggregate4(this.operator, this.initialValueFactory); + if (typeof checkpoint !== "undefined") + empty.value = checkpoint; + return empty; + } + update(values) { + let newValues = values; + if (!newValues.length) + return false; + if (this.value === undefined) { + const first = newValues[0]; + const [isOverwrite, overwriteVal] = _getOverwriteValue2(first); + if (isOverwrite) + this.value = overwriteVal; + else + this.value = first; + newValues = newValues.slice(1); } - throw error51; + let seenOverwrite = false; + for (const incoming of newValues) + if (_isOverwriteValue2(incoming)) { + if (seenOverwrite) + throw new InvalidUpdateError2("Can receive only one Overwrite value per step."); + const [, val] = _getOverwriteValue2(incoming); + this.value = val; + seenOverwrite = true; + continue; + } else if (!seenOverwrite && this.value !== undefined) + this.value = this.operator(this.value, incoming); + return true; } - } - exports.read = read; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/adapters/fs.js -var require_fs2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = undefined; - var fs = __require("fs"); - exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync - }; - function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; + get() { + if (this.value === undefined) + throw new EmptyChannelError2; + return this.value; } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); - } - exports.createFileSystemAdapter = createFileSystemAdapter; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/settings.js -var require_settings = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var fs = require_fs2(); - - class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); - this.fs = fs.createFileSystemAdapter(this._options.fs); - this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + checkpoint() { + if (this.value === undefined) + throw new EmptyChannelError2; + return this.value; } - _getValue(option, value) { - return option !== null && option !== undefined ? option : value; + isAvailable() { + return this.value !== undefined; } - } - exports.default = Settings; + equals(other) { + if (this === other) + return true; + if (!isBinaryOperatorAggregate2(other)) + return false; + return this.operator === other.operator; + } + }; }); -// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/index.js -var require_out = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.statSync = exports.stat = exports.Settings = undefined; - var async = require_async(); - var sync = require_sync(); - var settings_1 = require_settings(); - exports.Settings = settings_1.default; - function stat4(path2, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === "function") { - async.read(path2, getSettings(), optionsOrSettingsOrCallback); - return; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/last_value.js +var LastValue3; +var init_last_value2 = __esm(() => { + init_errors9(); + init_base16(); + LastValue3 = class LastValue4 extends BaseChannel2 { + lc_graph_name = "LastValue"; + value = []; + constructor(initialValueFactory) { + super(); + this.initialValueFactory = initialValueFactory; + if (initialValueFactory) + this.value = [initialValueFactory()]; } - async.read(path2, getSettings(optionsOrSettingsOrCallback), callback); - } - exports.stat = stat4; - function statSync(path2, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync.read(path2, settings); - } - exports.statSync = statSync; - function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; + fromCheckpoint(checkpoint) { + const empty = new LastValue4(this.initialValueFactory); + if (typeof checkpoint !== "undefined") + empty.value = [checkpoint]; + return empty; } - return new settings_1.default(settingsOrOptions); - } -}); - -// ../../node_modules/.pnpm/queue-microtask@1.2.3/node_modules/queue-microtask/index.js -var require_queue_microtask = __commonJS((exports, module) => { - /*! queue-microtask. MIT License. Feross Aboukhadijeh */ - var promise2; - module.exports = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : global) : (cb) => (promise2 || (promise2 = Promise.resolve())).then(cb).catch((err) => setTimeout(() => { - throw err; - }, 0)); -}); - -// ../../node_modules/.pnpm/run-parallel@1.2.0/node_modules/run-parallel/index.js -var require_run_parallel = __commonJS((exports, module) => { - /*! run-parallel. MIT License. Feross Aboukhadijeh */ - module.exports = runParallel; - var queueMicrotask2 = require_queue_microtask(); - function runParallel(tasks, cb) { - let results, pending, keys; - let isSync = true; - if (Array.isArray(tasks)) { - results = []; - pending = tasks.length; - } else { - keys = Object.keys(tasks); - results = {}; - pending = keys.length; + update(values) { + if (values.length === 0) + return false; + if (values.length !== 1) + throw new InvalidUpdateError2("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this.value = [values[values.length - 1]]; + return true; } - function done(err) { - function end() { - if (cb) - cb(err, results); - cb = null; - } - if (isSync) - queueMicrotask2(end); - else - end(); + get() { + if (this.value.length === 0) + throw new EmptyChannelError2; + return this.value[0]; } - function each(i, err, result) { - results[i] = result; - if (--pending === 0 || err) { - done(err); - } + checkpoint() { + if (this.value.length === 0) + throw new EmptyChannelError2; + return this.value[0]; } - if (!pending) { - done(null); - } else if (keys) { - keys.forEach(function(key) { - tasks[key](function(err, result) { - each(key, err, result); - }); - }); - } else { - tasks.forEach(function(task2, i) { - task2(function(err, result) { - each(i, err, result); - }); - }); + isAvailable() { + return this.value.length !== 0; } - isSync = false; - } + }; }); -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/constants.js -var require_constants3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = undefined; - var NODE_PROCESS_VERSION_PARTS = process.versions.node.split("."); - if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { - throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); - } - var MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); - var MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); - var SUPPORTED_MAJOR_VERSION = 10; - var SUPPORTED_MINOR_VERSION = 10; - var IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; - var IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; - exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/utils/fs.js -var require_fs3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createDirentFromStats = undefined; - - class DirentFromStats { - constructor(name, stats) { - this.name = name; - this.isBlockDevice = stats.isBlockDevice.bind(stats); - this.isCharacterDevice = stats.isCharacterDevice.bind(stats); - this.isDirectory = stats.isDirectory.bind(stats); - this.isFIFO = stats.isFIFO.bind(stats); - this.isFile = stats.isFile.bind(stats); - this.isSocket = stats.isSocket.bind(stats); - this.isSymbolicLink = stats.isSymbolicLink.bind(stats); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/annotation.js +function getChannel2(reducer) { + if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) + return new BinaryOperatorAggregate3(reducer.reducer, reducer.default); + if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) + return new BinaryOperatorAggregate3(reducer.value, reducer.default); + return new LastValue3; +} +var AnnotationRoot2 = class { + lc_graph_name = "AnnotationRoot"; + spec; + constructor(s) { + this.spec = s; } - function createDirentFromStats(name, stats) { - return new DirentFromStats(name, stats); + static isInstance(value) { + return typeof value === "object" && value !== null && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot"; } - exports.createDirentFromStats = createDirentFromStats; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/utils/index.js -var require_utils4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fs = undefined; - var fs = require_fs3(); - exports.fs = fs; +}, Annotation2 = function(annotation) { + if (annotation) + return getChannel2(annotation); + else + return new LastValue3; +}; +var init_annotation3 = __esm(() => { + init_binop2(); + init_last_value2(); + Annotation2.Root = (sd) => new AnnotationRoot2(sd); }); -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/common.js -var require_common = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.joinPathSegments = undefined; - function joinPathSegments(a, b, separator) { - if (a.endsWith(separator)) { - return a + b; - } - return a + separator + b; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/utils/config.js +function propagateConfigurableToMetadata2(configurable, metadata) { + if (!configurable) + return metadata; + const result = metadata ?? {}; + for (const key of PROPAGATE_TO_METADATA2) { + if (key in result) + continue; + const value = configurable[key]; + if (value !== undefined) + result[key] = value; } - exports.joinPathSegments = joinPathSegments; + return result; +} +function ensureLangGraphConfig2(...configs) { + const empty = { + tags: [], + metadata: {}, + callbacks: undefined, + recursionLimit: DEFAULT_RECURSION_LIMIT2, + configurable: {} + }; + const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (implicitConfig !== undefined) { + for (const [k, v] of Object.entries(implicitConfig)) + if (v !== undefined) + if (COPIABLE_KEYS2.includes(k)) { + let copiedValue; + if (Array.isArray(v)) + copiedValue = [...v]; + else if (typeof v === "object") + if (k === "callbacks" && "copy" in v && typeof v.copy === "function") + copiedValue = v.copy(); + else + copiedValue = { ...v }; + else + copiedValue = v; + empty[k] = copiedValue; + } else + empty[k] = v; + } + for (const config3 of configs) { + if (config3 === undefined) + continue; + for (const [k, v] of Object.entries(config3)) + if (v !== undefined && CONFIG_KEYS2.includes(k)) + empty[k] = v; + } + empty.metadata = propagateConfigurableToMetadata2(empty.configurable, empty.metadata) ?? {}; + return empty; +} +function getStore2(config3) { + const runConfig = config3 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (runConfig === undefined) + throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(` +`)); + return runConfig?.store; +} +function getConfig2() { + return AsyncLocalStorageProviderSingleton2.getRunnableConfig(); +} +function getCurrentTaskInput2(config3) { + const runConfig = config3 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (runConfig === undefined) + throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(` +`)); + if (runConfig.configurable?.["__pregel_scratchpad"]?.currentTaskInput === undefined) + throw new Error("BUG: internal scratchpad not initialized."); + return runConfig.configurable[CONFIG_KEY_SCRATCHPAD2].currentTaskInput; +} +function recastCheckpointNamespace2(namespace) { + return namespace.split("|").filter((part) => !part.match(/^\d+$/)).map((part) => part.split(":")[0]).join("|"); +} +function getParentCheckpointNamespace2(namespace) { + const parts = namespace.split("|"); + while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) + parts.pop(); + return parts.slice(0, -1).join("|"); +} +var COPIABLE_KEYS2, CONFIG_KEYS2, DEFAULT_RECURSION_LIMIT2 = 25, PROPAGATE_TO_METADATA2; +var init_config3 = __esm(() => { + init_constants5(); + init_singletons(); + COPIABLE_KEYS2 = [ + "tags", + "metadata", + "callbacks", + "configurable" + ]; + CONFIG_KEYS2 = [ + "tags", + "metadata", + "callbacks", + "runName", + "maxConcurrency", + "recursionLimit", + "configurable", + "runId", + "outputKeys", + "streamMode", + "store", + "writer", + "interrupt", + "context", + "interruptBefore", + "interruptAfter", + "checkpointDuring", + "durability", + "signal", + "executionInfo", + "serverInfo" + ]; + PROPAGATE_TO_METADATA2 = new Set([ + "thread_id", + "checkpoint_id", + "checkpoint_ns", + "task_id", + "run_id", + "assistant_id", + "graph_id" + ]); }); -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/async.js -var require_async2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.readdir = exports.readdirWithFileTypes = exports.read = undefined; - var fsStat = require_out(); - var rpl = require_run_parallel(); - var constants_1 = require_constants3(); - var utils = require_utils4(); - var common = require_common(); - function read(directory, settings, callback) { - if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - readdirWithFileTypes(directory, settings, callback); - return; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/stream-channel.js +function isStreamChannel2(value) { + return StreamChannel3.isInstance(value); +} +var STREAM_CHANNEL_BRAND2, StreamChannel3; +var init_stream_channel2 = __esm(() => { + STREAM_CHANNEL_BRAND2 = Symbol.for("langgraph.stream_channel"); + StreamChannel3 = class StreamChannel4 { + [STREAM_CHANNEL_BRAND2] = true; + channelName; + #items = []; + #waiters = []; + #done = false; + #error; + #onPush; + constructor(name) { + this.channelName = name; } - readdir4(directory, settings, callback); - } - exports.read = read; - function readdirWithFileTypes(directory, settings, callback) { - settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { - if (readdirError !== null) { - callFailureCallback(callback, readdirError); - return; - } - const entries = dirents.map((dirent) => ({ - dirent, - name: dirent.name, - path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) - })); - if (!settings.followSymbolicLinks) { - callSuccessCallback(callback, entries); - return; - } - const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); - rpl(tasks, (rplError, rplEntries) => { - if (rplError !== null) { - callFailureCallback(callback, rplError); - return; - } - callSuccessCallback(callback, rplEntries); - }); - }); - } - exports.readdirWithFileTypes = readdirWithFileTypes; - function makeRplTaskEntry(entry, settings) { - return (done) => { - if (!entry.dirent.isSymbolicLink()) { - done(null, entry); - return; - } - settings.fs.stat(entry.path, (statError, stats) => { - if (statError !== null) { - if (settings.throwErrorOnBrokenSymbolicLink) { - done(statError); - return; + static local() { + return new StreamChannel4; + } + static remote(name) { + return new StreamChannel4(name); + } + static isInstance(value) { + return typeof value === "object" && value !== null && STREAM_CHANNEL_BRAND2 in value && value[STREAM_CHANNEL_BRAND2] === true; + } + push(item) { + this.#items.push(item); + this.#wake(); + this.#onPush?.(item); + } + iterate(startAt = 0) { + let cursor = startAt; + return { next: async () => { + while (true) { + if (cursor < this.#items.length) + return { + value: this.#items[cursor++], + done: false + }; + if (this.#done) { + if (this.#error) + throw this.#error; + return { + value: undefined, + done: true + }; } - done(null, entry); - return; + await new Promise((resolve2) => this.#waiters.push(resolve2)); } - entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); - done(null, entry); - }); - }; - } - function readdir4(directory, settings, callback) { - settings.fs.readdir(directory, (readdirError, names) => { - if (readdirError !== null) { - callFailureCallback(callback, readdirError); - return; - } - const tasks = names.map((name) => { - const path2 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); - return (done) => { - fsStat.stat(path2, settings.fsStatSettings, (error51, stats) => { - if (error51 !== null) { - done(error51); + } }; + } + toAsyncIterable(startAt = 0) { + return { [Symbol.asyncIterator]: () => this.iterate(startAt) }; + } + toEventStream(options = {}) { + const encoder2 = new TextEncoder; + const iterator = this.iterate(options.startAt); + const event = options.event ?? this.channelName; + const serialize2 = options.serialize ?? ((item) => JSON.stringify(item) ?? "null"); + return new ReadableStream({ + async pull(controller) { + try { + const next = await iterator.next(); + if (next.done) { + controller.close(); return; } - const entry = { - name, - path: path2, - dirent: utils.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - done(null, entry); - }); - }; - }); - rpl(tasks, (rplError, entries) => { - if (rplError !== null) { - callFailureCallback(callback, rplError); - return; - } - callSuccessCallback(callback, entries); - }); - }); - } - exports.readdir = readdir4; - function callFailureCallback(callback, error51) { - callback(error51); - } - function callSuccessCallback(callback, result) { - callback(null, result); - } -}); + const lines = []; + if (event != null) + lines.push(`event: ${event}`); + for (const line of serialize2(next.value).split(/\r\n|\r|\n/)) + lines.push(`data: ${line}`); + controller.enqueue(encoder2.encode(`${lines.join(` +`)} -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/sync.js -var require_sync2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.readdir = exports.readdirWithFileTypes = exports.read = undefined; - var fsStat = require_out(); - var constants_1 = require_constants3(); - var utils = require_utils4(); - var common = require_common(); - function read(directory, settings) { - if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { - return readdirWithFileTypes(directory, settings); - } - return readdir4(directory, settings); - } - exports.read = read; - function readdirWithFileTypes(directory, settings) { - const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); - return dirents.map((dirent) => { - const entry = { - dirent, - name: dirent.name, - path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) - }; - if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { - try { - const stats = settings.fs.statSync(entry.path); - entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); - } catch (error51) { - if (settings.throwErrorOnBrokenSymbolicLink) { - throw error51; +`)); + } catch (error90) { + controller.error(error90); } + }, + async cancel() { + await iterator.return?.(); } - } - return entry; - }); - } - exports.readdirWithFileTypes = readdirWithFileTypes; - function readdir4(directory, settings) { - const names = settings.fs.readdirSync(directory); - return names.map((name) => { - const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); - const stats = fsStat.statSync(entryPath, settings.fsStatSettings); - const entry = { - name, - path: entryPath, - dirent: utils.fs.createDirentFromStats(name, stats) - }; - if (settings.stats) { - entry.stats = stats; - } - return entry; - }); - } - exports.readdir = readdir4; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/adapters/fs.js -var require_fs4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = undefined; - var fs = __require("fs"); - exports.FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - stat: fs.stat, - lstatSync: fs.lstatSync, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync - }; - function createFileSystemAdapter(fsMethods) { - if (fsMethods === undefined) { - return exports.FILE_SYSTEM_ADAPTER; - } - return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); - } - exports.createFileSystemAdapter = createFileSystemAdapter; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/settings.js -var require_settings2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var path2 = __require("path"); - var fsStat = require_out(); - var fs = require_fs4(); - - class Settings { - constructor(_options = {}) { - this._options = _options; - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); - this.fs = fs.createFileSystemAdapter(this._options.fs); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path2.sep); - this.stats = this._getValue(this._options.stats, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); - this.fsStatSettings = new fsStat.Settings({ - followSymbolicLink: this.followSymbolicLinks, - fs: this.fs, - throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink }); } - _getValue(option, value) { - return option !== null && option !== undefined ? option : value; - } - } - exports.default = Settings; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/index.js -var require_out2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Settings = exports.scandirSync = exports.scandir = undefined; - var async = require_async2(); - var sync = require_sync2(); - var settings_1 = require_settings2(); - exports.Settings = settings_1.default; - function scandir(path2, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === "function") { - async.read(path2, getSettings(), optionsOrSettingsOrCallback); - return; - } - async.read(path2, getSettings(optionsOrSettingsOrCallback), callback); - } - exports.scandir = scandir; - function scandirSync(path2, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - return sync.read(path2, settings); - } - exports.scandirSync = scandirSync; - function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; - } - return new settings_1.default(settingsOrOptions); - } -}); - -// ../../node_modules/.pnpm/reusify@1.1.0/node_modules/reusify/reusify.js -var require_reusify = __commonJS((exports, module) => { - function reusify(Constructor) { - var head = new Constructor; - var tail = head; - function get() { - var current = head; - if (current.next) { - head = current.next; - } else { - head = new Constructor; - tail = head; - } - current.next = null; - return current; + get(index2) { + if (index2 < 0 || index2 >= this.#items.length) + throw new RangeError(`StreamChannel index ${index2} out of bounds (size=${this.#items.length})`); + return this.#items[index2]; } - function release(obj) { - tail.next = obj; - tail = obj; + get size() { + return this.#items.length; } - return { - get, - release - }; - } - module.exports = reusify; -}); - -// ../../node_modules/.pnpm/fastq@1.20.1/node_modules/fastq/queue.js -var require_queue = __commonJS((exports, module) => { - var reusify = require_reusify(); - function fastqueue(context2, worker, _concurrency) { - if (typeof context2 === "function") { - _concurrency = worker; - worker = context2; - context2 = null; + get done() { + return this.#done; } - if (!(_concurrency >= 1)) { - throw new Error("fastqueue concurrency must be equal to or greater than 1"); + close() { + this.#done = true; + this.#wake(); } - var cache2 = reusify(Task); - var queueHead = null; - var queueTail = null; - var _running = 0; - var errorHandler2 = null; - var self2 = { - push: push2, - drain: noop, - saturated: noop, - pause, - paused: false, - get concurrency() { - return _concurrency; - }, - set concurrency(value) { - if (!(value >= 1)) { - throw new Error("fastqueue concurrency must be equal to or greater than 1"); - } - _concurrency = value; - if (self2.paused) - return; - for (;queueHead && _running < _concurrency; ) { - _running++; - release(); - } - }, - running, - resume, - idle, - length, - getQueue: getQueue2, - unshift, - empty: noop, - kill, - killAndDrain, - error: error51, - abort - }; - return self2; - function running() { - return _running; + fail(err) { + this.#error = err; + this.#done = true; + this.#wake(); } - function pause() { - self2.paused = true; + _wire(fn) { + this.#onPush = fn; } - function length() { - var current = queueHead; - var counter = 0; - while (current) { - current = current.next; - counter++; - } - return counter; + _close() { + this.close(); } - function getQueue2() { - var current = queueHead; - var tasks = []; - while (current) { - tasks.push(current.value); - current = current.next; - } - return tasks; + _fail(err) { + this.fail(err); } - function resume() { - if (!self2.paused) - return; - self2.paused = false; - if (queueHead === null) { - _running++; - release(); - return; - } - for (;queueHead && _running < _concurrency; ) { - _running++; - release(); - } + [Symbol.asyncIterator]() { + return this.iterate(); } - function idle() { - return _running === 0 && self2.length() === 0; + #wake() { + const waiters = this.#waiters.splice(0); + for (const w of waiters) + w(); } - function push2(value, done) { - var current = cache2.get(); - current.context = context2; - current.release = release; - current.value = value; - current.callback = done || noop; - current.errorHandler = errorHandler2; - if (_running >= _concurrency || self2.paused) { - if (queueTail) { - queueTail.next = current; - queueTail = current; - } else { - queueHead = current; - queueTail = current; - self2.saturated(); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/convert.js +function unwrapMessagesPayload2(payload) { + if (!Array.isArray(payload) || payload.length !== 2) + return { data: payload }; + const [data, metadata] = payload; + if (metadata == null || typeof metadata !== "object") + return { data: payload }; + const record3 = metadata; + const node = typeof record3.langgraph_node === "string" ? record3.langgraph_node : undefined; + const runId = typeof record3.run_id === "string" ? record3.run_id : undefined; + return { + data: runId != null && data != null && typeof data === "object" ? { + ...data, + run_id: runId + } : data, + node + }; +} +function convertToProtocolEvent2({ namespace: ns3, mode, payload, seq, meta: meta3 }) { + const timestamp = Date.now(); + const base = { type: "event" }; + switch (mode) { + case "messages": { + const { data, node } = unwrapMessagesPayload2(payload); + return [{ + ...base, + seq, + method: "messages", + params: { + namespace: ns3, + timestamp, + ...node ? { node } : {}, + data } - } else { - _running++; - worker.call(context2, current.value, current.worked); - } + }]; } - function unshift(value, done) { - var current = cache2.get(); - current.context = context2; - current.release = release; - current.value = value; - current.callback = done || noop; - current.errorHandler = errorHandler2; - if (_running >= _concurrency || self2.paused) { - if (queueHead) { - current.next = queueHead; - queueHead = current; - } else { - queueHead = current; - queueTail = current; - self2.saturated(); + case "tools": + return [{ + ...base, + seq, + method: "tools", + params: { + namespace: ns3, + timestamp, + data: convertToolsPayload2(payload) } - } else { - _running++; - worker.call(context2, current.value, current.worked); - } - } - function release(holder) { - if (holder) { - cache2.release(holder); - } - var next = queueHead; - if (next && _running <= _concurrency) { - if (!self2.paused) { - if (queueTail === queueHead) { - queueTail = null; - } - queueHead = next.next; - next.next = null; - worker.call(context2, next.value, next.worked); - if (queueTail === null) { - self2.empty(); + }]; + case "values": { + const events = []; + if (meta3?.checkpoint != null) + events.push({ + ...base, + seq, + method: "checkpoints", + params: { + namespace: ns3, + timestamp, + data: meta3.checkpoint } - } else { - _running--; + }); + events.push({ + ...base, + seq: meta3?.checkpoint != null ? seq + 1 : seq, + method: "values", + params: { + namespace: ns3, + timestamp, + data: payload } - } else if (--_running === 0) { - self2.drain(); - } - } - function kill() { - queueHead = null; - queueTail = null; - self2.drain = noop; - } - function killAndDrain() { - queueHead = null; - queueTail = null; - self2.drain(); - self2.drain = noop; + }); + return events; } - function abort() { - var current = queueHead; - queueHead = null; - queueTail = null; - while (current) { - var next = current.next; - var callback = current.callback; - var errorHandler3 = current.errorHandler; - var val = current.value; - var context3 = current.context; - current.value = null; - current.callback = noop; - current.errorHandler = null; - if (errorHandler3) { - errorHandler3(new Error("abort"), val); + case "updates": { + const data = convertUpdatesPayload2(payload); + return [{ + ...base, + seq, + method: "updates", + params: { + namespace: ns3, + timestamp, + ...typeof data.node === "string" ? { node: data.node } : {}, + data } - callback.call(context3, new Error("abort")); - current.release(current); - current = next; - } - self2.drain = noop; + }]; } - function error51(handler) { - errorHandler2 = handler; + case "custom": { + const data = typeof payload === "object" && payload !== null && !Array.isArray(payload) && "name" in payload ? payload : { payload }; + return [{ + ...base, + seq, + method: "custom", + params: { + namespace: ns3, + timestamp, + data + } + }]; } + case "tasks": + return [{ + ...base, + seq, + method: "tasks", + params: { + namespace: ns3, + timestamp, + data: payload + } + }]; + default: + return []; } - function noop() {} - function Task() { - this.value = null; - this.callback = noop; - this.next = null; - this.release = noop; - this.context = null; - this.errorHandler = null; - var self2 = this; - this.worked = function worked(err, result) { - var callback = self2.callback; - var errorHandler2 = self2.errorHandler; - var val = self2.value; - self2.value = null; - self2.callback = noop; - if (self2.errorHandler) { - errorHandler2(err, val); - } - callback.call(self2.context, err, result); - self2.release(self2); +} +function convertToolsPayload2(payload) { + if (typeof payload !== "object" || payload === null) + return { + event: "tool-error", + tool_call_id: "", + message: "Unexpected tools payload shape" }; - } - function queueAsPromised(context2, worker, _concurrency) { - if (typeof context2 === "function") { - _concurrency = worker; - worker = context2; - context2 = null; - } - function asyncWrapper(arg, cb) { - worker.call(this, arg).then(function(res) { - cb(null, res); - }, cb); - } - var queue2 = fastqueue(context2, asyncWrapper, _concurrency); - var pushCb = queue2.push; - var unshiftCb = queue2.unshift; - queue2.push = push2; - queue2.unshift = unshift; - queue2.drained = drained; - return queue2; - function push2(value) { - var p = new Promise(function(resolve2, reject) { - pushCb(value, function(err, result) { - if (err) { - reject(err); - return; - } - resolve2(result); - }); - }); - p.catch(noop); - return p; - } - function unshift(value) { - var p = new Promise(function(resolve2, reject) { - unshiftCb(value, function(err, result) { - if (err) { - reject(err); - return; - } - resolve2(result); - }); - }); - p.catch(noop); - return p; - } - function drained() { - var p = new Promise(function(resolve2) { - process.nextTick(function() { - if (queue2.idle()) { - resolve2(); - } else { - var previousDrain = queue2.drain; - queue2.drain = function() { - if (typeof previousDrain === "function") - previousDrain(); - resolve2(); - queue2.drain = previousDrain; - }; - } - }); - }); - return p; + const p = payload; + const tool_call_id = String(p.toolCallId ?? ""); + switch (p.event) { + case "on_tool_start": + return { + event: "tool-started", + tool_call_id, + tool_name: String(p.name ?? "unknown"), + input: p.input + }; + case "on_tool_event": + return { + event: "tool-output-delta", + tool_call_id, + delta: typeof p.data === "string" ? p.data : JSON.stringify(p.data ?? "") + }; + case "on_tool_end": + return { + event: "tool-finished", + tool_call_id, + output: p.output + }; + case "on_tool_error": { + const err = p.error; + return { + event: "tool-error", + tool_call_id, + message: typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err ?? "unknown error") + }; } + default: + return { + event: "tool-error", + tool_call_id: "", + message: `Unknown tool event: ${String(p.event)}` + }; } - module.exports = fastqueue; - module.exports.promise = queueAsPromised; +} +function convertUpdatesPayload2(payload) { + if (typeof payload !== "object" || payload === null) + return { values: {} }; + const entries = Object.entries(payload); + if (entries.length === 0) + return { values: {} }; + const [node, values] = entries[0]; + return { + node, + values: typeof values === "object" && values !== null ? values : { value: values } + }; +} +var STREAM_EVENTS_V3_MODES2; +var init_convert2 = __esm(() => { + STREAM_EVENTS_V3_MODES2 = [ + "values", + "updates", + "messages", + "tools", + "custom", + "tasks" + ]; }); -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/common.js -var require_common2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = undefined; - function isFatalError(settings, error51) { - if (settings.errorFilter === null) { - return true; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/mux.js +function isPromiseLike2(value) { + return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; +} +async function pump2(source, mux) { + let seq = 0; + try { + for await (const chunk of source) { + const [ns3, mode, payload, meta3] = chunk; + if (mode === "values" && isInterrupted2(payload)) { + const interrupts = payload[INTERRUPT3]; + mux.markInterrupted(interrupts.map((i) => ({ + interruptId: i.id ?? "", + payload: i.value + }))); + } + const events = convertToProtocolEvent2({ + namespace: ns3, + mode, + payload, + seq, + meta: meta3 + }); + seq += events.length; + for (const event of events) + mux.push(ns3, event); } - return !settings.errorFilter(error51); - } - exports.isFatalError = isFatalError; - function isAppliedFilter(filter, value) { - return filter === null || filter(value); + } catch (err) { + mux.fail(err); + return; } - exports.isAppliedFilter = isAppliedFilter; - function replacePathSegmentSeparator(filepath, separator) { - return filepath.split(/[/\\]/).join(separator); + mux.close(); +} +function nsKey2(ns3) { + return ns3.join("\x00"); +} +function hasPrefix2(ns3, prefix) { + if (prefix.length > ns3.length) + return false; + for (let i = 0;i < prefix.length; i += 1) + if (ns3[i] !== prefix[i]) + return false; + return true; +} +var RESOLVE_VALUES2, REJECT_VALUES2, StreamMux2 = class { + _events = StreamChannel3.local(); + _discoveries = StreamChannel3.local(); + #nextEmitSeq = 0; + #closed = false; + #error; + #interrupted = false; + #currentNamespace = []; + #transformers = []; + #channels = []; + #streamMap = /* @__PURE__ */ new Map; + #latestValues = /* @__PURE__ */ new Map; + #interrupts = []; + #finalValues = []; + register(path2, stream2) { + this.#streamMap.set(nsKey2(path2), stream2); } - exports.replacePathSegmentSeparator = replacePathSegmentSeparator; - function joinPathSegments(a, b, separator) { - if (a === "") { - return b; - } - if (a.endsWith(separator)) { - return a + b; + addTransformer(transformer) { + const snapshot = this._events.size; + this.#transformers.push(transformer); + if (transformer.onRegister) + transformer.onRegister({ push: (ns3, event) => this.push(ns3, event) }); + for (let i = 0;i < snapshot; i += 1) + transformer.process(this._events.get(i)); + if (this.#closed) + if (this.#error !== undefined) + transformer.fail?.(this.#error); + else + transformer.finalize?.(); + } + wireChannels(projection) { + for (const [key, value] of Object.entries(projection)) { + if (isStreamChannel2(value)) { + this.#channels.push(value); + if (typeof value.channelName !== "string") + continue; + value._wire((item) => { + this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method: value.channelName, + params: { + namespace: this.#currentNamespace, + timestamp: Date.now(), + data: item + } + }); + }); + continue; + } + if (isPromiseLike2(value)) + this.#finalValues.push({ + name: key, + promise: Promise.resolve(value) + }); } - return a + separator + b; } - exports.joinPathSegments = joinPathSegments; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/reader.js -var require_reader = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var common = require_common2(); - - class Reader { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + push(ns3, event) { + if (event.method === "values") + this.#latestValues.set(nsKey2(ns3), event.params.data); + const outerNamespace = this.#currentNamespace; + this.#currentNamespace = ns3; + let keep = true; + for (const transformer of this.#transformers) + if (!transformer.process(event)) + keep = false; + this.#currentNamespace = outerNamespace; + if (keep) + this._events.push({ + ...event, + seq: this.#nextEmitSeq++ + }); + } + close() { + this.#closed = true; + for (const [key, values] of this.#latestValues.entries()) { + const ns3 = key ? key.split("\x00") : []; + this.#streamMap.get(nsKey2(ns3))?.[RESOLVE_VALUES2](values); + } + const finalizePromises = []; + for (const transformer of this.#transformers) { + const result = transformer.finalize?.(); + if (result != null && typeof result.then === "function") + finalizePromises.push(result); } + for (const channel of this.#channels) + channel._close(); + const finalValues = this.#finalValues; + if (finalValues.length === 0 && finalizePromises.length === 0) { + this._events.close(); + this._discoveries.close(); + } else + Promise.allSettled([...finalizePromises, ...finalValues.map(async ({ name, promise: promise3 }) => { + try { + const resolved = await promise3; + if (!this._events.done) + this._events.push({ + type: "event", + seq: this.#nextEmitSeq++, + method: "custom", + params: { + namespace: [], + timestamp: Date.now(), + data: { + name, + payload: resolved + } + } + }); + } catch {} + })]).then(() => { + this._events.close(); + this._discoveries.close(); + }); + for (const stream2 of this.#streamMap.values()) + stream2[RESOLVE_VALUES2](undefined); } - exports.default = Reader; + fail(err) { + this.#closed = true; + this.#error = err; + for (const transformer of this.#transformers) + transformer.fail?.(err); + for (const channel of this.#channels) + channel._fail(err); + this._events.fail(err); + this._discoveries.fail(err); + for (const stream2 of this.#streamMap.values()) + stream2[REJECT_VALUES2](err); + } + markInterrupted(interrupts) { + this.#interrupted = true; + this.#interrupts.push(...interrupts); + } + get interrupted() { + return this.#interrupted; + } + get interrupts() { + return this.#interrupts; + } + subscribeEvents(path2, startAt = 0) { + const base = this._events.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return result; + if (hasPrefix2(result.value.params.namespace, path2)) + return result; + } + } }; + } +}; +var init_mux2 = __esm(() => { + init_constants5(); + init_stream_channel2(); + init_convert2(); + RESOLVE_VALUES2 = Symbol("resolveValues"); + REJECT_VALUES2 = Symbol("rejectValues"); }); -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/async.js -var require_async3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var events_1 = __require("events"); - var fsScandir = require_out2(); - var fastq = require_queue(); - var common = require_common2(); - var reader_1 = require_reader(); - - class AsyncReader extends reader_1.default { - constructor(_root, _settings) { - super(_root, _settings); - this._settings = _settings; - this._scandir = fsScandir.scandir; - this._emitter = new events_1.EventEmitter; - this._queue = fastq(this._worker.bind(this), this._settings.concurrency); - this._isFatalError = false; - this._isDestroyed = false; - this._queue.drain = () => { - if (!this._isFatalError) { - this._emitter.emit("end"); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/transformers/lifecycle.js +function filterLifecycleEntries2(log, path2, startAt = 0) { + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + if (hasPrefix2(result.value.namespace, path2)) + return { + value: result.value, + done: false + }; + } + } }; + } }; +} +function defaultGuessGraphName2(ns3) { + if (ns3.length === 0) + return DEFAULT_ROOT_GRAPH_NAME2; + const last = ns3[ns3.length - 1]; + const colon = last.indexOf(":"); + return colon === -1 ? last : last.slice(0, colon); +} +function defaultSerializeError2(err) { + if (err instanceof Error) + return err.message; + if (typeof err === "string") + return err; + try { + return JSON.stringify(err); + } catch { + return String(err); + } +} +function isRecord2(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function extractCause2(data) { + if (!isRecord2(data)) + return; + if (data.event !== "started") + return; + const cause = data.cause; + if (!isRecord2(cause)) + return; + if (typeof cause.type !== "string") + return; + return cause; +} +function extractTaskResultCompletion2(data) { + if (!isRecord2(data)) + return; + if (!("result" in data)) + return; + if (typeof data.name !== "string") + return; + if (typeof data.id !== "string") + return; + if (data.name.startsWith("__")) + return; + return { + name: data.name, + id: data.id + }; +} +function createLifecycleTransformer2(options = {}) { + const rootGraphName = options.rootGraphName ?? DEFAULT_ROOT_GRAPH_NAME2; + const initialStatus = options.initialStatus ?? "running"; + const emitRootOnRegister = options.emitRootOnRegister ?? true; + const getGraphName = options.getGraphName ?? defaultGuessGraphName2; + const serializeError = options.serializeError ?? defaultSerializeError2; + const getTerminalStatusOverride = options.getTerminalStatusOverride; + const log = StreamChannel3.local(); + const namespaces = /* @__PURE__ */ new Map; + const namespaceCause = /* @__PURE__ */ new Map; + const pendingInterruptIds = /* @__PURE__ */ new Set; + const pendingCompletions = []; + let emitter; + let inSelfEmit = 0; + let finalized = false; + const resolveGraphName = (ns3) => ns3.length === 0 ? rootGraphName : getGraphName(ns3); + const emit = (ns3, status, extras) => { + const key = nsKey2(ns3); + let current = namespaces.get(key); + const graphName = current?.graphName ?? resolveGraphName(ns3); + if (current != null && current.status === status && current.graphName === graphName && extras?.error == null) + return; + if (current == null) { + current = { + namespace: ns3, + graphName, + status }; - } - read() { - this._isFatalError = false; - this._isDestroyed = false; - setImmediate(() => { - this._pushToQueue(this._root, this._settings.basePath); + namespaces.set(key, current); + } else + current.status = status; + const data = { + event: status, + graph_name: graphName, + ...extras?.cause != null ? { cause: extras.cause } : {}, + ...extras?.error != null ? { error: extras.error } : {} + }; + const timestamp = Date.now(); + log.push({ + namespace: ns3, + timestamp, + ...data + }); + if (ns3.length === 0 && !emitRootOnRegister) + return; + if (emitter == null) + return; + inSelfEmit += 1; + try { + emitter.push(ns3, { + type: "event", + seq: 0, + method: "lifecycle", + params: { + namespace: ns3, + timestamp, + data + } }); - return this._emitter; + } finally { + inSelfEmit -= 1; } - get isDestroyed() { - return this._isDestroyed; + }; + const trackNamespace = (ns3) => { + const key = nsKey2(ns3); + let rec = namespaces.get(key); + if (rec == null) { + rec = { + namespace: ns3, + graphName: resolveGraphName(ns3), + status: undefined + }; + namespaces.set(key, rec); } - destroy() { - if (this._isDestroyed) { - throw new Error("The reader is already destroyed"); - } - this._isDestroyed = true; - this._queue.killAndDrain(); + return rec; + }; + const flushPendingCompletions = () => { + if (pendingCompletions.length === 0) + return; + const toFlush = pendingCompletions.splice(0, pendingCompletions.length); + for (const completion of toFlush) { + const key = nsKey2(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") + continue; + emit(completion.namespace, "completed"); } - onEntry(callback) { - this._emitter.on("entry", callback); + }; + const enqueueCompletion = (completion) => { + const key = nsKey2(completion.namespace); + const rec = namespaces.get(key); + if (rec == null || rec.status !== "started") + return; + if (pendingCompletions.some((pending) => nsKey2(pending.namespace) === key)) + return; + pendingCompletions.push(completion); + }; + const removePendingNodeCompletions = (parent, node) => { + for (let index2 = pendingCompletions.length - 1;index2 >= 0; index2 -= 1) { + const pending = pendingCompletions[index2]; + if (pending.source.type !== "node") + continue; + if (pending.source.node !== node) + continue; + if (nsKey2(pending.source.parent) !== nsKey2(parent)) + continue; + pendingCompletions.splice(index2, 1); } - onError(callback) { - this._emitter.once("error", callback); + }; + const ensureStarted = (ns3) => { + for (let length = 1;length <= ns3.length; length += 1) { + const prefix = ns3.slice(0, length); + const key = nsKey2(prefix); + if (namespaces.has(key)) + continue; + trackNamespace(prefix); + const cause = namespaceCause.get(key); + emit(prefix, "started", cause != null ? { cause } : undefined); } - onEnd(callback) { - this._emitter.once("end", callback); + }; + const defaultTerminalStatus = () => pendingInterruptIds.size > 0 ? "interrupted" : "completed"; + const cascadeTerminalStatus = (status) => { + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) + continue; + if (rec.status !== "started") + continue; + emit(rec.namespace, status); } - _pushToQueue(directory, base) { - const queueItem = { directory, base }; - this._queue.push(queueItem, (error51) => { - if (error51 !== null) { - this._handleError(error51); - } - }); + emit([], status); + log.close(); + }; + const resolveTerminalStatusOverride = async () => { + if (getTerminalStatusOverride == null) + return defaultTerminalStatus(); + try { + return await getTerminalStatusOverride() ?? defaultTerminalStatus(); + } catch { + return defaultTerminalStatus(); } - _worker(item, done) { - this._scandir(item.directory, this._settings.fsScandirSettings, (error51, entries) => { - if (error51 !== null) { - done(error51, undefined); - return; - } - for (const entry of entries) { - this._handleEntry(entry, item.base); - } - done(null, undefined); - }); + }; + const findStartedChildForNode = (parentNamespace, node) => { + const prefix = `${node}:`; + for (const rec of namespaces.values()) { + if (rec.namespace.length !== parentNamespace.length + 1) + continue; + if (rec.status !== "started") + continue; + if (!hasPrefix2(rec.namespace, parentNamespace)) + continue; + const last = rec.namespace[rec.namespace.length - 1]; + if (last === node || last.startsWith(prefix)) + return rec.namespace; } - _handleError(error51) { - if (this._isDestroyed || !common.isFatalError(this._settings, error51)) { - return; + }; + const findStartedChildForTask = (parentNamespace, task2) => { + const namespace = [...parentNamespace, `${task2.name}:${task2.id}`]; + return namespaces.get(nsKey2(namespace))?.status === "started" ? namespace : undefined; + }; + return { + __native: true, + init() { + return { + _lifecycleLog: log, + lifecycle: filterLifecycleEntries2(log, [], 0) + }; + }, + onRegister(handle) { + emitter = handle; + trackNamespace([]); + if (emitRootOnRegister) + emit([], initialStatus); + }, + process(event) { + const ns3 = event.params.namespace; + if (inSelfEmit > 0) + return true; + const taskCompletion = event.method === "tasks" ? extractTaskResultCompletion2(event.params.data) : undefined; + if (taskCompletion != null) + removePendingNodeCompletions(ns3, taskCompletion.name); + flushPendingCompletions(); + if (event.method === "lifecycle") { + const cause = extractCause2(event.params.data); + if (cause != null) + namespaceCause.set(nsKey2(ns3), cause); + ensureStarted(ns3); + return false; } - this._isFatalError = true; - this._isDestroyed = true; - this._emitter.emit("error", error51); - } - _handleEntry(entry, base) { - if (this._isDestroyed || this._isFatalError) { - return; + ensureStarted(ns3); + if (event.method === "input" && isRecord2(event.params.data) && event.params.data.event === "requested") { + const id = event.params.data.id; + if (typeof id === "string") + pendingInterruptIds.add(id); } - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + if (taskCompletion != null) { + const childNamespace = findStartedChildForTask(ns3, taskCompletion); + if (childNamespace != null) + enqueueCompletion({ + namespace: childNamespace, + source: { type: "task" } + }); } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._emitEntry(entry); + if (event.method === "updates") { + const node = event.params.node; + if (typeof node === "string" && !node.startsWith("__")) { + const childNamespace = findStartedChildForNode(ns3, node); + if (childNamespace != null) + enqueueCompletion({ + namespace: childNamespace, + source: { + type: "node", + parent: ns3, + node + } + }); + } } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + return true; + }, + finalize() { + if (finalized) + return; + finalized = true; + flushPendingCompletions(); + if (getTerminalStatusOverride == null) { + cascadeTerminalStatus(defaultTerminalStatus()); + return; } - } - _emitEntry(entry) { - this._emitter.emit("entry", entry); - } - } - exports.default = AsyncReader; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/async.js -var require_async4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var async_1 = require_async3(); - - class AsyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1.default(this._root, this._settings); - this._storage = []; - } - read(callback) { - this._reader.onError((error51) => { - callFailureCallback(callback, error51); - }); - this._reader.onEntry((entry) => { - this._storage.push(entry); - }); - this._reader.onEnd(() => { - callSuccessCallback(callback, this._storage); + return resolveTerminalStatusOverride().then(cascadeTerminalStatus).catch((err) => { + log.fail(err); }); - this._reader.read(); + }, + fail(err) { + if (finalized) + return; + finalized = true; + const errorMessage = serializeError(err); + for (const rec of namespaces.values()) { + if (rec.namespace.length === 0) + continue; + if (rec.status !== "started") + continue; + emit(rec.namespace, "failed"); + } + emit([], "failed", { error: errorMessage }); + log.fail(err); } - } - exports.default = AsyncProvider; - function callFailureCallback(callback, error51) { - callback(error51); - } - function callSuccessCallback(callback, entries) { - callback(null, entries); - } + }; +} +var DEFAULT_ROOT_GRAPH_NAME2 = "root"; +var init_lifecycle2 = __esm(() => { + init_stream_channel2(); + init_mux2(); }); -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/stream.js -var require_stream2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var stream_1 = __require("stream"); - var async_1 = require_async3(); - - class StreamProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new async_1.default(this._root, this._settings); - this._stream = new stream_1.Readable({ - objectMode: true, - read: () => {}, - destroy: () => { - if (!this._reader.isDestroyed) { - this._reader.destroy(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/transformers/messages.js +function getMessageStreamKey2(data) { + const record3 = data; + if (typeof record3.run_id === "string") + return `run:${record3.run_id}`; + if (data.event === "message-start" && typeof record3.id === "string") + return `message:${record3.id}`; + return "__default__"; +} +function createMessagesTransformer2(path2, nodeFilter) { + const log = StreamChannel3.local(); + const active = /* @__PURE__ */ new Map; + const ignored = /* @__PURE__ */ new Set; + return { + init: () => ({ messages: log.toAsyncIterable() }), + process(event) { + if (event.method !== "messages") + return true; + if (!hasPrefix2(event.params.namespace, path2)) + return true; + if (event.params.namespace.length !== path2.length + 1) + return true; + if (nodeFilter !== undefined && event.params.node !== nodeFilter) + return true; + const data = event.params.data; + switch (data.event) { + case "message-start": { + const key = getMessageStreamKey2(data); + if (data.role === "tool") { + ignored.add(key); + break; } + const source = StreamChannel3.local(); + const stream2 = Object.assign(new ChatModelStream(source.toAsyncIterable()), { + namespace: event.params.namespace, + node: event.params.node + }); + active.set(key, { + source, + stream: stream2 + }); + source.push(data); + log.push(stream2); + break; } - }); - } - read() { - this._reader.onError((error51) => { - this._stream.emit("error", error51); - }); - this._reader.onEntry((entry) => { - this._stream.push(entry); - }); - this._reader.onEnd(() => { - this._stream.push(null); - }); - this._reader.read(); - return this._stream; - } - } - exports.default = StreamProvider; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/sync.js -var require_sync3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var fsScandir = require_out2(); - var common = require_common2(); - var reader_1 = require_reader(); - - class SyncReader extends reader_1.default { - constructor() { - super(...arguments); - this._scandir = fsScandir.scandirSync; - this._storage = []; - this._queue = new Set; - } - read() { - this._pushToQueue(this._root, this._settings.basePath); - this._handleQueue(); - return this._storage; - } - _pushToQueue(directory, base) { - this._queue.add({ directory, base }); - } - _handleQueue() { - for (const item of this._queue.values()) { - this._handleDirectory(item.directory, item.base); - } - } - _handleDirectory(directory, base) { - try { - const entries = this._scandir(directory, this._settings.fsScandirSettings); - for (const entry of entries) { - this._handleEntry(entry, base); + case "content-block-start": + case "content-block-delta": + case "content-block-finish": + if (ignored.has(getMessageStreamKey2(data))) + break; + active.get(getMessageStreamKey2(data))?.source.push(data); + break; + case "message-finish": { + const key = getMessageStreamKey2(data); + if (ignored.delete(key)) + break; + const stream2 = active.get(key); + if (stream2) { + stream2.source.push(data); + stream2.source.close(); + active.delete(key); + } + break; } - } catch (error51) { - this._handleError(error51); - } - } - _handleError(error51) { - if (!common.isFatalError(this._settings, error51)) { - return; - } - throw error51; - } - _handleEntry(entry, base) { - const fullpath = entry.path; - if (base !== undefined) { - entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + case "error": + if (ignored.has(getMessageStreamKey2(data))) + break; + active.get(getMessageStreamKey2(data))?.source.push(data); + break; } - if (common.isAppliedFilter(this._settings.entryFilter, entry)) { - this._pushToStorage(entry); + return true; + }, + finalize() { + for (const [key, stream2] of active) { + stream2.source.push({ event: "message-finish" }); + stream2.source.close(); + active.delete(key); } - if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { - this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + ignored.clear(); + log.close(); + }, + fail(err) { + for (const [key, stream2] of active) { + stream2.source.fail(err); + active.delete(key); } + ignored.clear(); + log.fail(err); } - _pushToStorage(entry) { - this._storage.push(entry); - } - } - exports.default = SyncReader; -}); - -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/sync.js -var require_sync4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var sync_1 = require_sync3(); - - class SyncProvider { - constructor(_root, _settings) { - this._root = _root; - this._settings = _settings; - this._reader = new sync_1.default(this._root, this._settings); - } - read() { - return this._reader.read(); - } - } - exports.default = SyncProvider; + }; +} +var init_messages5 = __esm(() => { + init_stream_channel2(); + init_mux2(); + init_stream2(); }); -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/settings.js -var require_settings3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var path2 = __require("path"); - var fsScandir = require_out2(); - - class Settings { - constructor(_options = {}) { - this._options = _options; - this.basePath = this._getValue(this._options.basePath, undefined); - this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); - this.deepFilter = this._getValue(this._options.deepFilter, null); - this.entryFilter = this._getValue(this._options.entryFilter, null); - this.errorFilter = this._getValue(this._options.errorFilter, null); - this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path2.sep); - this.fsScandirSettings = new fsScandir.Settings({ - followSymbolicLinks: this._options.followSymbolicLinks, - fs: this._options.fs, - pathSegmentSeparator: this._options.pathSegmentSeparator, - stats: this._options.stats, - throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/transformers/subgraphs.js +function filterSubgraphHandles2(log, path2, startAt = 0) { + const targetDepth = path2.length + 1; + return { [Symbol.asyncIterator]() { + const base = log.iterate(startAt); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + const { ns: ns3, stream: stream2 } = result.value; + if (ns3.length === targetDepth && hasPrefix2(ns3, path2)) + return { + value: stream2, + done: false + }; + } + } }; + } }; +} +function createSubgraphDiscoveryTransformer2(mux, options) { + const { createStream } = options; + const seen = /* @__PURE__ */ new Set; + return { + __native: true, + init() { + return { + _discoveries: mux._discoveries, + subgraphs: filterSubgraphHandles2(mux._discoveries, [], 0) + }; + }, + process(event) { + const ns3 = event.params.namespace; + if (ns3.length === 0) + return true; + const topNs = ns3.slice(0, 1); + const topKey = nsKey2(topNs); + if (seen.has(topKey)) + return true; + seen.add(topKey); + const stream2 = createStream(topNs, mux._discoveries.size, mux._events.size); + mux.register(topNs, stream2); + mux._discoveries.push({ + ns: topNs, + stream: stream2 }); + return true; } - _getValue(option, value) { - return option !== null && option !== undefined ? option : value; - } - } - exports.default = Settings; + }; +} +var init_subgraphs2 = __esm(() => { + init_mux2(); }); -// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/index.js -var require_out3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Settings = exports.walkStream = exports.walkSync = exports.walk = undefined; - var async_1 = require_async4(); - var stream_1 = require_stream2(); - var sync_1 = require_sync4(); - var settings_1 = require_settings3(); - exports.Settings = settings_1.default; - function walk(directory, optionsOrSettingsOrCallback, callback) { - if (typeof optionsOrSettingsOrCallback === "function") { - new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); - return; - } - new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); - } - exports.walk = walk; - function walkSync(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new sync_1.default(directory, settings); - return provider.read(); - } - exports.walkSync = walkSync; - function walkStream(directory, optionsOrSettings) { - const settings = getSettings(optionsOrSettings); - const provider = new stream_1.default(directory, settings); - return provider.read(); - } - exports.walkStream = walkStream; - function getSettings(settingsOrOptions = {}) { - if (settingsOrOptions instanceof settings_1.default) { - return settingsOrOptions; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/transformers/values.js +function createValuesTransformer2(path2) { + const valuesLog = StreamChannel3.local(); + return { + init: () => ({ _valuesLog: valuesLog }), + process(event) { + if (event.method !== "values") + return true; + if (event.params.namespace.length !== path2.length) + return true; + if (!hasPrefix2(event.params.namespace, path2)) + return true; + valuesLog.push(event.params.data); + return true; + }, + finalize() { + valuesLog.close(); + }, + fail(err) { + valuesLog.fail(err); } - return new settings_1.default(settingsOrOptions); - } + }; +} +var init_values3 = __esm(() => { + init_stream_channel2(); + init_mux2(); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/reader.js -var require_reader2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var path2 = __require("path"); - var fsStat = require_out(); - var utils = require_utils3(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/types.js +function isNativeTransformer2(t) { + return "__native" in t && t.__native === true; +} +var init_types11 = () => {}; - class Reader { - constructor(_settings) { - this._settings = _settings; - this._fsStatSettings = new fsStat.Settings({ - followSymbolicLink: this._settings.followSymbolicLinks, - fs: this._settings.fs, - throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/transformers/index.js +var init_transformers4 = __esm(() => { + init_lifecycle2(); + init_messages5(); + init_subgraphs2(); + init_values3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/run-stream.js +function createGraphRunStream2(source, transformers = [], optionsOrAbortController) { + const { abortController } = optionsOrAbortController instanceof AbortController ? { abortController: optionsOrAbortController } : optionsOrAbortController ?? {}; + const mux = new StreamMux2; + const lifecycleTransformer = createLifecycleTransformer2(); + const lifecycleProjection = lifecycleTransformer.init(); + const lifecycleLog = lifecycleProjection._lifecycleLog; + const subgraphDiscoveryTransformer = createSubgraphDiscoveryTransformer2(mux, { createStream: (path2, discoveryStart, eventStart) => { + const sub = new SubgraphRunStream2(path2, mux, discoveryStart, eventStart); + sub[SET_SUBGRAPHS_ITERABLE2](filterSubgraphHandles2(mux._discoveries, path2, discoveryStart)); + sub[SET_LIFECYCLE_ITERABLE2](filterLifecycleEntries2(lifecycleLog, path2, lifecycleLog.size)); + return sub; + } }); + const subgraphsProjection = subgraphDiscoveryTransformer.init(); + mux.addTransformer(subgraphDiscoveryTransformer); + mux.addTransformer(lifecycleTransformer); + const valuesTransformer = createValuesTransformer2([]); + const messagesTransformer = createMessagesTransformer2([]); + mux.addTransformer(valuesTransformer); + mux.addTransformer(messagesTransformer); + const extensions = {}; + const nativeProjections = []; + for (const factory of transformers) { + const transformer = factory(); + mux.addTransformer(transformer); + const projection = transformer.init(); + if (isNativeTransformer2(transformer)) + nativeProjections.push(projection); + else + Object.assign(extensions, projection); + if (typeof projection === "object" && projection !== null && !isNativeTransformer2(transformer)) + mux.wireChannels(projection); + } + const root = new GraphRunStream2([], mux, 0, 0, extensions, abortController); + for (const proj of nativeProjections) + Object.assign(root, proj); + const valuesProjection = valuesTransformer.init(); + root[SET_VALUES_LOG2](valuesProjection._valuesLog); + const messagesProjection = messagesTransformer.init(); + root[SET_MESSAGES_ITERABLE2](messagesProjection.messages); + root[SET_LIFECYCLE_ITERABLE2](lifecycleProjection.lifecycle); + root[SET_SUBGRAPHS_ITERABLE2](subgraphsProjection.subgraphs); + mux.register([], root); + pump2(source, mux).catch((err) => {}); + return root; +} +var SET_VALUES_LOG2, SET_MESSAGES_ITERABLE2, SET_LIFECYCLE_ITERABLE2, SET_SUBGRAPHS_ITERABLE2, EMPTY_ASYNC_ITERABLE2, GraphRunStream2, SubgraphRunStream2; +var init_run_stream2 = __esm(() => { + init_mux2(); + init_lifecycle2(); + init_messages5(); + init_subgraphs2(); + init_values3(); + init_transformers4(); + init_types11(); + SET_VALUES_LOG2 = Symbol("setValuesLog"); + SET_MESSAGES_ITERABLE2 = Symbol("setMessagesIterable"); + SET_LIFECYCLE_ITERABLE2 = Symbol("setLifecycleIterable"); + SET_SUBGRAPHS_ITERABLE2 = Symbol("setSubgraphsIterable"); + EMPTY_ASYNC_ITERABLE2 = { [Symbol.asyncIterator]() { + return { next: () => Promise.resolve({ + value: undefined, + done: true + }) }; + } }; + GraphRunStream2 = class { + path; + extensions; + _mux; + #eventStart; + #discoveryStart; + #abortController; + #resolveValuesFn; + #rejectValuesFn; + #valuesDone; + #valuesLog; + #messagesIterable; + #lifecycleIterable; + #subgraphsIterable; + constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + this.path = path2; + this._mux = mux; + this.#discoveryStart = discoveryStart; + this.#eventStart = eventStart; + this.extensions = extensions ?? {}; + this.#abortController = abortController ?? new AbortController; + this.#valuesDone = new Promise((resolve2, reject) => { + this.#resolveValuesFn = resolve2; + this.#rejectValuesFn = reject; }); + this.#valuesDone.catch(() => {}); } - _getFullEntryPath(filepath) { - return path2.resolve(this._settings.cwd, filepath); + [Symbol.asyncIterator]() { + return this._mux.subscribeEvents(this.path, this.#eventStart); } - _makeEntry(stats, pattern) { - const entry = { - name: pattern, - path: pattern, - dirent: utils.fs.createDirentFromStats(pattern, stats) + get subgraphs() { + if (this.#subgraphsIterable) + return this.#subgraphsIterable; + return filterSubgraphHandles2(this._mux._discoveries, this.path, this.#discoveryStart); + } + get values() { + const log = this.#valuesLog; + const done = this.#valuesDone; + const mux = this._mux; + const eventStart = this.#eventStart; + const path2 = this.path; + const iterable = log ? log.toAsyncIterable() : { [Symbol.asyncIterator]: () => { + const base = mux.subscribeEvents(path2, eventStart); + return { async next() { + while (true) { + const result = await base.next(); + if (result.done) + return { + value: undefined, + done: true + }; + if (result.value.method === "values" && result.value.params.namespace.length === path2.length) + return { + value: result.value.params.data, + done: false + }; + } + } }; + } }; + return { + [Symbol.asyncIterator]: () => iterable[Symbol.asyncIterator](), + then: done.then.bind(done) }; - if (this._settings.stats) { - entry.stats = stats; - } - return entry; } - _isFatalError(error51) { - return !utils.errno.isEnoentCodeError(error51) && !this._settings.suppressErrors; + get messages() { + if (this.#messagesIterable) + return this.#messagesIterable; + const transformer = createMessagesTransformer2(this.path); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + this.#messagesIterable = projection.messages; + return this.#messagesIterable; } - } - exports.default = Reader; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/stream.js -var require_stream3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var stream_1 = __require("stream"); - var fsStat = require_out(); - var fsWalk = require_out3(); - var reader_1 = require_reader2(); - - class ReaderStream extends reader_1.default { - constructor() { - super(...arguments); - this._walkStream = fsWalk.walkStream; - this._stat = fsStat.stat; + get lifecycle() { + return this.#lifecycleIterable ?? EMPTY_ASYNC_ITERABLE2; } - dynamic(root, options) { - return this._walkStream(root, options); + messagesFrom(node) { + const transformer = createMessagesTransformer2(this.path, node); + const projection = transformer.init(); + this._mux.addTransformer(transformer); + return projection.messages; } - static(patterns, options) { - const filepaths = patterns.map(this._getFullEntryPath, this); - const stream2 = new stream_1.PassThrough({ objectMode: true }); - stream2._write = (index2, _enc, done) => { - return this._getEntry(filepaths[index2], patterns[index2], options).then((entry) => { - if (entry !== null && options.entryFilter(entry)) { - stream2.push(entry); - } - if (index2 === filepaths.length - 1) { - stream2.end(); - } - done(); - }).catch(done); - }; - for (let i = 0;i < filepaths.length; i++) { - stream2.write(i); - } - return stream2; + get output() { + return this.#valuesDone; } - _getEntry(filepath, pattern, options) { - return this._getStat(filepath).then((stats) => this._makeEntry(stats, pattern)).catch((error51) => { - if (options.errorFilter(error51)) { - return null; - } - throw error51; - }); + get interrupted() { + return this._mux.interrupted; } - _getStat(filepath) { - return new Promise((resolve2, reject) => { - this._stat(filepath, this._fsStatSettings, (error51, stats) => { - return error51 === null ? resolve2(stats) : reject(error51); - }); - }); + get interrupts() { + return this._mux.interrupts; + } + abort(reason) { + this.#abortController.abort(reason); + } + get signal() { + return this.#abortController.signal; + } + [RESOLVE_VALUES2](values) { + this.#resolveValuesFn?.(values); + this.#resolveValuesFn = undefined; + } + [REJECT_VALUES2](err) { + this.#rejectValuesFn?.(err); + this.#rejectValuesFn = undefined; + } + [SET_VALUES_LOG2](log) { + this.#valuesLog = log; + } + [SET_MESSAGES_ITERABLE2](iterable) { + this.#messagesIterable = iterable; + } + [SET_LIFECYCLE_ITERABLE2](iterable) { + this.#lifecycleIterable = iterable; + } + [SET_SUBGRAPHS_ITERABLE2](iterable) { + this.#subgraphsIterable = iterable; + } + }; + SubgraphRunStream2 = class extends GraphRunStream2 { + name; + index; + constructor(path2, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { + super(path2, mux, discoveryStart, eventStart, extensions, abortController); + const lastSegment = path2[path2.length - 1] ?? ""; + const colonIdx = lastSegment.lastIndexOf(":"); + if (colonIdx >= 0) { + this.name = lastSegment.slice(0, colonIdx); + const suffix = lastSegment.slice(colonIdx + 1); + this.index = /^\d+$/.test(suffix) ? Number(suffix) : 0; + } else { + this.name = lastSegment; + this.index = 0; + } } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/stream/index.js +var init_stream7 = __esm(() => { + init_stream_channel2(); + init_convert2(); + init_mux2(); + init_lifecycle2(); + init_messages5(); + init_subgraphs2(); + init_values3(); + init_transformers4(); + init_types11(); + init_run_stream2(); + init_stream2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/hash.js +function assert5(a) { + if (!a) + throw new Error("Assert failed"); +} +function bswap643(a) { + const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); + scratchbuf.setBigUint64(0, a, true); + return scratchbuf.getBigUint64(0, false); +} +function bswap323(input) { + let a = input; + a = (a & n3(65535)) << n3(16) | (a & n3(4294901760)) >> n3(16); + a = (a & n3(16711935)) << n3(8) | (a & n3(4278255360)) >> n3(8); + return a; +} +function XXH_mult32to643(a, b) { + return (a & mask323) * (b & mask323) & mask643; +} +function rotl323(a, b) { + return (a << b | a >> n3(32) - b) & mask323; +} +function XXH3_accumulate_5123(acc, dataView, keyView) { + for (let i = 0;i < ACC_NB3; i += 1) { + const data_val = dataView.getBigUint64(i * 8, true); + const data_key = data_val ^ keyView.getBigUint64(i * 8, true); + acc[i ^ 1] += data_val; + acc[i] += XXH_mult32to643(data_key, data_key >> n3(32)); } - exports.default = ReaderStream; + return acc; +} +function XXH3_accumulate3(acc, dataView, keyView, nbStripes) { + for (let n4 = 0;n4 < nbStripes; n4 += 1) + XXH3_accumulate_5123(acc, view2(dataView, n4 * STRIPE_LEN3), view2(keyView, n4 * 8)); + return acc; +} +function XXH3_scrambleAcc3(acc, key) { + for (let i = 0;i < ACC_NB3; i += 1) { + const key64 = key.getBigUint64(i * 8, true); + let acc64 = acc[i]; + acc64 = xorshift643(acc64, n3(47)); + acc64 ^= key64; + acc64 *= PRIME32_13; + acc[i] = acc64 & mask643; + } + return acc; +} +function XXH3_mix2Accs3(acc, key) { + return XXH3_mul128_fold643(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U643, true)); +} +function XXH3_mergeAccs3(acc, key, start) { + let result64 = start; + result64 += XXH3_mix2Accs3(acc.slice(0), view2(key, 0 * _U323)); + result64 += XXH3_mix2Accs3(acc.slice(2), view2(key, 4 * _U323)); + result64 += XXH3_mix2Accs3(acc.slice(4), view2(key, 8 * _U323)); + result64 += XXH3_mix2Accs3(acc.slice(6), view2(key, 12 * _U323)); + return XXH3_avalanche3(result64 & mask643); +} +function XXH3_hashLong3(input, data, secret, f_acc, f_scramble) { + let acc = input; + const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN3) / 8); + const block_len = STRIPE_LEN3 * nbStripesPerBlock; + const nb_blocks = Math.floor((data.byteLength - 1) / block_len); + for (let n4 = 0;n4 < nb_blocks; n4 += 1) { + acc = XXH3_accumulate3(acc, view2(data, n4 * block_len), secret, nbStripesPerBlock); + acc = f_scramble(acc, view2(secret, secret.byteLength - STRIPE_LEN3)); + } + { + const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN3); + acc = XXH3_accumulate3(acc, view2(data, nb_blocks * block_len), secret, nbStripes); + acc = f_acc(acc, view2(data, data.byteLength - STRIPE_LEN3), view2(secret, secret.byteLength - STRIPE_LEN3 - 7)); + } + return acc; +} +function XXH3_hashLong_128b3(data, secret) { + let acc = new BigUint64Array([ + PRIME32_33, + PRIME64_13, + PRIME64_23, + PRIME64_33, + PRIME64_43, + PRIME32_23, + PRIME64_53, + PRIME32_13 + ]); + assert5(data.byteLength > 128); + acc = XXH3_hashLong3(acc, data, secret, XXH3_accumulate_5123, XXH3_scrambleAcc3); + assert5(acc.length * 8 === 64); + { + const low64 = XXH3_mergeAccs3(acc, view2(secret, 11), n3(data.byteLength) * PRIME64_13 & mask643); + return XXH3_mergeAccs3(acc, view2(secret, secret.byteLength - STRIPE_LEN3 - 11), ~(n3(data.byteLength) * PRIME64_23) & mask643) << n3(64) | low64; + } +} +function XXH3_mul128_fold643(a, b) { + const lll = a * b & mask1283; + return lll & mask643 ^ lll >> n3(64); +} +function XXH3_mix16B3(dataView, keyView, seed) { + return XXH3_mul128_fold643((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask643, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask643); +} +function XXH3_mix32B3(acc, data1, data2, key, seed) { + let accl = acc & mask643; + let acch = acc >> n3(64) & mask643; + accl += XXH3_mix16B3(data1, key, seed); + accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); + accl &= mask643; + acch += XXH3_mix16B3(data2, view2(key, 16), seed); + acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); + acch &= mask643; + return acch << n3(64) | accl; +} +function XXH3_avalanche3(input) { + let h64 = input; + h64 ^= h64 >> n3(37); + h64 *= PRIME_MX13; + h64 &= mask643; + h64 ^= h64 >> n3(32); + return h64; +} +function XXH3_avalanche643(input) { + let h64 = input; + h64 ^= h64 >> n3(33); + h64 *= PRIME64_23; + h64 &= mask643; + h64 ^= h64 >> n3(29); + h64 *= PRIME64_33; + h64 &= mask643; + h64 ^= h64 >> n3(32); + return h64; +} +function XXH3_len_1to3_128b3(data, key32, seed) { + const len = data.byteLength; + assert5(len > 0 && len <= 3); + const combined = n3(data.getUint8(len - 1)) | n3(len << 8) | n3(data.getUint8(0) << 16) | n3(data.getUint8(len >> 1) << 24); + const low = (combined ^ (n3(key32.getUint32(0, true)) ^ n3(key32.getUint32(4, true))) + seed) & mask643; + const bhigh = (n3(key32.getUint32(8, true)) ^ n3(key32.getUint32(12, true))) - seed; + return (XXH3_avalanche643((rotl323(bswap323(combined), n3(13)) ^ bhigh) & mask643) & mask643) << n3(64) | XXH3_avalanche643(low); +} +function xorshift643(b, shift) { + return b ^ b >> shift; +} +function XXH3_len_4to8_128b3(data, key32, seed) { + const len = data.byteLength; + assert5(len >= 4 && len <= 8); + { + const l1 = data.getUint32(0, true); + const l2 = data.getUint32(len - 4, true); + let m128 = ((n3(l1) | n3(l2) << n3(32)) ^ (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask643) * (PRIME64_13 + (n3(len) << n3(2))) & mask1283; + m128 += (m128 & mask643) << n3(65); + m128 &= mask1283; + m128 ^= m128 >> n3(67); + return xorshift643(xorshift643(m128 & mask643, n3(35)) * PRIME_MX23 & mask643, n3(28)) | XXH3_avalanche3(m128 >> n3(64)) << n3(64); + } +} +function XXH3_len_9to16_128b3(data, key64, seed) { + const len = data.byteLength; + assert5(len >= 9 && len <= 16); + { + const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask643; + const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask643; + const ll1 = data.getBigUint64(0, true); + let ll2 = data.getBigUint64(len - 8, true); + let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_13; + const m128_l = (m128 & mask643) + (n3(len - 1) << n3(54)); + m128 = m128 & (mask1283 ^ mask643) | m128_l; + ll2 ^= bitfliph; + m128 += ll2 + (ll2 & mask323) * (PRIME32_23 - n3(1)) << n3(64); + m128 &= mask1283; + m128 ^= bswap643(m128 >> n3(64)); + let h128 = (m128 & mask643) * PRIME64_23; + h128 += (m128 >> n3(64)) * PRIME64_23 << n3(64); + h128 &= mask1283; + return XXH3_avalanche3(h128 & mask643) | XXH3_avalanche3(h128 >> n3(64)) << n3(64); + } +} +function XXH3_len_0to16_128b3(data, seed) { + const len = data.byteLength; + assert5(len <= 16); + if (len > 8) + return XXH3_len_9to16_128b3(data, kkey3, seed); + if (len >= 4) + return XXH3_len_4to8_128b3(data, kkey3, seed); + if (len > 0) + return XXH3_len_1to3_128b3(data, kkey3, seed); + return XXH3_avalanche643(seed ^ kkey3.getBigUint64(64, true) ^ kkey3.getBigUint64(72, true)) | XXH3_avalanche643(seed ^ kkey3.getBigUint64(80, true) ^ kkey3.getBigUint64(88, true)) << n3(64); +} +function inv643(x) { + return ~x + n3(1) & mask643; +} +function XXH3_len_17to128_128b3(data, secret, seed) { + let acc = n3(data.byteLength) * PRIME64_13 & mask643; + let i = n3(data.byteLength - 1) / n3(32); + while (i >= 0) { + const ni = Number(i); + acc = XXH3_mix32B3(acc, view2(data, 16 * ni), view2(data, data.byteLength - 16 * (ni + 1)), view2(secret, 32 * ni), seed); + i -= n3(1); + } + let h128l = acc + (acc >> n3(64)) & mask643; + h128l = XXH3_avalanche3(h128l); + let h128h = (acc & mask643) * PRIME64_13 + (acc >> n3(64)) * PRIME64_43 + (n3(data.byteLength) - seed & mask643) * PRIME64_23; + h128h &= mask643; + h128h = inv643(XXH3_avalanche3(h128h)); + return h128l | h128h << n3(64); +} +function XXH3_len_129to240_128b3(data, secret, seed) { + let acc = n3(data.byteLength) * PRIME64_13 & mask643; + for (let i = 32;i < 160; i += 32) + acc = XXH3_mix32B3(acc, view2(data, i - 32), view2(data, i - 16), view2(secret, i - 32), seed); + acc = XXH3_avalanche3(acc & mask643) | XXH3_avalanche3(acc >> n3(64)) << n3(64); + for (let i = 160;i <= data.byteLength; i += 32) + acc = XXH3_mix32B3(acc, view2(data, i - 32), view2(data, i - 16), view2(secret, 3 + i - 160), seed); + acc = XXH3_mix32B3(acc, view2(data, data.byteLength - 16), view2(data, data.byteLength - 32), view2(secret, 103), inv643(seed)); + let h128l = acc + (acc >> n3(64)) & mask643; + h128l = XXH3_avalanche3(h128l); + let h128h = (acc & mask643) * PRIME64_13 + (acc >> n3(64)) * PRIME64_43 + (n3(data.byteLength) - seed & mask643) * PRIME64_23; + h128h &= mask643; + h128h = inv643(XXH3_avalanche3(h128h)); + return h128l | h128h << n3(64); +} +function XXH32(input, seed = n3(0)) { + const encoder2 = new TextEncoder; + const data = view2(typeof input === "string" ? encoder2.encode(input) : input); + const len = data.byteLength; + const hexDigest = (data2) => data2.toString(16).padStart(32, "0"); + if (len <= 16) + return hexDigest(XXH3_len_0to16_128b3(data, seed)); + if (len <= 128) + return hexDigest(XXH3_len_17to128_128b3(data, kkey3, seed)); + if (len <= 240) + return hexDigest(XXH3_len_129to240_128b3(data, kkey3, seed)); + return hexDigest(XXH3_hashLong_128b3(data, kkey3)); +} +function isXXH32(value) { + return /^[0-9a-f]{32}$/.test(value); +} +var n3 = (n4) => BigInt(n4), view2 = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset), PRIME32_13, PRIME32_23, PRIME32_33, PRIME64_13, PRIME64_23, PRIME64_33, PRIME64_43, PRIME64_53, PRIME_MX13, PRIME_MX23, hexToUint8Array3 = (hex3) => { + const strLen = hex3.length; + if (strLen % 2 !== 0) + throw new Error("String should have an even number of characters"); + const maxLength = strLen / 2; + const bytes = new Uint8Array(maxLength); + let read = 0; + let write = 0; + while (write < maxLength) { + const slice = hex3.slice(read, read += 2); + bytes[write] = Number.parseInt(slice, 16); + write += 1; + } + return view2(bytes); +}, kkey3, mask1283, mask643, mask323, STRIPE_LEN3 = 64, ACC_NB3, _U643 = 8, _U323 = 4; +var init_hash4 = __esm(() => { + PRIME32_13 = n3("0x9E3779B1"); + PRIME32_23 = n3("0x85EBCA77"); + PRIME32_33 = n3("0xC2B2AE3D"); + PRIME64_13 = n3("0x9E3779B185EBCA87"); + PRIME64_23 = n3("0xC2B2AE3D27D4EB4F"); + PRIME64_33 = n3("0x165667B19E3779F9"); + PRIME64_43 = n3("0x85EBCA77C2B2AE63"); + PRIME64_53 = n3("0x27D4EB2F165667C5"); + PRIME_MX13 = n3("0x165667919E3779F9"); + PRIME_MX23 = n3("0x9FB21C651E98DF25"); + kkey3 = hexToUint8Array3("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); + mask1283 = (n3(1) << n3(128)) - n3(1); + mask643 = (n3(1) << n3(64)) - n3(1); + mask323 = (n3(1) << n3(32)) - n3(1); + ACC_NB3 = STRIPE_LEN3 / 8; }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/async.js -var require_async5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var fsWalk = require_out3(); - var reader_1 = require_reader2(); - var stream_1 = require_stream3(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/interrupt.js +function interrupt2(value) { + const config3 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); + if (!config3) + throw new Error("Called interrupt() outside the context of a graph."); + const conf = config3.configurable; + if (!conf) + throw new Error("No configurable found in config"); + if (!conf["__pregel_checkpointer"]) + throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const scratchpad = conf[CONFIG_KEY_SCRATCHPAD2]; + scratchpad.interruptCounter += 1; + const idx = scratchpad.interruptCounter; + if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { + conf[CONFIG_KEY_SEND2]?.([[RESUME3, scratchpad.resume]]); + return scratchpad.resume[idx]; + } + if (scratchpad.nullResume !== undefined) { + if (scratchpad.resume.length !== idx) + throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); + const v = scratchpad.consumeNullResume(); + scratchpad.resume.push(v); + conf[CONFIG_KEY_SEND2]?.([[RESUME3, scratchpad.resume]]); + return v; + } + const ns3 = conf[CONFIG_KEY_CHECKPOINT_NS2]?.split("|"); + throw new GraphInterrupt2([{ + id: ns3 ? XXH32(ns3.join("|")) : undefined, + value + }]); +} +var init_interrupt2 = __esm(() => { + init_constants5(); + init_errors9(); + init_hash4(); + init_singletons(); +}); - class ReaderAsync extends reader_1.default { - constructor() { - super(...arguments); - this._walkAsync = fsWalk.walk; - this._readerStream = new stream_1.default(this._settings); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/utils.js +function* prefixGenerator2(generator, prefix) { + if (prefix === undefined) + yield* generator; + else + for (const value of generator) + yield [prefix, value]; +} +async function gatherIterator2(i) { + const out = []; + for await (const item of await i) + out.push(item); + return out; +} +function gatherIteratorSync2(i) { + const out = []; + for (const item of i) + out.push(item); + return out; +} +function patchConfigurable3(config3, patch) { + if (!config3) + return { configurable: patch }; + else if (!("configurable" in config3)) + return { + ...config3, + configurable: patch + }; + else + return { + ...config3, + configurable: { + ...config3.configurable, + ...patch + } + }; +} +function isAsyncGeneratorFunction2(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; +} +function isGeneratorFunction2(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; +} +var RunnableCallable3; +var init_utils14 = __esm(() => { + init_config3(); + init_singletons(); + init_runnables(); + RunnableCallable3 = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : undefined; + this.trace = fields.trace ?? this.trace; + this.recurse = fields.recurse ?? this.recurse; } - dynamic(root, options) { + async _tracedInvoke(input, config3, runManager) { return new Promise((resolve2, reject) => { - this._walkAsync(root, options, (error51, entries) => { - if (error51 === null) { - resolve2(entries); - } else { - reject(error51); + const childConfig = patchConfig(config3, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { + try { + resolve2(await this.func(input, childConfig)); + } catch (e) { + reject(e); } }); }); } - async static(patterns, options) { - const entries = []; - const stream2 = this._readerStream.static(patterns, options); - return new Promise((resolve2, reject) => { - stream2.once("error", reject); - stream2.on("data", (entry) => entries.push(entry)); - stream2.once("end", () => resolve2(entries)); - }); + async invoke(input, options) { + let returnValue; + const config3 = ensureLangGraphConfig2(options); + const mergedConfig = mergeConfigs(this.config, config3); + if (this.trace) + returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); + else + returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) + return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + return returnValue; } - } - exports.default = ReaderAsync; + }; }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/matchers/matcher.js -var require_matcher = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var utils = require_utils3(); - - class Matcher { - constructor(_patterns, _settings, _micromatchOptions) { - this._patterns = _patterns; - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this._storage = []; - this._fillStorage(); - } - _fillStorage() { - for (const pattern of this._patterns) { - const segments = this._getPatternSegments(pattern); - const sections = this._splitSegmentsIntoSections(segments); - this._storage.push({ - complete: sections.length <= 1, - pattern, - segments, - sections - }); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/write.js +function _isSkipWrite2(x) { + return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== undefined; +} +function _isPassthrough2(x) { + return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== undefined; +} +function _isChannelWriteEntry2(x) { + return x !== undefined && typeof x.channel === "string"; +} +function _isChannelWriteTupleEntry2(x) { + return x !== undefined && !_isChannelWriteEntry2(x) && Runnable.isRunnable(x.mapper); +} +var PASSTHROUGH2, IS_WRITER2, ChannelWrite3; +var init_write2 = __esm(() => { + init_constants5(); + init_errors9(); + init_utils14(); + init_runnables(); + PASSTHROUGH2 = { [Symbol.for("LG_PASSTHROUGH")]: true }; + IS_WRITER2 = Symbol("IS_WRITER"); + ChannelWrite3 = class ChannelWrite4 extends RunnableCallable3 { + writes; + constructor(writes, tags) { + const name = `ChannelWrite<${writes.map((packet) => { + if (_isSend2(packet)) + return packet.node; + else if ("channel" in packet) + return packet.channel; + return "..."; + }).join(",")}>`; + super({ + writes, + name, + tags, + trace: false, + func: async (input, config3) => { + return this._write(input, config3 ?? {}); + } + }); + this.writes = writes; } - _getPatternSegments(pattern) { - const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); - return parts.map((part) => { - const dynamic = utils.pattern.isDynamicPattern(part, this._settings); - if (!dynamic) { + async _write(input, config3) { + const writes = this.writes.map((write) => { + if (_isChannelWriteTupleEntry2(write) && _isPassthrough2(write.value)) return { - dynamic: false, - pattern: part + mapper: write.mapper, + value: input }; - } - return { - dynamic: true, - pattern: part, - patternRe: utils.pattern.makeRe(part, this._micromatchOptions) - }; + else if (_isChannelWriteEntry2(write) && _isPassthrough2(write.value)) + return { + channel: write.channel, + value: input, + skipNone: write.skipNone, + mapper: write.mapper + }; + else + return write; }); + await ChannelWrite4.doWrite(config3, writes); + return input; } - _splitSegmentsIntoSections(segments) { - return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); - } - } - exports.default = Matcher; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/matchers/partial.js -var require_partial = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var matcher_1 = require_matcher(); - - class PartialMatcher extends matcher_1.default { - match(filepath) { - const parts = filepath.split("/"); - const levels = parts.length; - const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); - for (const pattern of patterns) { - const section = pattern.sections[0]; - if (!pattern.complete && levels > section.length) { - return true; + static async doWrite(config3, writes) { + for (const w of writes) { + if (_isChannelWriteEntry2(w)) { + if (w.channel === "__pregel_tasks") + throw new InvalidUpdateError2("Cannot write to the reserved channel TASKS"); + if (_isPassthrough2(w.value)) + throw new InvalidUpdateError2("PASSTHROUGH value must be replaced"); } - const match2 = parts.every((part, index2) => { - const segment = pattern.segments[index2]; - if (segment.dynamic && segment.patternRe.test(part)) { - return true; - } - if (!segment.dynamic && segment.pattern === part) { - return true; - } - return false; - }); - if (match2) { - return true; + if (_isChannelWriteTupleEntry2(w)) { + if (_isPassthrough2(w.value)) + throw new InvalidUpdateError2("PASSTHROUGH value must be replaced"); } } - return false; - } - } - exports.default = PartialMatcher; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/deep.js -var require_deep = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var utils = require_utils3(); - var partial_1 = require_partial(); - - class DeepFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - } - getFilter(basePath, positive, negative) { - const matcher = this._getMatcher(positive); - const negativeRe = this._getNegativePatternsRe(negative); - return (entry) => this._filter(basePath, entry, matcher, negativeRe); - } - _getMatcher(patterns) { - return new partial_1.default(patterns, this._settings, this._micromatchOptions); - } - _getNegativePatternsRe(patterns) { - const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); - return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); - } - _filter(basePath, entry, matcher, negativeRe) { - if (this._isSkippedByDeep(basePath, entry.path)) { - return false; - } - if (this._isSkippedSymbolicLink(entry)) { - return false; - } - const filepath = utils.path.removeLeadingDotSegment(entry.path); - if (this._isSkippedByPositivePatterns(filepath, matcher)) { - return false; - } - return this._isSkippedByNegativePatterns(filepath, negativeRe); - } - _isSkippedByDeep(basePath, entryPath) { - if (this._settings.deep === Infinity) { - return false; - } - return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; - } - _getEntryLevel(basePath, entryPath) { - const entryPathDepth = entryPath.split("/").length; - if (basePath === "") { - return entryPathDepth; - } - const basePathDepth = basePath.split("/").length; - return entryPathDepth - basePathDepth; - } - _isSkippedSymbolicLink(entry) { - return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + const writeEntries = []; + for (const w of writes) + if (_isSend2(w)) + writeEntries.push([TASKS3, w]); + else if (_isChannelWriteTupleEntry2(w)) { + const mappedResult = await w.mapper.invoke(w.value, config3); + if (mappedResult != null && mappedResult.length > 0) + writeEntries.push(...mappedResult); + } else if (_isChannelWriteEntry2(w)) { + const mappedValue = w.mapper !== undefined ? await w.mapper.invoke(w.value, config3) : w.value; + if (_isSkipWrite2(mappedValue)) + continue; + if (w.skipNone && mappedValue === undefined) + continue; + writeEntries.push([w.channel, mappedValue]); + } else + throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); + const write = config3.configurable?.[CONFIG_KEY_SEND2]; + write(writeEntries); } - _isSkippedByPositivePatterns(entryPath, matcher) { - return !this._settings.baseNameMatch && !matcher.match(entryPath); + static isWriter(runnable) { + return runnable instanceof ChannelWrite4 || IS_WRITER2 in runnable && !!runnable[IS_WRITER2]; } - _isSkippedByNegativePatterns(entryPath, patternsRe) { - return !utils.pattern.matchAny(entryPath, patternsRe); + static registerWriter(runnable) { + return Object.defineProperty(runnable, IS_WRITER2, { value: true }); } - } - exports.default = DeepFilter; + }; }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/entry.js -var require_entry = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var utils = require_utils3(); - - class EntryFilter { - constructor(_settings, _micromatchOptions) { - this._settings = _settings; - this._micromatchOptions = _micromatchOptions; - this.index = new Map; - } - getFilter(positive, negative) { - const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); - const patterns = { - positive: { - all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) - }, - negative: { - absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), - relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/read.js +var defaultRunnableBound2, PregelNode3; +var init_read2 = __esm(() => { + init_constants5(); + init_utils14(); + init_write2(); + init_runnables(); + defaultRunnableBound2 = /* @__PURE__ */ new RunnablePassthrough; + PregelNode3 = class PregelNode4 extends RunnableBinding { + lc_graph_name = "PregelNode"; + channels; + triggers = []; + mapper; + writers = []; + bound = defaultRunnableBound2; + kwargs = {}; + metadata = {}; + tags = []; + retryPolicy; + cachePolicy; + subgraphs; + ends; + constructor(fields) { + const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; + const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; + super({ + ...fields, + bound: fields.bound ?? defaultRunnableBound2, + config: { + ...fields.config ? fields.config : {}, + tags: mergedTags } - }; - return (entry) => this._filter(entry, patterns); + }); + this.channels = channels; + this.triggers = triggers; + this.mapper = mapper; + this.writers = writers ?? this.writers; + this.bound = bound ?? this.bound; + this.kwargs = kwargs ?? this.kwargs; + this.metadata = metadata ?? this.metadata; + this.tags = mergedTags; + this.retryPolicy = retryPolicy; + this.cachePolicy = cachePolicy; + this.subgraphs = subgraphs; + this.ends = ends; } - _filter(entry, patterns) { - const filepath = utils.path.removeLeadingDotSegment(entry.path); - if (this._settings.unique && this._isDuplicateEntry(filepath)) { - return false; - } - if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { - return false; - } - const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); - if (this._settings.unique && isMatched) { - this._createIndexRecord(filepath); + getWriters() { + const newWriters = [...this.writers]; + while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite3 && newWriters[newWriters.length - 2] instanceof ChannelWrite3) { + const endWriters = newWriters.slice(-2); + const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); + newWriters[newWriters.length - 2] = new ChannelWrite3(combinedWrites, endWriters[0].config?.tags); + newWriters.pop(); } - return isMatched; - } - _isDuplicateEntry(filepath) { - return this.index.has(filepath); - } - _createIndexRecord(filepath) { - this.index.set(filepath, undefined); - } - _onlyFileFilter(entry) { - return this._settings.onlyFiles && !entry.dirent.isFile(); - } - _onlyDirectoryFilter(entry) { - return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + return newWriters; } - _isMatchToPatternsSet(filepath, patterns, isDirectory) { - const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); - if (!isMatched) { - return false; - } - const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); - if (isMatchedByRelativeNegative) { - return false; - } - const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); - if (isMatchedByAbsoluteNegative) { - return false; - } - return true; + getNode() { + const writers = this.getWriters(); + if (this.bound === defaultRunnableBound2 && writers.length === 0) + return; + else if (this.bound === defaultRunnableBound2 && writers.length === 1) + return writers[0]; + else if (this.bound === defaultRunnableBound2) + return new RunnableSequence({ + first: writers[0], + middle: writers.slice(1, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else if (writers.length > 0) + return new RunnableSequence({ + first: this.bound, + middle: writers.slice(0, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else + return this.bound; } - _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { - if (patternsRe.length === 0) { - return false; - } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); - return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + join(channels) { + if (!Array.isArray(channels)) + throw new Error("channels must be a list"); + if (typeof this.channels !== "object") + throw new Error("all channels must be named when using .join()"); + return new PregelNode4({ + channels: { + ...this.channels, + ...Object.fromEntries(channels.map((chan) => [chan, chan])) + }, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); } - _isMatchToPatterns(filepath, patternsRe, isDirectory) { - if (patternsRe.length === 0) { - return false; - } - const isMatched = utils.pattern.matchAny(filepath, patternsRe); - if (!isMatched && isDirectory) { - return utils.pattern.matchAny(filepath + "/", patternsRe); - } - return isMatched; + pipe(coerceable) { + if (ChannelWrite3.isWriter(coerceable)) + return new PregelNode4({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: [...this.writers, coerceable], + bound: this.bound, + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else if (this.bound === defaultRunnableBound2) + return new PregelNode4({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: _coerceToRunnable(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else + return new PregelNode4({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound.pipe(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); } - } - exports.default = EntryFilter; + }; }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/error.js -var require_error = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var utils = require_utils3(); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js +function isRunnableSequence2(x) { + return "steps" in x && Array.isArray(x.steps); +} +function isPregelLike2(x) { + return "lg_is_pregel" in x && x.lg_is_pregel === true; +} +function findSubgraphPregel2(candidate) { + const candidates = [candidate]; + for (const candidate2 of candidates) + if (isPregelLike2(candidate2)) + return candidate2; + else if (isRunnableSequence2(candidate2)) + candidates.push(...candidate2.steps); +} +var init_subgraph2 = () => {}; - class ErrorFilter { - constructor(_settings) { - this._settings = _settings; - } - getFilter() { - return (error51) => this._isNonFatalError(error51); - } - _isNonFatalError(error51) { - return utils.errno.isEnoentCodeError(error51) || this._settings.suppressErrors; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/io.js +function readChannel2(channels, chan, catchErrors = true, returnException = false) { + try { + return channels[chan].get(); + } catch (e) { + if (e.name === EmptyChannelError2.unminifiable_name) { + if (returnException) + return e; + else if (catchErrors) + return null; } + throw e; } - exports.default = ErrorFilter; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/transformers/entry.js -var require_entry2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var utils = require_utils3(); - - class EntryTransformer { - constructor(_settings) { - this._settings = _settings; - } - getTransformer() { - return (entry) => this._transform(entry); - } - _transform(entry) { - let filepath = entry.path; - if (this._settings.absolute) { - filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); - filepath = utils.path.unixify(filepath); - } - if (this._settings.markDirectories && entry.dirent.isDirectory()) { - filepath += "/"; - } - if (!this._settings.objectMode) { - return filepath; +} +function readChannels2(channels, select, skipEmpty = true) { + if (Array.isArray(select)) { + const values = {}; + for (const k of select) + try { + values[k] = readChannel2(channels, k, !skipEmpty); + } catch (e) { + if (e.name === EmptyChannelError2.unminifiable_name) + continue; } - return Object.assign(Object.assign({}, entry), { path: filepath }); - } + return values; + } else + return readChannel2(channels, select); +} +function* mapCommand2(cmd, pendingWrites) { + if (cmd.graph === Command2.PARENT) + throw new InvalidUpdateError2("There is no parent graph."); + if (cmd.goto) { + let sends; + if (Array.isArray(cmd.goto)) + sends = cmd.goto; + else + sends = [cmd.goto]; + for (const send of sends) + if (_isSend2(send)) + yield [ + NULL_TASK_ID2, + TASKS3, + send + ]; + else if (typeof send === "string") + yield [ + NULL_TASK_ID2, + `branch:to:${send}`, + "__start__" + ]; + else + throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); } - exports.default = EntryTransformer; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/provider.js -var require_provider = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var path2 = __require("path"); - var deep_1 = require_deep(); - var entry_1 = require_entry(); - var error_1 = require_error(); - var entry_2 = require_entry2(); - - class Provider { - constructor(_settings) { - this._settings = _settings; - this.errorFilter = new error_1.default(this._settings); - this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); - this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); - this.entryTransformer = new entry_2.default(this._settings); - } - _getRootDirectory(task2) { - return path2.resolve(this._settings.cwd, task2.base); - } - _getReaderOptions(task2) { - const basePath = task2.base === "." ? "" : task2.base; - return { - basePath, - pathSegmentSeparator: "/", - concurrency: this._settings.concurrency, - deepFilter: this.deepFilter.getFilter(basePath, task2.positive, task2.negative), - entryFilter: this.entryFilter.getFilter(task2.positive, task2.negative), - errorFilter: this.errorFilter.getFilter(), - followSymbolicLinks: this._settings.followSymbolicLinks, - fs: this._settings.fs, - stats: this._settings.stats, - throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, - transform: this.entryTransformer.getTransformer() - }; - } - _getMicromatchOptions() { - return { - dot: this._settings.dot, - matchBase: this._settings.baseNameMatch, - nobrace: !this._settings.braceExpansion, - nocase: !this._settings.caseSensitiveMatch, - noext: !this._settings.extglob, - noglobstar: !this._settings.globstar, - posix: true, - strictSlashes: false - }; - } - } - exports.default = Provider; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/async.js -var require_async6 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var async_1 = require_async5(); - var provider_1 = require_provider(); - - class ProviderAsync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new async_1.default(this._settings); - } - async read(task2) { - const root = this._getRootDirectory(task2); - const options = this._getReaderOptions(task2); - const entries = await this.api(root, task2, options); - return entries.map((entry) => options.transform(entry)); - } - api(root, task2, options) { - if (task2.dynamic) { - return this._reader.dynamic(root, options); + if (cmd.resume) + if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH32)) + for (const [tid, resume] of Object.entries(cmd.resume)) { + const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === "__resume__").map((w) => w[2]).slice(0, 1) ?? []; + existing.push(resume); + yield [ + tid, + RESUME3, + existing + ]; } - return this._reader.static(task2.patterns, options); - } + else + yield [ + NULL_TASK_ID2, + RESUME3, + cmd.resume + ]; + if (cmd.update) { + if (typeof cmd.update !== "object" || !cmd.update) + throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); + if (Array.isArray(cmd.update)) + for (const [k, v] of cmd.update) + yield [ + NULL_TASK_ID2, + k, + v + ]; + else + for (const [k, v] of Object.entries(cmd.update)) + yield [ + NULL_TASK_ID2, + k, + v + ]; } - exports.default = ProviderAsync; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/stream.js -var require_stream4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var stream_1 = __require("stream"); - var stream_2 = require_stream3(); - var provider_1 = require_provider(); - - class ProviderStream extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new stream_2.default(this._settings); - } - read(task2) { - const root = this._getRootDirectory(task2); - const options = this._getReaderOptions(task2); - const source = this.api(root, task2, options); - const destination = new stream_1.Readable({ objectMode: true, read: () => {} }); - source.once("error", (error51) => destination.emit("error", error51)).on("data", (entry) => destination.emit("data", options.transform(entry))).once("end", () => destination.emit("end")); - destination.once("close", () => source.destroy()); - return destination; - } - api(root, task2, options) { - if (task2.dynamic) { - return this._reader.dynamic(root, options); - } - return this._reader.static(task2.patterns, options); - } +} +function* mapInput2(inputChannels, chunk) { + if (chunk !== undefined && chunk !== null) + if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { + for (const k in chunk) + if (inputChannels.includes(k)) + yield [k, chunk[k]]; + } else if (Array.isArray(inputChannels)) + throw new Error(`Input chunk must be an object when "inputChannels" is an array`); + else + yield [inputChannels, chunk]; +} +function* mapOutputValues2(outputChannels, pendingWrites, channels) { + if (Array.isArray(outputChannels)) { + if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) + yield readChannels2(channels, outputChannels); + } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) + yield readChannel2(channels, outputChannels); +} +function* mapOutputUpdates2(outputChannels, tasks, cached3) { + const outputTasks = tasks.filter(([task2, ww]) => { + return (task2.config === undefined || !task2.config.tags?.includes("langsmith:hidden")) && ww[0][0] !== "__error__" && ww[0][0] !== "__interrupt__"; + }); + if (!outputTasks.length) + return; + let updated; + if (outputTasks.some(([task2]) => task2.writes.some(([chan, _]) => chan === "__return__"))) + updated = outputTasks.flatMap(([task2]) => task2.writes.filter(([chan, _]) => chan === RETURN2).map(([_, value]) => [task2.name, value])); + else if (!Array.isArray(outputChannels)) + updated = outputTasks.flatMap(([task2]) => task2.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task2.name, value])); + else + updated = outputTasks.flatMap(([task2]) => { + const { writes } = task2; + const counts = {}; + for (const [chan] of writes) + if (outputChannels.includes(chan)) + counts[chan] = (counts[chan] || 0) + 1; + if (Object.values(counts).some((count) => count > 1)) + return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task2.name, { [chan]: value }]); + else + return [[task2.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; + }); + const grouped = {}; + for (const [node, value] of updated) { + if (!(node in grouped)) + grouped[node] = []; + grouped[node].push(value); } - exports.default = ProviderStream; + const flattened = {}; + for (const node in grouped) + if (grouped[node].length === 1) { + const [write] = grouped[node]; + flattened[node] = write; + } else + flattened[node] = grouped[node]; + if (cached3) + flattened["__metadata__"] = { cached: cached3 }; + yield flattened; +} +var init_io2 = __esm(() => { + init_constants5(); + init_errors9(); + init_hash4(); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/sync.js -var require_sync5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var fsStat = require_out(); - var fsWalk = require_out3(); - var reader_1 = require_reader2(); - - class ReaderSync extends reader_1.default { - constructor() { - super(...arguments); - this._walkSync = fsWalk.walkSync; - this._statSync = fsStat.statSync; - } - dynamic(root, options) { - return this._walkSync(root, options); - } - static(patterns, options) { - const entries = []; - for (const pattern of patterns) { - const filepath = this._getFullEntryPath(pattern); - const entry = this._getEntry(filepath, pattern, options); - if (entry === null || !options.entryFilter(entry)) { - continue; - } - entries.push(entry); - } - return entries; - } - _getEntry(filepath, pattern, options) { - try { - const stats = this._getStat(filepath); - return this._makeEntry(stats, pattern); - } catch (error51) { - if (options.errorFilter(error51)) { - return null; - } - throw error51; - } - } - _getStat(filepath) { - return this._statSync(filepath, this._fsStatSettings); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/utils/index.js +function getNullChannelVersion2(currentVersions) { + const startVersion = typeof currentVersions[START2]; + if (startVersion === "number") + return 0; + if (startVersion === "string") + return ""; + for (const key in currentVersions) { + if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) + continue; + const versionType = typeof currentVersions[key]; + if (versionType === "number") + return 0; + if (versionType === "string") + return ""; + break; } - exports.default = ReaderSync; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/sync.js -var require_sync6 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var sync_1 = require_sync5(); - var provider_1 = require_provider(); - - class ProviderSync extends provider_1.default { - constructor() { - super(...arguments); - this._reader = new sync_1.default(this._settings); - } - read(task2) { - const root = this._getRootDirectory(task2); - const options = this._getReaderOptions(task2); - const entries = this.api(root, task2, options); - return entries.map(options.transform); - } - api(root, task2, options) { - if (task2.dynamic) { - return this._reader.dynamic(root, options); +} +function getNewChannelVersions2(previousVersions, currentVersions) { + if (Object.keys(previousVersions).length > 0) { + const nullVersion = getNullChannelVersion2(currentVersions); + return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); + } else + return currentVersions; +} +function _coerceToDict4(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function patchConfigurable4(config3, patch) { + if (config3 === null) + return { configurable: patch }; + else if (config3?.configurable === undefined) + return { + ...config3, + configurable: patch + }; + else + return { + ...config3, + configurable: { + ...config3.configurable, + ...patch } - return this._reader.static(task2.patterns, options); + }; +} +function patchCheckpointMap2(config3, metadata) { + const parents = metadata?.parents ?? {}; + if (Object.keys(parents).length > 0) + return patchConfigurable4(config3, { [CONFIG_KEY_CHECKPOINT_MAP2]: { + ...parents, + [config3.configurable?.checkpoint_ns ?? ""]: config3.configurable?.checkpoint_id + } }); + else + return config3; +} +function combineAbortSignals2(...x) { + const signals = [...new Set(x.filter(Boolean))]; + if (signals.length === 0) + return { + signal: undefined, + dispose: undefined + }; + if (signals.length === 1) + return { + signal: signals[0], + dispose: undefined + }; + const combinedController = new AbortController; + const listener = () => { + const reason = signals.find((s) => s.aborted)?.reason; + combinedController.abort(reason); + signals.forEach((s) => s.removeEventListener("abort", listener)); + }; + signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); + const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); + if (hasAlreadyAbortedSignal) + combinedController.abort(hasAlreadyAbortedSignal.reason); + return { + signal: combinedController.signal, + dispose: () => { + signals.forEach((s) => s.removeEventListener("abort", listener)); } - } - exports.default = ProviderSync; -}); - -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/settings.js -var require_settings4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DEFAULT_FILE_SYSTEM_ADAPTER = undefined; - var fs = __require("fs"); - var os = __require("os"); - var CPU_COUNT = Math.max(os.cpus().length, 1); - exports.DEFAULT_FILE_SYSTEM_ADAPTER = { - lstat: fs.lstat, - lstatSync: fs.lstatSync, - stat: fs.stat, - statSync: fs.statSync, - readdir: fs.readdir, - readdirSync: fs.readdirSync }; +} +var combineCallbacks2 = (callback1, callback2) => { + if (!callback1 && !callback2) + return; + if (!callback1) + return callback2; + if (!callback2) + return callback1; + if (Array.isArray(callback1) && Array.isArray(callback2)) + return [...callback1, ...callback2]; + if (Array.isArray(callback1)) + return [...callback1, callback2]; + if (Array.isArray(callback2)) + return [callback1, ...callback2]; + return [callback1, callback2]; +}; +var init_utils15 = __esm(() => { + init_constants5(); +}); - class Settings { - constructor(_options = {}) { - this._options = _options; - this.absolute = this._getValue(this._options.absolute, false); - this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); - this.braceExpansion = this._getValue(this._options.braceExpansion, true); - this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); - this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); - this.cwd = this._getValue(this._options.cwd, process.cwd()); - this.deep = this._getValue(this._options.deep, Infinity); - this.dot = this._getValue(this._options.dot, false); - this.extglob = this._getValue(this._options.extglob, true); - this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); - this.fs = this._getFileSystemMethods(this._options.fs); - this.globstar = this._getValue(this._options.globstar, true); - this.ignore = this._getValue(this._options.ignore, []); - this.markDirectories = this._getValue(this._options.markDirectories, false); - this.objectMode = this._getValue(this._options.objectMode, false); - this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); - this.onlyFiles = this._getValue(this._options.onlyFiles, true); - this.stats = this._getValue(this._options.stats, false); - this.suppressErrors = this._getValue(this._options.suppressErrors, false); - this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); - this.unique = this._getValue(this._options.unique, true); - if (this.onlyDirectories) { - this.onlyFiles = false; - } - if (this.stats) { - this.objectMode = true; - } - this.ignore = [].concat(this.ignore); - } - _getValue(option, value) { - return option === undefined ? value : option; - } - _getFileSystemMethods(methods = {}) { - return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/types.js +function isCall2(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; +} +var Call2 = class { + func; + name; + input; + retry; + cache; + callbacks; + __lg_type = "call"; + constructor({ func, name, input, retry, cache: cache2, callbacks }) { + this.func = func; + this.name = name; + this.input = input; + this.retry = retry; + this.cache = cache2; + this.callbacks = callbacks; } - exports.default = Settings; +}; +var init_types12 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/call.js +function getRunnableForFunc2(name, func) { + return new RunnableSequence({ + name, + first: new RunnableCallable3({ + func: (input) => func(...input), + name, + trace: false, + recurse: false + }), + last: new ChannelWrite3([{ + channel: RETURN2, + value: PASSTHROUGH2 + }], [TAG_HIDDEN2]) + }); +} +function getRunnableForEntrypoint2(name, func) { + return new RunnableCallable3({ + func: (input, config3) => { + return func(input, config3); + }, + name, + trace: false, + recurse: false + }); +} +var init_call2 = __esm(() => { + init_constants5(); + init_utils14(); + init_write2(); + init_singletons(); + init_runnables(); }); -// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/index.js -var require_out4 = __commonJS((exports, module) => { - var taskManager = require_tasks(); - var async_1 = require_async6(); - var stream_1 = require_stream4(); - var sync_1 = require_sync6(); - var settings_1 = require_settings4(); - var utils = require_utils3(); - async function FastGlob(source, options) { - assertPatternsInput(source); - const works = getWorks(source, async_1.default, options); - const result = await Promise.all(works); - return utils.array.flatten(result); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/algo.js +function triggersNextStep2(updatedChannels, triggerToNodes) { + if (triggerToNodes == null) + return false; + for (const chan of updatedChannels) + if (triggerToNodes[chan]) + return true; + return false; +} +function maxChannelMapVersion2(channelVersions) { + let maxVersion; + for (const chan in channelVersions) { + if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) + continue; + if (maxVersion == null) + maxVersion = channelVersions[chan]; + else + maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); } - (function(FastGlob2) { - FastGlob2.glob = FastGlob2; - FastGlob2.globSync = sync; - FastGlob2.globStream = stream2; - FastGlob2.async = FastGlob2; - function sync(source, options) { - assertPatternsInput(source); - const works = getWorks(source, sync_1.default, options); - return utils.array.flatten(works); - } - FastGlob2.sync = sync; - function stream2(source, options) { - assertPatternsInput(source); - const works = getWorks(source, stream_1.default, options); - return utils.stream.merge(works); - } - FastGlob2.stream = stream2; - function generateTasks(source, options) { - assertPatternsInput(source); - const patterns = [].concat(source); - const settings = new settings_1.default(options); - return taskManager.generate(patterns, settings); - } - FastGlob2.generateTasks = generateTasks; - function isDynamicPattern(source, options) { - assertPatternsInput(source); - const settings = new settings_1.default(options); - return utils.pattern.isDynamicPattern(source, settings); - } - FastGlob2.isDynamicPattern = isDynamicPattern; - function escapePath(source) { - assertPatternsInput(source); - return utils.path.escape(source); - } - FastGlob2.escapePath = escapePath; - function convertPathToPattern(source) { - assertPatternsInput(source); - return utils.path.convertPathToPattern(source); - } - FastGlob2.convertPathToPattern = convertPathToPattern; - let posix; - (function(posix2) { - function escapePath2(source) { - assertPatternsInput(source); - return utils.path.escapePosixPath(source); - } - posix2.escapePath = escapePath2; - function convertPathToPattern2(source) { - assertPatternsInput(source); - return utils.path.convertPosixPathToPattern(source); - } - posix2.convertPathToPattern = convertPathToPattern2; - })(posix = FastGlob2.posix || (FastGlob2.posix = {})); - let win32; - (function(win322) { - function escapePath2(source) { - assertPatternsInput(source); - return utils.path.escapeWindowsPath(source); - } - win322.escapePath = escapePath2; - function convertPathToPattern2(source) { - assertPatternsInput(source); - return utils.path.convertWindowsPathToPattern(source); + return maxVersion; +} +function shouldInterrupt2(checkpoint, interruptNodes, tasks) { + const nullVersion = getNullChannelVersion2(checkpoint.channel_versions); + const seen = checkpoint.versions_seen["__interrupt__"] ?? {}; + let anyChannelUpdated = false; + if ((checkpoint.channel_versions["__start__"] ?? nullVersion) > (seen["__start__"] ?? nullVersion)) + anyChannelUpdated = true; + else + for (const chan in checkpoint.channel_versions) { + if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) + continue; + if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { + anyChannelUpdated = true; + break; } - win322.convertPathToPattern = convertPathToPattern2; - })(win32 = FastGlob2.win32 || (FastGlob2.win32 = {})); - })(FastGlob || (FastGlob = {})); - function getWorks(source, _Provider, options) { - const patterns = [].concat(source); - const settings = new settings_1.default(options); - const tasks = taskManager.generate(patterns, settings); - const provider = new _Provider(settings); - return tasks.map(provider.read, provider); - } - function assertPatternsInput(input) { - const source = [].concat(input); - const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); - if (!isValidSource) { - throw new TypeError("Patterns must be a string (non empty) or an array of strings"); - } - } - module.exports = FastGlob; -}); - -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/errors.js -var LangSmithSandboxError, LangSmithSandboxAPIError, LangSmithSandboxAuthenticationError, LangSmithSandboxConnectionError, LangSmithResourceNotFoundError, LangSmithResourceTimeoutError, LangSmithResourceNameConflictError, LangSmithValidationError, LangSmithQuotaExceededError, LangSmithResourceCreationError, LangSmithSandboxCreationError, LangSmithDataplaneNotConfiguredError, LangSmithSandboxNotReadyError, LangSmithSandboxOperationError, LangSmithCommandTimeoutError, LangSmithSandboxServerReloadError; -var init_errors8 = __esm(() => { - LangSmithSandboxError = class LangSmithSandboxError extends Error { - constructor(message) { - super(message); - this.name = "LangSmithSandboxError"; - } - }; - LangSmithSandboxAPIError = class LangSmithSandboxAPIError extends LangSmithSandboxError { - constructor(message) { - super(message); - this.name = "LangSmithSandboxAPIError"; - } - }; - LangSmithSandboxAuthenticationError = class LangSmithSandboxAuthenticationError extends LangSmithSandboxError { - constructor(message) { - super(message); - this.name = "LangSmithSandboxAuthenticationError"; - } - }; - LangSmithSandboxConnectionError = class LangSmithSandboxConnectionError extends LangSmithSandboxError { - constructor(message) { - super(message); - this.name = "LangSmithSandboxConnectionError"; - } - }; - LangSmithResourceNotFoundError = class LangSmithResourceNotFoundError extends LangSmithSandboxError { - constructor(message, resourceType) { - super(message); - Object.defineProperty(this, "resourceType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithResourceNotFoundError"; - this.resourceType = resourceType; - } - }; - LangSmithResourceTimeoutError = class LangSmithResourceTimeoutError extends LangSmithSandboxError { - constructor(message, resourceType, lastStatus) { - super(message); - Object.defineProperty(this, "resourceType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "lastStatus", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithResourceTimeoutError"; - this.resourceType = resourceType; - this.lastStatus = lastStatus; } - toString() { - const base = super.toString(); - if (this.lastStatus) { - return `${base} (last_status: ${this.lastStatus})`; + const anyTriggeredNodeInInterruptNodes = tasks.some((task2) => interruptNodes === "*" ? !task2.config?.tags?.includes(TAG_HIDDEN2) : interruptNodes.includes(task2.name)); + return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; +} +function _localRead2(checkpoint, channels, task2, select, fresh = false) { + let updated = /* @__PURE__ */ new Set; + if (!Array.isArray(select)) { + for (const [c] of task2.writes) + if (c === select) { + updated = new Set([c]); + break; } - return base; - } - }; - LangSmithResourceNameConflictError = class LangSmithResourceNameConflictError extends LangSmithSandboxError { - constructor(message, resourceType) { - super(message); - Object.defineProperty(this, "resourceType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithResourceNameConflictError"; - this.resourceType = resourceType; - } - }; - LangSmithValidationError = class LangSmithValidationError extends LangSmithSandboxError { - constructor(message, field, details, errorType) { - super(message); - Object.defineProperty(this, "field", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "errorType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithValidationError"; - this.field = field; - this.details = details; - this.errorType = errorType; - } - }; - LangSmithQuotaExceededError = class LangSmithQuotaExceededError extends LangSmithSandboxError { - constructor(message, quotaType) { - super(message); - Object.defineProperty(this, "quotaType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithQuotaExceededError"; - this.quotaType = quotaType; + updated = updated || /* @__PURE__ */ new Set; + } else + updated = new Set(select.filter((c) => task2.writes.some(([key, _]) => key === c))); + let values; + if (fresh && updated.size > 0) { + const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); + const newCheckpoint = createCheckpoint2(checkpoint, localChannels, -1); + const newChannels = emptyChannels2(localChannels, newCheckpoint); + _applyWrites2(copyCheckpoint(newCheckpoint), newChannels, [task2], undefined, undefined); + values = readChannels2({ + ...channels, + ...newChannels + }, select); + } else + values = readChannels2(channels, select); + return values; +} +function _localWrite2(commit, processes, writes) { + for (const [chan, value] of writes) + if (["__pregel_push", "__pregel_tasks"].includes(chan) && value != null) { + if (!_isSend2(value)) + throw new InvalidUpdateError2(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); + if (!(value.node in processes)) + throw new InvalidUpdateError2(`Invalid node name "${value.node}" in Send packet`); } - }; - LangSmithResourceCreationError = class LangSmithResourceCreationError extends LangSmithSandboxError { - constructor(message, resourceType, errorType) { - super(message); - Object.defineProperty(this, "resourceType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "errorType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithResourceCreationError"; - this.resourceType = resourceType; - this.errorType = errorType; + commit(writes); +} +function _applyWrites2(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { + tasks.sort((a, b) => { + const aPath = a.path?.slice(0, 3) || []; + const bPath = b.path?.slice(0, 3) || []; + for (let i = 0;i < Math.min(aPath.length, bPath.length); i += 1) { + if (aPath[i] < bPath[i]) + return -1; + if (aPath[i] > bPath[i]) + return 1; } - toString() { - if (this.errorType) { - return `${super.toString()} [${this.errorType}]`; + return aPath.length - bPath.length; + }); + const bumpStep = tasks.some((task2) => task2.triggers.length > 0); + const onlyChannels = getOnlyChannels2(channels); + for (const task2 of tasks) { + checkpoint.versions_seen[task2.name] ??= {}; + for (const chan of task2.triggers) + if (chan in checkpoint.channel_versions) + checkpoint.versions_seen[task2.name][chan] = checkpoint.channel_versions[chan]; + } + let maxVersion = maxChannelMapVersion2(checkpoint.channel_versions); + const channelsToConsume = new Set(tasks.flatMap((task2) => task2.triggers).filter((chan) => !RESERVED2.includes(chan))); + let usedNewVersion = false; + for (const chan of channelsToConsume) + if (chan in onlyChannels && onlyChannels[chan].consume()) { + if (getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + usedNewVersion = true; } - return super.toString(); - } - }; - LangSmithSandboxCreationError = class LangSmithSandboxCreationError extends LangSmithSandboxError { - constructor(message, errorType) { - super(message); - Object.defineProperty(this, "errorType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithSandboxCreationError"; - this.errorType = errorType; } - toString() { - if (this.errorType) { - return `${super.toString()} [${this.errorType}]`; + const pendingWritesByChannel = {}; + for (const task2 of tasks) + for (const [chan, val] of task2.writes) + if (IGNORE2.has(chan)) {} else if (chan in onlyChannels) { + pendingWritesByChannel[chan] ??= []; + pendingWritesByChannel[chan].push(val); + } + if (maxVersion != null && getNextVersion != null) + maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; + const updatedChannels = /* @__PURE__ */ new Set; + for (const [chan, vals] of Object.entries(pendingWritesByChannel)) + if (chan in onlyChannels) { + const channel = onlyChannels[chan]; + let updated; + try { + updated = channel.update(vals); + } catch (e) { + if (e.name === InvalidUpdateError2.unminifiable_name) { + const wrappedError = new InvalidUpdateError2(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); + wrappedError.lc_error_code = e.lc_error_code; + throw wrappedError; + } else + throw e; + } + if (updated && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); } - return super.toString(); - } - }; - LangSmithDataplaneNotConfiguredError = class LangSmithDataplaneNotConfiguredError extends LangSmithSandboxError { - constructor(message) { - super(message); - this.name = "LangSmithDataplaneNotConfiguredError"; - } - }; - LangSmithSandboxNotReadyError = class LangSmithSandboxNotReadyError extends LangSmithSandboxError { - constructor(message) { - super(message); - this.name = "LangSmithSandboxNotReadyError"; - } - }; - LangSmithSandboxOperationError = class LangSmithSandboxOperationError extends LangSmithSandboxError { - constructor(message, operation, errorType) { - super(message); - Object.defineProperty(this, "operation", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "errorType", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithSandboxOperationError"; - this.operation = operation; - this.errorType = errorType; } - toString() { - if (this.errorType) { - return `${super.toString()} [${this.errorType}]`; + if (bumpStep) + for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) + continue; + const channel = onlyChannels[chan]; + if (channel.isAvailable() && !updatedChannels.has(chan)) { + if (channel.update([]) && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); + } } - return super.toString(); } - }; - LangSmithCommandTimeoutError = class LangSmithCommandTimeoutError extends LangSmithSandboxOperationError { - constructor(message, timeout) { - super(message, "command", "CommandTimeout"); - Object.defineProperty(this, "timeout", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = "LangSmithCommandTimeoutError"; - this.timeout = timeout; + if (bumpStep && !triggersNextStep2(updatedChannels, triggerToNodes)) + for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) + continue; + const channel = onlyChannels[chan]; + if (channel.finish() && getNextVersion !== undefined) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) + updatedChannels.add(chan); + } } - }; - LangSmithSandboxServerReloadError = class LangSmithSandboxServerReloadError extends LangSmithSandboxConnectionError { - constructor(message) { - super(message); - this.name = "LangSmithSandboxServerReloadError"; + return updatedChannels; +} +function* candidateNodes2(checkpoint, processes, extra) { + if (extra.updatedChannels != null && extra.triggerToNodes != null) { + const triggeredNodes = /* @__PURE__ */ new Set; + for (const channel of extra.updatedChannels) { + const nodeIds = extra.triggerToNodes[channel]; + for (const id of nodeIds ?? []) + triggeredNodes.add(id); } - }; -}); - -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/helpers.js -function validateTtl(value, name) { - if (value === undefined) { + yield* [...triggeredNodes].sort(); return; } - if (value < 0) { - throw new LangSmithValidationError(`${name} must be >= 0, got ${value}`, name); + if ((() => { + for (const chan in checkpoint.channel_versions) + if (checkpoint.channel_versions[chan] !== null) + return false; + return true; + })()) + return; + for (const name in processes) { + if (!Object.prototype.hasOwnProperty.call(processes, name)) + continue; + yield name; } - if (value !== 0 && value % 60 !== 0) { - throw new LangSmithValidationError(`${name} must be a multiple of 60 seconds, got ${value}`, name); +} +function _prepareNextTasks2(checkpoint, pendingWrites, processes, channels, config3, forExecution, extra) { + const tasks = {}; + const tasksChannel = channels[TASKS3]; + if (tasksChannel?.isAvailable()) { + const len = tasksChannel.get().length; + for (let i = 0;i < len; i += 1) { + const task2 = _prepareSingleTask2([PUSH2, i], checkpoint, pendingWrites, processes, channels, config3, forExecution, extra); + if (task2 !== undefined) + tasks[task2.id] = task2; + } + } + for (const name of candidateNodes2(checkpoint, processes, extra)) { + const task2 = _prepareSingleTask2([PULL2, name], checkpoint, pendingWrites, processes, channels, config3, forExecution, extra); + if (task2 !== undefined) + tasks[task2.id] = task2; } + return tasks; } -async function parseErrorResponse(response) { - try { - const data = await response.json(); - const detail = data?.detail; - if (detail && typeof detail === "object" && !Array.isArray(detail)) { +function _prepareSingleTask2(taskPath, checkpoint, pendingWrites, processes, channels, config3, forExecution, extra) { + const { step, checkpointer, manager } = extra; + const configurable = config3.configurable ?? {}; + const parentNamespace = configurable.checkpoint_ns ?? ""; + if (taskPath[0] === "__pregel_push" && isCall2(taskPath[taskPath.length - 1])) { + const call3 = taskPath[taskPath.length - 1]; + const proc = getRunnableForFunc2(call3.name, call3.func); + const triggers = [PUSH2]; + const checkpointNamespace = parentNamespace === "" ? call3.name : `${parentNamespace}|${call3.name}`; + const id = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + call3.name, + PUSH2, + taskPath[1], + taskPath[2] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${id}`; + const outputTaskPath = [...taskPath.slice(0, 3), true]; + const metadata = { + langgraph_step: step, + langgraph_node: call3.name, + langgraph_triggers: triggers, + langgraph_path: outputTaskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId: id, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; return { - errorType: detail.error, - message: detail.message || `HTTP ${response.status}: ${response.statusText}` + name: call3.name, + input: call3.input, + proc, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + store: extra.store ?? config3.store + }), { + runName: call3.name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID2]: id, + [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { + name: call3.name, + writes, + triggers, + path: outputTaskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP2]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ + pendingWrites: pendingWrites ?? [], + taskId: id, + currentTaskInput: call3.input, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP2], + namespaceHash: XXH32(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: call3.retry, + cache_key: call3.cache ? { + key: XXH32((call3.cache.keyFunc ?? JSON.stringify)([call3.input])), + ns: [CACHE_NS_WRITES2, call3.name ?? "__dynamic__"], + ttl: call3.cache.ttl + } : undefined, + id, + path: outputTaskPath, + writers: [] }; - } - if (Array.isArray(detail) && detail.length > 0) { - const messages = detail.filter((d) => typeof d === "object" && d !== null).map((d) => d.msg || String(d)).filter(Boolean); + } else return { - errorType: undefined, - message: messages.length > 0 ? messages.join("; ") : `HTTP ${response.status}: ${response.statusText}` + id, + name: call3.name, + interrupts: [], + path: outputTaskPath }; + } else if (taskPath[0] === "__pregel_push") { + const index2 = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); + if (!channels["__pregel_tasks"]?.isAvailable()) + return; + const sends = channels[TASKS3].get(); + if (index2 < 0 || index2 >= sends.length) + return; + const packet = _isSendInterface2(sends[index2]) && !_isSend2(sends[index2]) ? new Send2(sends[index2].node, sends[index2].args) : sends[index2]; + if (!_isSendInterface2(packet)) { + console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); + return; } - return { - errorType: undefined, - message: detail || `HTTP ${response.status}: ${response.statusText}` - }; - } catch { - return { - errorType: undefined, - message: `HTTP ${response.status}: ${response.statusText}` - }; - } -} -async function parseValidationError(response) { - try { - const data = await response.json(); - const detail = data?.detail; - if (Array.isArray(detail)) { - return detail; + if (!(packet.node in processes)) { + console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); + return; + } + const triggers = [PUSH2]; + const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}|${packet.node}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + packet.node, + PUSH2, + index2.toString() + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: packet.node, + langgraph_triggers: triggers, + langgraph_path: taskPath.slice(0, 3), + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const proc = processes[packet.node]; + const node = proc.getNode(); + if (node !== undefined) { + if (proc.metadata !== undefined) + metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; + return { + name: packet.node, + input: packet.args, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + tags: proc.tags, + store: extra.store ?? config3.store + }), { + runName: packet.node, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID2]: taskId, + [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { + name: packet.node, + writes, + triggers, + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP2]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: packet.args, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP2], + namespaceHash: XXH32(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers, + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH32((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), + ns: [ + CACHE_NS_WRITES2, + proc.name ?? "__dynamic__", + packet.node + ], + ttl: proc.cachePolicy.ttl + } : undefined, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else + return { + id: taskId, + name: packet.node, + interrupts: [], + path: taskPath + }; + } else if (taskPath[0] === "__pregel_pull") { + const name = taskPath[1].toString(); + const proc = processes[name]; + if (proc === undefined) + return; + if (pendingWrites?.length) { + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL2, + name + ]), checkpoint.id); + if (pendingWrites.some((w) => w[0] === taskId && w[1] !== "__error__")) + return; + } + const nullVersion = getNullChannelVersion2(checkpoint.channel_versions); + if (nullVersion === undefined) + return; + const seen = checkpoint.versions_seen[name] ?? {}; + const trigger = proc.triggers.find((chan) => { + if (!channels[chan].isAvailable()) + return false; + return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); + }); + if (trigger !== undefined) { + const val = _procInput2(proc, channels, forExecution); + if (val === undefined) + return; + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; + const taskId = uuid52(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL2, + [trigger] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: name, + langgraph_triggers: [trigger], + langgraph_path: taskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace, + checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const node = proc.getNode(); + if (node !== undefined) { + if (proc.metadata !== undefined) + metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + const executionInfo = { + checkpointId: checkpoint.id, + checkpointNs: taskCheckpointNamespace, + taskId, + threadId: configurable.thread_id, + runId: config3.runId != null ? String(config3.runId) : undefined, + nodeAttempt: 1 + }; + return { + name, + input: val, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: { + ...patchConfig(mergeConfigs(config3, { + metadata, + tags: proc.tags, + store: extra.store ?? config3.store + }), { + runName: name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID2]: taskId, + [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => { + writes.push(...items); + }, processes, writes_), + [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { + name, + writes, + triggers: [trigger], + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], + [CONFIG_KEY_CHECKPOINT_MAP2]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], + [parentNamespace]: checkpoint.id + }, + [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: val, + resumeMap: config3.configurable?.[CONFIG_KEY_RESUME_MAP2], + namespaceHash: XXH32(taskCheckpointNamespace) + }), + [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], + checkpoint_id: undefined, + checkpoint_ns: taskCheckpointNamespace + } + }), + executionInfo + }, + triggers: [trigger], + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH32((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), + ns: [ + CACHE_NS_WRITES2, + proc.name ?? "__dynamic__", + name + ], + ttl: proc.cachePolicy.ttl + } : undefined, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else + return { + id: taskId, + name, + interrupts: [], + path: taskPath + }; } - return []; - } catch { - return []; } } -function extractQuotaType(message) { - const messageLower = message.toLowerCase(); - if (messageLower.includes("sandbox") && (messageLower.includes("count") || messageLower.includes("limit"))) { - return "sandbox_count"; - } else if (messageLower.includes("cpu")) { - return "cpu"; - } else if (messageLower.includes("memory")) { - return "memory"; - } else if (messageLower.includes("storage")) { - return "storage"; +function _procInput2(proc, channels, forExecution) { + let val; + if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { + val = {}; + for (const [k, chan] of Object.entries(proc.channels)) + if (proc.triggers.includes(chan)) + try { + val[k] = readChannel2(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError2.unminifiable_name) + return; + else + throw e; + } + else if (chan in channels) + try { + val[k] = readChannel2(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError2.unminifiable_name) + continue; + else + throw e; + } + } else if (Array.isArray(proc.channels)) { + let successfulRead = false; + for (const chan of proc.channels) + try { + val = readChannel2(channels, chan, false); + successfulRead = true; + break; + } catch (e) { + if (e.name === EmptyChannelError2.unminifiable_name) + continue; + else + throw e; + } + if (!successfulRead) + return; + } else + throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); + if (forExecution && proc.mapper !== undefined) + val = proc.mapper(val); + return val; +} +function sanitizeUntrackedValuesInSend2(packet, channels) { + if (typeof packet.args !== "object" || packet.args === null) + return packet; + const sanitizedArg = {}; + for (const [key, value] of Object.entries(packet.args)) { + const channel = channels[key]; + if (!channel || channel.lc_graph_name !== "UntrackedValue") + sanitizedArg[key] = value; } - return; + return new Send2(packet.node, sanitizedArg); } -async function handleSandboxCreationError(response) { - const status = response.status; - const clonedResponse = response.clone(); - const data = await parseErrorResponse(response); - if (status === 408) { - throw new LangSmithResourceTimeoutError(data.message, "sandbox"); - } else if (status === 422) { - const details = await parseValidationError(clonedResponse); - if (details.length > 0 && details.some((d) => d.type === "value_error")) { - const field = details[0]?.loc?.slice(-1)[0]; - throw new LangSmithValidationError(data.message, field, details); - } else { - throw new LangSmithSandboxCreationError(data.message, data.errorType); +function _scratchpad2({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { + const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__")?.[2]; + const scratchpad = { + callCounter: 0, + interruptCounter: -1, + resume: (() => { + const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === "__resume__").flatMap(([_writeTaskId, _chan, resume]) => resume); + if (resumeMap != null && namespaceHash in resumeMap) { + const mappedResume = resumeMap[namespaceHash]; + result.push(mappedResume); + } + return result; + })(), + nullResume, + subgraphCounter: 0, + currentTaskInput, + consumeNullResume: () => { + if (scratchpad.nullResume) { + delete scratchpad.nullResume; + pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__"), 1); + return nullResume; + } } - } else if (status === 429) { - const quotaType = extractQuotaType(data.message) ?? "unknown"; - throw new LangSmithQuotaExceededError(data.message, quotaType); - } else if (status === 503) { - throw new LangSmithSandboxCreationError(data.message, data.errorType || "Unschedulable"); - } - return handleClientHttpError(clonedResponse); + }; + return scratchpad; } -async function handleClientHttpError(response) { - const status = response.status; - const clonedResponse = status === 422 ? response.clone() : null; - const data = await parseErrorResponse(response); - const message = data.message; - const errorType = data.errorType; - if (status === 401 || status === 403) { - throw new LangSmithSandboxAuthenticationError(message); - } - if (status === 404) { - throw new LangSmithResourceNotFoundError(message); - } - if (status === 422 && clonedResponse) { - const details = await parseValidationError(clonedResponse); - const field = details[0]?.loc?.slice(-1)[0]; - throw new LangSmithValidationError(message, field, details); - } - if (status === 429) { - const quotaType = extractQuotaType(message); - throw new LangSmithQuotaExceededError(message, quotaType); - } - if (status === 502 && errorType === "ConnectionError") { - throw new LangSmithSandboxConnectionError(message); - } - if (status === 500) { - throw new LangSmithSandboxAPIError(message); +var increment2 = (current) => { + return current !== undefined ? current + 1 : 1; +}, IGNORE2; +var init_algo2 = __esm(() => { + init_constants5(); + init_errors9(); + init_base16(); + init_hash4(); + init_io2(); + init_types12(); + init_utils15(); + init_call2(); + init_dist3(); + init_runnables(); + IGNORE2 = new Set([ + NO_WRITES2, + PUSH2, + RESUME3, + INTERRUPT3, + RETURN2, + ERROR4 + ]); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/debug.js +function* mapDebugTasks2(tasks) { + for (const { id, name, input, config: config3, triggers, writes } of tasks) { + if (config3?.tags?.includes("langsmith:hidden")) + continue; + yield { + id, + name, + input, + triggers, + interrupts: writes.filter(([writeId, n4]) => { + return writeId === id && n4 === "__interrupt__"; + }).map(([, v]) => { + return v; + }) + }; } - throw new LangSmithSandboxError(message); } -async function handleSandboxHttpError(response) { - const data = await parseErrorResponse(response); - const message = data.message; - const errorType = data.errorType; - const status = response.status; - if (errorType === "WriteError") { - throw new LangSmithSandboxOperationError(message, "write", errorType); - } - if (errorType === "ReadError") { - throw new LangSmithSandboxOperationError(message, "read", errorType); - } - if (errorType === "CommandError") { - throw new LangSmithSandboxOperationError(message, "command", errorType); - } - if (status === 403) { - throw new LangSmithSandboxOperationError(message, undefined, "PermissionDenied"); +function isMultipleChannelWrite2(value) { + if (typeof value !== "object" || value === null) + return false; + return "$writes" in value && Array.isArray(value.$writes); +} +function mapTaskResultWrites2(writes) { + const result = {}; + for (const [channel, value] of writes) { + const strChannel = String(channel); + if (strChannel in result) { + const channelWrites = isMultipleChannelWrite2(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; + channelWrites.push(value); + result[strChannel] = { $writes: channelWrites }; + } else + result[strChannel] = value; } - if (status === 502 && errorType === "ConnectionError") { - throw new LangSmithSandboxConnectionError(message); + return result; +} +function* mapDebugTaskResults2(tasks, streamChannels) { + for (const [{ id, name, config: config3 }, writes] of tasks) { + if (config3?.tags?.includes("langsmith:hidden")) + continue; + yield { + id, + name, + result: mapTaskResultWrites2(writes.filter(([channel]) => { + return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; + })), + interrupts: writes.filter((w) => w[0] === INTERRUPT3).map((w) => w[1]) + }; } - if (status === 400 && errorType === "NotReady") { - throw new LangSmithSandboxNotReadyError(message); +} +function* mapDebugCheckpoint2(config3, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { + function formatConfig(config4) { + const pyConfig = {}; + if (config4.callbacks != null) + pyConfig.callbacks = config4.callbacks; + if (config4.configurable != null) + pyConfig.configurable = config4.configurable; + if (config4.maxConcurrency != null) + pyConfig.max_concurrency = config4.maxConcurrency; + if (config4.metadata != null) + pyConfig.metadata = config4.metadata; + if (config4.recursionLimit != null) + pyConfig.recursion_limit = config4.recursionLimit; + if (config4.runId != null) + pyConfig.run_id = config4.runId; + if (config4.runName != null) + pyConfig.run_name = config4.runName; + if (config4.tags != null) + pyConfig.tags = config4.tags; + return pyConfig; } - if (status === 404 || errorType === "FileNotFound") { - throw new LangSmithResourceNotFoundError(message, "file"); + const parentNs = config3.configurable?.checkpoint_ns; + const taskStates = {}; + for (const task2 of tasks) { + if (!((task2.subgraphs?.length) ? task2.subgraphs : [task2.proc]).find(findSubgraphPregel2)) + continue; + let taskNs = `${task2.name}:${task2.id}`; + if (parentNs) + taskNs = `${parentNs}|${taskNs}`; + taskStates[task2.id] = { configurable: { + thread_id: config3.configurable?.thread_id, + checkpoint_ns: taskNs + } }; } - throw new LangSmithSandboxError(message); + yield { + config: formatConfig(config3), + values: readChannels2(channels, streamChannels), + metadata, + next: tasks.map((task2) => task2.name), + tasks: tasksWithWrites2(tasks, pendingWrites, taskStates, outputKeys), + parentConfig: parentConfig ? formatConfig(parentConfig) : undefined + }; } -var init_helpers2 = __esm(() => { - init_errors8(); -}); - -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/command_handle.js -var CommandHandle; -var init_command_handle = __esm(() => { - init_errors8(); - CommandHandle = class CommandHandle { - constructor(messageStream, control, sandbox, options) { - Object.defineProperty(this, "_stream", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_control", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_sandbox", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_commandId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "_pid", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "_result", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "_stdoutParts", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "_stderrParts", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "_exhausted", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "_lastStdoutOffset", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_lastStderrOffset", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_started", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this._stream = messageStream; - this._control = control; - this._sandbox = sandbox; - this._lastStdoutOffset = options?.stdoutOffset ?? 0; - this._lastStderrOffset = options?.stderrOffset ?? 0; - if (options?.commandId) { - this._commandId = options.commandId; - this._started = true; - } else { - this._started = false; - } - } - async _ensureStarted() { - if (this._started) +function tasksWithWrites2(tasks, pendingWrites, states, outputKeys) { + return tasks.map((task2) => { + const error90 = pendingWrites.find(([id, n4]) => id === task2.id && n4 === "__error__")?.[2]; + const interrupts = pendingWrites.filter(([id, n4]) => id === task2.id && n4 === "__interrupt__").map(([, , v]) => v); + const result = (() => { + if (error90 || interrupts.length || !pendingWrites.length) return; - const firstResult = await this._stream.next(); - if (firstResult.done) { - throw new LangSmithSandboxOperationError("Command stream ended before 'started' message", "command"); - } - const firstMsg = firstResult.value; - if (firstMsg.type !== "started") { - throw new LangSmithSandboxOperationError(`Expected 'started' message, got '${firstMsg.type}'`, "command"); + const idx = pendingWrites.findIndex(([tid, n4]) => tid === task2.id && n4 === "__return__"); + if (idx >= 0) + return pendingWrites[idx][2]; + if (typeof outputKeys === "string") + return pendingWrites.find(([tid, n4]) => tid === task2.id && n4 === outputKeys)?.[2]; + if (Array.isArray(outputKeys)) { + const results = pendingWrites.filter(([tid, n4]) => tid === task2.id && outputKeys.includes(n4)).map(([, n4, v]) => [n4, v]); + if (!results.length) + return; + return mapTaskResultWrites2(results); } - this._commandId = firstMsg.command_id ?? null; - this._pid = firstMsg.pid ?? null; - this._started = true; - } - get commandId() { - return this._commandId; - } - get pid() { - return this._pid; + })(); + if (error90) + return { + id: task2.id, + name: task2.name, + path: task2.path, + error: error90, + interrupts, + result + }; + const taskState = states?.[task2.id]; + return { + id: task2.id, + name: task2.name, + path: task2.path, + interrupts, + ...taskState !== undefined ? { state: taskState } : {}, + result + }; + }); +} +function printStepCheckpoint2(step, channels, whitelist) { + console.log([ + `${wrap3(COLORS_MAP2.blue, `[${step}:checkpoint]`)}`, + `\x1B[1m State at the end of step ${step}:\x1B[0m +`, + JSON.stringify(readChannels2(channels, whitelist), null, 2) + ].join("")); +} +function printStepTasks2(step, nextTasks) { + const nTasks = nextTasks.length; + console.log([ + `${wrap3(COLORS_MAP2.blue, `[${step}:tasks]`)}`, + `\x1B[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1B[0m +`, + nextTasks.map((task2) => `- ${wrap3(COLORS_MAP2.green, String(task2.name))} -> ${JSON.stringify(task2.input, null, 2)}`).join(` +`) + ].join("")); +} +function printStepWrites2(step, writes, whitelist) { + const byChannel = {}; + for (const [channel, value] of writes) + if (whitelist.includes(channel)) { + if (!byChannel[channel]) + byChannel[channel] = []; + byChannel[channel].push(value); } - get result() { - return this._getResult(); + console.log([ + `${wrap3(COLORS_MAP2.blue, `[${step}:writes]`)}`, + `\x1B[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1B[0m +`, + Object.entries(byChannel).map(([name, vals]) => `- ${wrap3(COLORS_MAP2.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join(` +`) + ].join("")); +} +var COLORS_MAP2, wrap3 = (color2, text) => `${color2.start}${text}${color2.end}`; +var init_debug2 = __esm(() => { + init_constants5(); + init_io2(); + init_subgraph2(); + COLORS_MAP2 = { + blue: { + start: "\x1B[34m", + end: "\x1B[0m" + }, + green: { + start: "\x1B[32m", + end: "\x1B[0m" + }, + yellow: { + start: "\x1B[33;1m", + end: "\x1B[0m" } - async _getResult() { - if (this._result === null) { - for await (const _ of this) {} - } - if (this._result === null) { - throw new LangSmithSandboxOperationError("Command stream ended without exit message", "command"); - } - return this._result; + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/stream.js +function _stringifyAsDict2(obj) { + return JSON.stringify(obj, function(key, value) { + const rawValue2 = this[key]; + if (rawValue2 != null && typeof rawValue2 === "object" && "toDict" in rawValue2 && typeof rawValue2.toDict === "function") { + const { type, data } = rawValue2.toDict(); + return { + ...data, + type + }; } - async* _iterStream() { - await this._ensureStarted(); - if (this._exhausted) - return; - for await (const msg of this._stream) { - const msgType = msg.type; - if (msgType === "stdout" || msgType === "stderr") { - const chunk = { - stream: msgType, - data: msg.data, - offset: msg.offset ?? 0 - }; - if (msgType === "stdout") { - this._stdoutParts.push(msg.data); - } else { - this._stderrParts.push(msg.data); - } - yield chunk; - } else if (msgType === "exit") { - this._result = { - stdout: this._stdoutParts.join(""), - stderr: this._stderrParts.join(""), - exit_code: msg.exit_code ?? -1 + return value; + }); +} +function _serializeError2(error90) { + if (error90 instanceof Error) + return { + error: error90.name, + message: error90.message + }; + return { + error: "Error", + message: JSON.stringify(error90) + }; +} +function _isRunnableConfig2(config3) { + if (typeof config3 !== "object" || config3 == null) + return false; + return "configurable" in config3 && typeof config3.configurable === "object" && config3.configurable != null; +} +function _extractCheckpointFromConfig2(config3) { + if (!_isRunnableConfig2(config3) || !config3.configurable.thread_id) + return null; + return { + thread_id: config3.configurable.thread_id, + checkpoint_ns: config3.configurable.checkpoint_ns || "", + checkpoint_id: config3.configurable.checkpoint_id || null, + checkpoint_map: config3.configurable.checkpoint_map || null + }; +} +function _serializeConfig2(config3) { + if (_isRunnableConfig2(config3)) { + const configurable = Object.fromEntries(Object.entries(config3.configurable).filter(([key]) => !key.startsWith("__"))); + const newConfig = { + ...config3, + configurable + }; + delete newConfig.callbacks; + return newConfig; + } + return config3; +} +function _serializeCheckpoint2(payload) { + const result = { + ...payload, + checkpoint: _extractCheckpointFromConfig2(payload.config), + parent_checkpoint: _extractCheckpointFromConfig2(payload.parentConfig), + config: _serializeConfig2(payload.config), + parent_config: _serializeConfig2(payload.parentConfig), + tasks: payload.tasks.map((task2) => { + if (_isRunnableConfig2(task2.state)) { + const checkpoint = _extractCheckpointFromConfig2(task2.state); + if (checkpoint != null) { + const cloneTask = { + ...task2, + checkpoint }; - this._exhausted = true; - return; + delete cloneTask.state; + return cloneTask; } } - this._exhausted = true; + return task2; + }) + }; + delete result.parentConfig; + return result; +} +function toEventStream2(stream2) { + const encoder2 = new TextEncoder; + return new ReadableStream({ async start(controller) { + const enqueueChunk = (sse) => { + controller.enqueue(encoder2.encode(`event: ${sse.event} +data: ${_stringifyAsDict2(sse.data)} + +`)); + }; + try { + for await (const payload of stream2) { + const [ns3, mode, chunk] = payload; + let data = chunk; + if (mode === "debug") { + const debugChunk = chunk; + if (debugChunk.type === "checkpoint") + data = { + ...debugChunk, + payload: _serializeCheckpoint2(debugChunk.payload) + }; + } + if (mode === "checkpoints") + data = _serializeCheckpoint2(chunk); + enqueueChunk({ + event: ns3?.length ? `${mode}|${ns3.join("|")}` : mode, + data + }); + } + } catch (error90) { + enqueueChunk({ + event: "error", + data: _serializeError2(error90) + }); } - async* [Symbol.asyncIterator]() { - let reconnectAttempts = 0; - while (true) { - try { - for await (const chunk of this._iterStream()) { - reconnectAttempts = 0; - if (chunk.stream === "stdout") { - this._lastStdoutOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; - } else { - this._lastStderrOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; + controller.close(); + } }); +} +var IterableReadableStreamWithAbortSignal2, IterableReadableWritableStream2, StreamToolsHandler2; +var init_stream8 = __esm(() => { + init_constants5(); + init_stream(); + init_base2(); + IterableReadableStreamWithAbortSignal2 = class extends IterableReadableStream { + _abortController; + _innerReader; + constructor(readableStream, abortController) { + const reader = readableStream.getReader(); + const ac = abortController ?? new AbortController; + super({ start(controller) { + return pump3(); + function pump3() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; } - yield chunk; - } - return; - } catch (e) { - const eName = e != null && typeof e === "object" ? e.name : ""; - if (eName !== "LangSmithSandboxConnectionError" && eName !== "LangSmithSandboxServerReloadError") { - throw e; - } - if (this._control && this._control.killed) { - throw e; - } - reconnectAttempts++; - if (reconnectAttempts > CommandHandle.MAX_AUTO_RECONNECTS) { - throw new LangSmithSandboxConnectionError(`Lost connection ${reconnectAttempts} times in succession, giving up`); - } - const isHotReload = eName === "LangSmithSandboxServerReloadError"; - if (!isHotReload) { - const delay = Math.min(CommandHandle.BACKOFF_BASE * 2 ** (reconnectAttempts - 1), CommandHandle.BACKOFF_MAX); - await new Promise((r) => setTimeout(r, delay * 1000)); - } - if (this._commandId === null) { - throw e; - } - const newHandle = await this._sandbox.reconnect(this._commandId, { - stdoutOffset: this._lastStdoutOffset, - stderrOffset: this._lastStderrOffset + controller.enqueue(value); + return pump3(); }); - this._stream = newHandle._stream; - this._control = newHandle._control; - this._exhausted = false; } - } - } - kill() { - if (this._control) { - this._control.sendKill(); - } + } }); + this._abortController = ac; + this._innerReader = reader; } - sendInput(data) { - if (this._control) { - this._control.sendInput(data); - } + async cancel(reason) { + this._abortController.abort(reason); + this._innerReader.releaseLock(); } - get lastStdoutOffset() { - return this._lastStdoutOffset; + get signal() { + return this._abortController.signal; } - get lastStderrOffset() { - return this._lastStderrOffset; + }; + IterableReadableWritableStream2 = class extends IterableReadableStream { + modes; + controller; + passthroughFn; + _closed = false; + get closed() { + return this._closed; } - async reconnect() { - if (this._commandId === null) { - throw new LangSmithSandboxOperationError("Cannot reconnect: command ID not available", "reconnect"); - } - return this._sandbox.reconnect(this._commandId, { - stdoutOffset: this._lastStdoutOffset, - stderrOffset: this._lastStderrOffset + constructor(params) { + let streamControllerPromiseResolver; + const streamControllerPromise = new Promise((resolve2) => { + streamControllerPromiseResolver = resolve2; }); + super({ start: (controller) => { + streamControllerPromiseResolver(controller); + } }); + streamControllerPromise.then((controller) => { + this.controller = controller; + }); + this.passthroughFn = params.passthroughFn; + this.modes = params.modes; } - }; - Object.defineProperty(CommandHandle, "MAX_AUTO_RECONNECTS", { - enumerable: true, - configurable: true, - writable: true, - value: 5 - }); - Object.defineProperty(CommandHandle, "BACKOFF_BASE", { - enumerable: true, - configurable: true, - writable: true, - value: 0.5 - }); - Object.defineProperty(CommandHandle, "BACKOFF_MAX", { - enumerable: true, - configurable: true, - writable: true, - value: 8 - }); -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/constants.js -var require_constants4 = __commonJS((exports, module) => { - var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; - var hasBlob = typeof Blob !== "undefined"; - if (hasBlob) - BINARY_TYPES.push("blob"); - module.exports = { - BINARY_TYPES, - CLOSE_TIMEOUT: 30000, - EMPTY_BUFFER: Buffer.alloc(0), - GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", - hasBlob, - kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), - kListener: Symbol("kListener"), - kStatusCode: Symbol("status-code"), - kWebSocket: Symbol("websocket"), - NOOP: () => {} - }; -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/buffer-util.js -var require_buffer_util = __commonJS((exports, module) => { - var { EMPTY_BUFFER } = require_constants4(); - var FastBuffer = Buffer[Symbol.species]; - function concat3(list, totalLength) { - if (list.length === 0) - return EMPTY_BUFFER; - if (list.length === 1) - return list[0]; - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - for (let i = 0;i < list.length; i++) { - const buf = list[i]; - target.set(buf, offset); - offset += buf.length; - } - if (offset < totalLength) { - return new FastBuffer(target.buffer, target.byteOffset, offset); + push(chunk) { + this.passthroughFn?.(chunk); + this.controller.enqueue(chunk); } - return target; - } - function _mask(source, mask, output, offset, length) { - for (let i = 0;i < length; i++) { - output[offset + i] = source[i] ^ mask[i & 3]; + close() { + try { + this.controller.close(); + } catch {} finally { + this._closed = true; + } } - } - function _unmask(buffer, mask) { - for (let i = 0;i < buffer.length; i++) { - buffer[i] ^= mask[i & 3]; + error(e) { + this.controller.error(e); } - } - function toArrayBuffer(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; + }; + StreamToolsHandler2 = class extends BaseCallbackHandler { + name = "StreamToolsHandler"; + streamFn; + runs = {}; + constructor(streamFn) { + super(); + this.streamFn = streamFn; } - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); - } - function toBuffer(data) { - toBuffer.readOnly = true; - if (Buffer.isBuffer(data)) - return data; - let buf; - if (data instanceof ArrayBuffer) { - buf = new FastBuffer(data); - } else if (ArrayBuffer.isView(data)) { - buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); - } else { - buf = Buffer.from(data); - toBuffer.readOnly = false; + handleToolStart(_tool, input, runId, _parentRunId, tags, metadata, runName, toolCallId) { + if (!metadata || tags && tags.includes("langsmith:hidden")) + return; + const ns3 = metadata.langgraph_checkpoint_ns?.split("|") ?? []; + const info = { + ns: ns3, + toolCallId, + toolName: runName ?? "unknown", + input + }; + this.runs[runId] = info; + this.streamFn([ + ns3, + "tools", + { + event: "on_tool_start", + toolCallId: info.toolCallId, + name: info.toolName, + input + } + ]); } - return buf; - } - module.exports = { - concat: concat3, - mask: _mask, - toArrayBuffer, - toBuffer, - unmask: _unmask - }; - if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})(); - module.exports.mask = function(source, mask, output, offset, length) { - if (length < 48) - _mask(source, mask, output, offset, length); - else - bufferUtil.mask(source, mask, output, offset, length); - }; - module.exports.unmask = function(buffer, mask) { - if (buffer.length < 32) - _unmask(buffer, mask); - else - bufferUtil.unmask(buffer, mask); - }; - } catch (e) {} - } -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/limiter.js -var require_limiter = __commonJS((exports, module) => { - var kDone = Symbol("kDone"); - var kRun = Symbol("kRun"); - - class Limiter { - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; + handleToolEvent(chunk, runId) { + const info = this.runs[runId]; + if (!info) + return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_event", + toolCallId: info.toolCallId, + name: info.toolName, + data: chunk + } + ]); } - add(job) { - this.jobs.push(job); - this[kRun](); + handleToolEnd(output, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) + return; + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_end", + toolCallId: info.toolCallId, + name: info.toolName, + output + } + ]); } - [kRun]() { - if (this.pending === this.concurrency) + handleToolError(err, runId) { + const info = this.runs[runId]; + delete this.runs[runId]; + if (!info) return; - if (this.jobs.length) { - const job = this.jobs.shift(); - this.pending++; - job(this[kDone]); - } + this.streamFn([ + info.ns, + "tools", + { + event: "on_tool_error", + toolCallId: info.toolCallId, + name: info.toolName, + error: err + } + ]); } - } - module.exports = Limiter; + }; }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/permessage-deflate.js -var require_permessage_deflate = __commonJS((exports, module) => { - var zlib = __require("zlib"); - var bufferUtil = require_buffer_util(); - var Limiter = require_limiter(); - var { kStatusCode } = require_constants4(); - var FastBuffer = Buffer[Symbol.species]; - var TRAILER = Buffer.from([0, 0, 255, 255]); - var kPerMessageDeflate = Symbol("permessage-deflate"); - var kTotalLength = Symbol("total-length"); - var kCallback = Symbol("callback"); - var kBuffers = Symbol("buffers"); - var kError = Symbol("error"); - var zlibLimiter; - - class PerMessageDeflate { - constructor(options) { - this._options = options || {}; - this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; - this._maxPayload = this._options.maxPayload | 0; - this._isServer = !!this._options.isServer; - this._deflate = null; - this._inflate = null; - this.params = null; - if (!zlibLimiter) { - const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; - zlibLimiter = new Limiter(concurrency); - } - } - static get extensionName() { - return "permessage-deflate"; - } - offer() { - const params = {}; - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - return params; - } - accept(configurations) { - configurations = this.normalizeParams(configurations); - this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); - return this.params; - } - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - if (this._deflate) { - const callback = this._deflate[kCallback]; - this._deflate.close(); - this._deflate = null; - if (callback) { - callback(new Error("The deflate stream was closed while data was being processed")); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/loop.js +function createDuplexStream2(...streams) { + return new IterableReadableWritableStream2({ + passthroughFn: (value) => { + for (const stream2 of streams) + if (stream2.modes.has(value[1])) + stream2.push(value); + }, + modes: new Set(streams.flatMap((s) => Array.from(s.modes))) + }); +} +var INPUT_DONE2, INPUT_RESUMING2, DEFAULT_LOOP_LIMIT2 = 25, AsyncBatchedCache2, PregelLoop3 = class PregelLoop4 { + input; + output; + config; + checkpointer; + checkpointerGetNextVersion; + channels; + checkpoint; + checkpointIdSaved; + checkpointConfig; + checkpointMetadata; + checkpointNamespace; + checkpointPendingWrites = []; + checkpointPreviousVersions; + step; + stop; + durability; + outputKeys; + streamKeys; + nodes; + skipDoneTasks; + prevCheckpointConfig; + updatedChannels; + status = "pending"; + tasks = {}; + stream; + checkpointerPromises = /* @__PURE__ */ new Set; + isNested; + _checkpointerChainedPromise = Promise.resolve(); + _trackCheckpointerPromise(promise3) { + const tracked = promise3.then((value) => { + this.checkpointerPromises.delete(tracked); + return value; + }, (error90) => { + throw error90; + }); + this.checkpointerPromises.add(tracked); + } + store; + cache; + manager; + interruptAfter; + interruptBefore; + toInterrupt = []; + debug = false; + triggerToNodes; + get isResuming() { + let hasChannelVersions = false; + if ("__start__" in this.checkpoint.channel_versions) + hasChannelVersions = true; + else + for (const chan in this.checkpoint.channel_versions) + if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { + hasChannelVersions = true; + break; } - } + const configIsResuming = this.config.configurable?.["__pregel_resuming"] !== undefined && this.config.configurable?.["__pregel_resuming"]; + const inputIsNullOrUndefined = this.input === null || this.input === undefined; + const inputIsCommandResuming = isCommand2(this.input) && this.input.resume != null; + const inputIsResuming = this.input === INPUT_RESUMING2; + const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== undefined && this.checkpointMetadata?.run_id !== undefined && this.config.metadata.run_id === this.checkpointMetadata?.run_id; + return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); + } + constructor(params) { + this.input = params.input; + this.checkpointer = params.checkpointer; + if (this.checkpointer !== undefined) + this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); + else + this.checkpointerGetNextVersion = increment2; + this.checkpoint = params.checkpoint; + this.checkpointMetadata = params.checkpointMetadata; + this.checkpointPreviousVersions = params.checkpointPreviousVersions; + this.channels = params.channels; + this.checkpointPendingWrites = params.checkpointPendingWrites; + this.step = params.step; + this.stop = params.stop; + this.config = params.config; + this.checkpointConfig = params.checkpointConfig; + this.isNested = params.isNested; + this.manager = params.manager; + this.outputKeys = params.outputKeys; + this.streamKeys = params.streamKeys; + this.nodes = params.nodes; + this.skipDoneTasks = params.skipDoneTasks; + this.store = params.store; + this.cache = params.cache ? new AsyncBatchedCache2(params.cache) : undefined; + this.stream = params.stream; + this.checkpointNamespace = params.checkpointNamespace; + this.prevCheckpointConfig = params.prevCheckpointConfig; + this.interruptAfter = params.interruptAfter; + this.interruptBefore = params.interruptBefore; + this.durability = params.durability; + this.debug = params.debug; + this.triggerToNodes = params.triggerToNodes; + } + static async initialize(params) { + let { config: config3, stream: stream2 } = params; + if (stream2 !== undefined && config3.configurable?.["__pregel_stream"] !== undefined) + stream2 = createDuplexStream2(stream2, config3.configurable[CONFIG_KEY_STREAM2]); + const skipDoneTasks = config3.configurable ? !("checkpoint_id" in config3.configurable) : true; + const scratchpad = config3.configurable?.[CONFIG_KEY_SCRATCHPAD2]; + if (config3.configurable && scratchpad) { + if (scratchpad.subgraphCounter > 0) + config3 = patchConfigurable4(config3, { [CONFIG_KEY_CHECKPOINT_NS2]: [config3.configurable[CONFIG_KEY_CHECKPOINT_NS2], scratchpad.subgraphCounter.toString()].join("|") }); + scratchpad.subgraphCounter += 1; } - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { - return false; - } - return true; + const isNested = CONFIG_KEY_READ2 in (config3.configurable ?? {}); + if (!isNested && config3.configurable?.checkpoint_ns !== undefined && config3.configurable?.checkpoint_ns !== "") + config3 = patchConfigurable4(config3, { + checkpoint_ns: "", + checkpoint_id: undefined }); - if (!accepted) { - throw new Error("None of the extension offers can be accepted"); + let checkpointConfig = config3; + if (config3.configurable?.["checkpoint_map"] !== undefined && config3.configurable?.["checkpoint_map"]?.[config3.configurable?.checkpoint_ns]) + checkpointConfig = patchConfigurable4(config3, { checkpoint_id: config3.configurable[CONFIG_KEY_CHECKPOINT_MAP2][config3.configurable?.checkpoint_ns] }); + const checkpointNamespace = config3.configurable?.checkpoint_ns?.split("|") ?? []; + const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { + config: config3, + checkpoint: emptyCheckpoint(), + metadata: { + source: "input", + step: -2, + parents: {} + }, + pendingWrites: [] + }; + checkpointConfig = { + ...config3, + ...saved.config, + configurable: { + checkpoint_ns: "", + ...config3.configurable, + ...saved.config.configurable } - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; + }; + const prevCheckpointConfig = saved.parentConfig; + const checkpoint = copyCheckpoint(saved.checkpoint); + const checkpointMetadata = { ...saved.metadata }; + const checkpointPendingWrites = saved.pendingWrites ?? []; + const channels = emptyChannels2(params.channelSpecs, checkpoint); + const step = (checkpointMetadata.step ?? 0) + 1; + const stop = step + (config3.recursionLimit ?? DEFAULT_LOOP_LIMIT2) + 1; + const checkpointPreviousVersions = { ...checkpoint.channel_versions }; + const store = params.store ? new AsyncBatchedStore(params.store) : undefined; + if (store) + await store.start(); + return new PregelLoop4({ + input: params.input, + config: config3, + checkpointer: params.checkpointer, + checkpoint, + checkpointMetadata, + checkpointConfig, + prevCheckpointConfig, + checkpointNamespace, + channels, + isNested, + manager: params.manager, + skipDoneTasks, + step, + stop, + checkpointPreviousVersions, + checkpointPendingWrites, + outputKeys: params.outputKeys ?? [], + streamKeys: params.streamKeys ?? [], + nodes: params.nodes, + stream: stream2, + store, + cache: params.cache, + interruptAfter: params.interruptAfter, + interruptBefore: params.interruptBefore, + durability: params.durability, + debug: params.debug, + triggerToNodes: params.triggerToNodes + }); + } + _checkpointerPutAfterPrevious(input) { + this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { + return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); + }); + this._trackCheckpointerPromise(this._checkpointerChainedPromise); + } + putWrites(taskId, writes) { + let writesCopy = writes; + if (writesCopy.length === 0) + return; + if (writesCopy.every(([key]) => (key in WRITES_IDX_MAP))) + writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); + let hasUntrackedChannels = false; + for (const key in this.channels) + if (Object.prototype.hasOwnProperty.call(this.channels, key)) { + if (this.channels[key].lc_graph_name === "UntrackedValue") { + hasUntrackedChannels = true; + break; + } } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; + let writesToSave = writesCopy; + if (hasUntrackedChannels) + writesToSave = writesCopy.filter(([c]) => { + const channel = this.channels[c]; + return !channel || channel.lc_graph_name !== "UntrackedValue"; + }).map(([c, v]) => { + if (c === "__pregel_tasks" && _isSend2(v)) + return [c, sanitizeUntrackedValuesInSend2(v, this.channels)]; + return [c, v]; + }); + this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); + for (const [c, v] of writesToSave) + this.checkpointPendingWrites.push([ + taskId, + c, + v + ]); + const config3 = patchConfigurable4(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID2]: this.checkpoint.id + }); + if (this.durability !== "exit" && this.checkpointer != null) + this._trackCheckpointerPromise(this.checkpointer.putWrites(config3, writesToSave, taskId)); + if (this.tasks) + this._outputWrites(taskId, writesCopy); + if (!writes.length || !this.cache || !this.tasks) + return; + const task2 = this.tasks[taskId]; + if (task2 == null || task2.cache_key == null) + return; + if (writes[0][0] === "__error__" || writes[0][0] === "__interrupt__") + return; + this.cache.set([{ + key: [task2.cache_key.ns, task2.cache_key.key], + value: task2.writes, + ttl: task2.cache_key.ttl + }]); + } + _outputWrites(taskId, writes, cached3 = false) { + const task2 = this.tasks[taskId]; + if (task2 !== undefined) { + if (task2.config !== undefined && (task2.config.tags ?? []).includes("langsmith:hidden")) + return; + if (writes.length > 0) { + if (writes[0][0] === "__interrupt__") { + if (task2.path?.[0] === "__pregel_push" && task2.path?.[task2.path.length - 1] === true) + return; + const interruptWrites = writes.filter((w) => w[0] === INTERRUPT3).flatMap((w) => w[1]); + this._emit([["updates", { [INTERRUPT3]: interruptWrites }], ["values", { [INTERRUPT3]: interruptWrites }]]); + } else if (writes[0][0] !== "__error__") + this._emit(gatherIteratorSync2(prefixGenerator2(mapOutputUpdates2(this.outputKeys, [[task2, writes]], cached3), "updates"))); } - if (typeof opts.serverMaxWindowBits === "number") { - accepted.server_max_window_bits = opts.serverMaxWindowBits; + if (!cached3) + this._emit(gatherIteratorSync2(prefixGenerator2(mapDebugTaskResults2([[task2, writes]], this.streamKeys), "tasks"))); + } + } + async _matchCachedWrites() { + if (!this.cache) + return []; + const matched = []; + const serializeKey = ([ns3, key]) => { + return `ns:${ns3.join(",")}|key:${key}`; + }; + const keys = []; + const keyMap = {}; + for (const task2 of Object.values(this.tasks)) + if (task2.cache_key != null && !task2.writes.length) { + keys.push([task2.cache_key.ns, task2.cache_key.key]); + keyMap[serializeKey([task2.cache_key.ns, task2.cache_key.key])] = task2; } - if (typeof opts.clientMaxWindowBits === "number") { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { - delete accepted.client_max_window_bits; + if (keys.length === 0) + return []; + const cache2 = await this.cache.get(keys); + for (const { key, value } of cache2) { + const task2 = keyMap[serializeKey(key)]; + if (task2 != null) { + task2.writes.push(...value); + matched.push({ + task: task2, + result: value + }); } - return accepted; } - acceptAsClient(response) { - const params = response[0]; - if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === "number") { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { - throw new Error('Unexpected or invalid parameter "client_max_window_bits"'); + return matched; + } + async tick(params) { + if (this.store && !this.store.isRunning) + await this.store?.start(); + const { inputKeys = [] } = params; + if (this.status !== "pending") + throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); + if (![INPUT_DONE2, INPUT_RESUMING2].includes(this.input)) + await this._first(inputKeys); + else if (this.toInterrupt.length > 0) { + this.status = "interrupt_before"; + throw new GraphInterrupt2; + } else if (Object.values(this.tasks).every((task2) => task2.writes.length > 0)) { + const writes = Object.values(this.tasks).flatMap((t) => t.writes); + this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + const valuesOutput = await gatherIterator2(prefixGenerator2(mapOutputValues2(this.outputKeys, writes, this.channels), "values")); + this.checkpointPendingWrites = []; + await this._putCheckpoint({ source: "loop" }); + this._emitValuesWithCheckpointMeta(valuesOutput); + if (shouldInterrupt2(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { + this.status = "interrupt_after"; + throw new GraphInterrupt2; } - return params; + if (this.config.configurable?.["__pregel_resuming"] !== undefined) + delete this.config.configurable?.[CONFIG_KEY_RESUMING2]; + } else + return false; + if (this.step > this.stop) { + this.status = "out_of_steps"; + return false; } - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - value = value[0]; - if (key === "client_max_window_bits") { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError(`Invalid value for parameter "${key}": ${value}`); - } - value = num; - } else if (!this._isServer) { - throw new TypeError(`Invalid value for parameter "${key}": ${value}`); - } - } else if (key === "server_max_window_bits") { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError(`Invalid value for parameter "${key}": ${value}`); - } - value = num; - } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { - if (value !== true) { - throw new TypeError(`Invalid value for parameter "${key}": ${value}`); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - params[key] = value; - }); - }); - return configurations; + this.tasks = _prepareNextTasks2(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { + step: this.step, + checkpointer: this.checkpointer, + isResuming: this.isResuming, + manager: this.manager, + store: this.store, + stream: this.stream, + triggerToNodes: this.triggerToNodes, + updatedChannels: this.updatedChannels + }); + if (this.checkpointer) + this._emit(await gatherIterator2(prefixGenerator2(mapDebugCheckpoint2(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); + if (Object.values(this.tasks).length === 0) { + this.status = "done"; + return false; } - decompress(data, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); + if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__interrupt__" || k === "__resume__") + continue; + const task2 = Object.values(this.tasks).find((t) => t.id === tid); + if (task2) + task2.writes.push([k, v]); + } + for (const task2 of Object.values(this.tasks)) + if (task2.writes.length > 0) + this._outputWrites(task2.id, task2.writes, true); } - compress(data, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); + if (Object.values(this.tasks).every((task2) => task2.writes.length > 0)) + return this.tick({ inputKeys }); + if (shouldInterrupt2(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { + this.status = "interrupt_before"; + throw new GraphInterrupt2; } - _decompress(data, fin, callback) { - const endpoint = this._isServer ? "client" : "server"; - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on("error", inflateOnError); - this._inflate.on("data", inflateOnData); - } - this._inflate[kCallback] = callback; - this._inflate.write(data); - if (fin) - this._inflate.write(TRAILER); - this._inflate.flush(() => { - const err = this._inflate[kError]; - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]); - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - callback(null, data2); - }); + const debugOutput = await gatherIterator2(prefixGenerator2(mapDebugTasks2(Object.values(this.tasks)), "tasks")); + this._emit(debugOutput); + return true; + } + async finishAndHandleError(error90) { + if (this.durability === "exit" && (!this.isNested || typeof error90 !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(":")))) { + this._putCheckpoint(this.checkpointMetadata); + this._flushPendingWrites(); } - _compress(data, fin, callback) { - const endpoint = this._isServer ? "server" : "client"; - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - this._deflate.on("data", deflateOnData); + const suppress = this._suppressInterrupt(error90); + if (suppress || error90 === undefined) + this.output = readChannels2(this.channels, this.outputKeys); + if (suppress) { + if (this.tasks !== undefined && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task2) => task2.writes.length > 0)) { + this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + this._emitValuesWithCheckpointMeta(gatherIteratorSync2(prefixGenerator2(mapOutputValues2(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); } - this._deflate[kCallback] = callback; - this._deflate.write(data); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - return; - } - let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]); - if (fin) { - data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); - } - this._deflate[kCallback] = null; - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - callback(null, data2); - }); + if (isGraphInterrupt2(error90) && !error90.interrupts.length) + this._emit([["updates", { [INTERRUPT3]: [] }], ["values", { [INTERRUPT3]: [] }]]); } + return suppress; } - module.exports = PerMessageDeflate; - function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; - } - function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { - this[kBuffers].push(chunk); + async acceptPush(task2, writeIdx, call3) { + if (this.interruptAfter?.length > 0 && shouldInterrupt2(this.checkpoint, this.interruptAfter, [task2])) { + this.toInterrupt.push(task2); return; } - this[kError] = new RangeError("Max payload size exceeded"); - this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; - this[kError][kStatusCode] = 1009; - this.removeListener("data", inflateOnData); - this.reset(); - } - function inflateOnError(err) { - this[kPerMessageDeflate]._inflate = null; - if (this[kError]) { - this[kCallback](this[kError]); + const pushed = _prepareSingleTask2([ + PUSH2, + task2.path ?? [], + writeIdx, + task2.id, + call3 + ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task2.config ?? {}, true, { + step: this.step, + checkpointer: this.checkpointer, + manager: this.manager, + store: this.store, + stream: this.stream + }); + if (!pushed) + return; + if (this.interruptBefore?.length > 0 && shouldInterrupt2(this.checkpoint, this.interruptBefore, [pushed])) { + this.toInterrupt.push(pushed); return; } - err[kStatusCode] = 1007; - this[kCallback](err); + this._emit(gatherIteratorSync2(prefixGenerator2(mapDebugTasks2([pushed]), "tasks"))); + if (this.debug) + printStepTasks2(this.step, [pushed]); + this.tasks[pushed.id] = pushed; + if (this.skipDoneTasks) + this._matchWrites({ [pushed.id]: pushed }); + const tasks = await this._matchCachedWrites(); + for (const { task: task3 } of tasks) + this._outputWrites(task3.id, task3.writes, true); + return pushed; } -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/validation.js -var require_validation = __commonJS((exports, module) => { - var { isUtf8 } = __require("buffer"); - var { hasBlob } = require_constants4(); - var tokenChars = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 1, - 1, - 0, - 1, - 1, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 1, - 0, - 1, - 0, - 1, - 0 - ]; - function isValidStatusCode(code) { - return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999; + _suppressInterrupt(e) { + return isGraphInterrupt2(e) && !this.isNested; } - function _isValidUTF8(buf) { - const len = buf.length; - let i = 0; - while (i < len) { - if ((buf[i] & 128) === 0) { - i++; - } else if ((buf[i] & 224) === 192) { - if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { - return false; - } - i += 2; - } else if ((buf[i] & 240) === 224) { - if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) { - return false; - } - i += 3; - } else if ((buf[i] & 248) === 240) { - if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { - return false; + async _first(inputKeys) { + const { configurable } = this.config; + const scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD2]; + if (scratchpad && scratchpad.nullResume !== undefined) + this.putWrites(NULL_TASK_ID2, [[RESUME3, scratchpad.nullResume]]); + if (isCommand2(this.input)) { + const hasResume = this.input.resume != null; + if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH32)) { + this.config.configurable ??= {}; + this.config.configurable[CONFIG_KEY_RESUME_MAP2] = this.input.resume; + } + if (hasResume && this.checkpointer == null) + throw new Error("Cannot use Command(resume=...) without checkpointer"); + const writes = {}; + for (const [tid, key, value] of mapCommand2(this.input, this.checkpointPendingWrites)) { + writes[tid] ??= []; + writes[tid].push([key, value]); + } + if (Object.keys(writes).length === 0) + throw new EmptyInputError2("Received empty Command input"); + for (const [tid, ws] of Object.entries(writes)) + this.putWrites(tid, ws); + } + const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites2(this.checkpoint, this.channels, [{ + name: INPUT2, + writes: nullWrites, + triggers: [] + }], this.checkpointerGetNextVersion, this.triggerToNodes); + const isCommandUpdateOrGoto = isCommand2(this.input) && nullWrites.length > 0; + if (this.isResuming || isCommandUpdateOrGoto) { + for (const channelName in this.channels) { + if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) + continue; + if (this.checkpoint.channel_versions[channelName] !== undefined) { + const version6 = this.checkpoint.channel_versions[channelName]; + this.checkpoint.versions_seen[INTERRUPT3] = { + ...this.checkpoint.versions_seen[INTERRUPT3], + [channelName]: version6 + }; } - i += 4; - } else { - return false; } + const valuesOutput = await gatherIterator2(prefixGenerator2(mapOutputValues2(this.outputKeys, true, this.channels), "values")); + if (this.isResuming) + this.input = INPUT_RESUMING2; + else if (isCommandUpdateOrGoto) { + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE2; + } + this._emitValuesWithCheckpointMeta(valuesOutput); + } else { + const inputWrites = await gatherIterator2(mapInput2(inputKeys, this.input)); + if (inputWrites.length > 0) { + const discardTasks = _prepareNextTasks2(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); + this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ + name: INPUT2, + writes: inputWrites, + triggers: [] + }]), this.checkpointerGetNextVersion, this.triggerToNodes); + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE2; + } else if (!("__pregel_resuming" in (this.config.configurable ?? {}))) + throw new EmptyInputError2(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); + else + this.input = INPUT_DONE2; } - return true; + if (!this.isNested) + this.config = patchConfigurable4(this.config, { [CONFIG_KEY_RESUMING2]: this.isResuming }); } - function isBlob(value) { - return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); + _emit(values) { + for (const entry of values) { + const [mode, payload, meta3] = entry; + if (this.stream.modes.has(mode)) + this.stream.push([ + this.checkpointNamespace, + mode, + payload, + meta3 + ]); + if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { + const step = mode === "checkpoints" ? this.step - 1 : this.step; + const timestamp = (/* @__PURE__ */ new Date()).toISOString(); + const type = (() => { + if (mode === "checkpoints") + return "checkpoint"; + else if (typeof payload === "object" && payload != null && "result" in payload) + return "task_result"; + else + return "task"; + })(); + this.stream.push([ + this.checkpointNamespace, + "debug", + { + step, + type, + timestamp, + payload + } + ]); + } + } } - module.exports = { - isBlob, - isValidStatusCode, - isValidUTF8: _isValidUTF8, - tokenChars - }; - if (isUtf8) { - module.exports.isValidUTF8 = function(buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + _currentCheckpointMeta() { + if (!this.checkpointMetadata || !this.checkpoint?.id) + return; + const parent_id = this.prevCheckpointConfig?.configurable?.checkpoint_id; + return { checkpoint: { + id: this.checkpoint.id, + ...parent_id ? { parent_id } : {}, + step: this.checkpointMetadata.step, + source: this.checkpointMetadata.source + } }; + } + _emitValuesWithCheckpointMeta(entries) { + const meta3 = this._currentCheckpointMeta(); + if (!meta3) { + this._emit(entries); + return; + } + this._emit(entries.map(([mode, payload]) => mode === "values" ? [ + mode, + payload, + meta3 + ] : [mode, payload])); + } + _putCheckpoint(inputMetadata) { + const exiting = this.checkpointMetadata === inputMetadata; + const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); + const storeCheckpoint = (checkpoint) => { + this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : undefined; + this.checkpointConfig = patchConfigurable4(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "" }); + const channelVersions = { ...this.checkpoint.channel_versions }; + const newVersions = getNewChannelVersions2(this.checkpointPreviousVersions, channelVersions); + this.checkpointPreviousVersions = channelVersions; + this._checkpointerPutAfterPrevious({ + config: { ...this.checkpointConfig }, + checkpoint: copyCheckpoint(checkpoint), + metadata: { ...this.checkpointMetadata }, + newVersions + }); + this.checkpointConfig = { + ...this.checkpointConfig, + configurable: { + ...this.checkpointConfig.configurable, + checkpoint_id: this.checkpoint.id + } + }; }; - } else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})(); - module.exports.isValidUTF8 = function(buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + if (!exiting) + this.checkpointMetadata = { + ...inputMetadata, + step: this.step, + parents: this.config.configurable?.["checkpoint_map"] ?? {} }; - } catch (e) {} + this.checkpoint = createCheckpoint2(this.checkpoint, doCheckpoint ? this.channels : undefined, this.step, exiting ? { id: this.checkpoint.id } : undefined); + if (doCheckpoint) + storeCheckpoint(this.checkpoint); + if (!exiting) + this.step += 1; } -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/receiver.js -var require_receiver = __commonJS((exports, module) => { - var { Writable } = __require("stream"); - var PerMessageDeflate = require_permessage_deflate(); - var { - BINARY_TYPES, - EMPTY_BUFFER, - kStatusCode, - kWebSocket - } = require_constants4(); - var { concat: concat3, toArrayBuffer, unmask } = require_buffer_util(); - var { isValidStatusCode, isValidUTF8 } = require_validation(); - var FastBuffer = Buffer[Symbol.species]; - var GET_INFO = 0; - var GET_PAYLOAD_LENGTH_16 = 1; - var GET_PAYLOAD_LENGTH_64 = 2; - var GET_MASK = 3; - var GET_DATA = 4; - var INFLATING = 5; - var DEFER_EVENT = 6; - - class Receiver extends Writable { - constructor(options = {}) { + _flushPendingWrites() { + if (this.checkpointer == null) + return; + if (this.checkpointPendingWrites.length === 0) + return; + const config3 = patchConfigurable4(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID2]: this.checkpoint.id + }); + const byTask = {}; + for (const [tid, key, value] of this.checkpointPendingWrites) { + byTask[tid] ??= []; + byTask[tid].push([key, value]); + } + for (const [tid, ws] of Object.entries(byTask)) + this._trackCheckpointerPromise(this.checkpointer.putWrites(config3, ws, tid)); + } + _matchWrites(tasks) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === "__error__" || k === "__interrupt__" || k === "__resume__") + continue; + const task2 = Object.values(tasks).find((t) => t.id === tid); + if (task2) + task2.writes.push([k, v]); + } + for (const task2 of Object.values(tasks)) + if (task2.writes.length > 0) + this._outputWrites(task2.id, task2.writes, true); + } +}; +var init_loop2 = __esm(() => { + init_constants5(); + init_errors9(); + init_base16(); + init_utils14(); + init_hash4(); + init_io2(); + init_utils15(); + init_algo2(); + init_debug2(); + init_stream8(); + init_dist3(); + INPUT_DONE2 = Symbol.for("INPUT_DONE"); + INPUT_RESUMING2 = Symbol.for("INPUT_RESUMING"); + AsyncBatchedCache2 = class extends BaseCache2 { + cache; + queue = Promise.resolve(); + constructor(cache2) { super(); - this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true; - this._binaryType = options.binaryType || BINARY_TYPES[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket] = undefined; - this._bufferedBytes = 0; - this._buffers = []; - this._compressed = false; - this._payloadLength = 0; - this._mask = undefined; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - this._errored = false; - this._loop = false; - this._state = GET_INFO; + this.cache = cache2; } - _write(chunk, encoding, cb) { - if (this._opcode === 8 && this._state == GET_INFO) - return cb(); - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); + async get(keys) { + return this.enqueueOperation("get", keys); } - consume(n3) { - this._bufferedBytes -= n3; - if (n3 === this._buffers[0].length) - return this._buffers.shift(); - if (n3 < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n3, buf.length - n3); - return new FastBuffer(buf.buffer, buf.byteOffset, n3); - } - const dst = Buffer.allocUnsafe(n3); - do { - const buf = this._buffers[0]; - const offset = dst.length - n3; - if (n3 >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset); - this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n3, buf.length - n3); - } - n3 -= buf.length; - } while (n3 > 0); - return dst; + async set(pairs) { + return this.enqueueOperation("set", pairs); } - startLoop(cb) { - this._loop = true; - do { - switch (this._state) { - case GET_INFO: - this.getInfo(cb); - break; - case GET_PAYLOAD_LENGTH_16: - this.getPayloadLength16(cb); - break; - case GET_PAYLOAD_LENGTH_64: - this.getPayloadLength64(cb); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - this.getData(cb); - break; - case INFLATING: - case DEFER_EVENT: - this._loop = false; - return; - } - } while (this._loop); - if (!this._errored) - cb(); + async clear(namespaces) { + return this.enqueueOperation("clear", namespaces); } - getInfo(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - const buf = this.consume(2); - if ((buf[0] & 48) !== 0) { - const error51 = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"); - cb(error51); - return; - } - const compressed = (buf[0] & 64) === 64; - if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { - const error51 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); - cb(error51); - return; - } - this._fin = (buf[0] & 128) === 128; - this._opcode = buf[0] & 15; - this._payloadLength = buf[1] & 127; - if (this._opcode === 0) { - if (compressed) { - const error51 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); - cb(error51); - return; - } - if (!this._fragmented) { - const error51 = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"); - cb(error51); - return; - } - this._opcode = this._fragmented; - } else if (this._opcode === 1 || this._opcode === 2) { - if (this._fragmented) { - const error51 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"); - cb(error51); - return; - } - this._compressed = compressed; - } else if (this._opcode > 7 && this._opcode < 11) { - if (!this._fin) { - const error51 = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"); - cb(error51); - return; - } - if (compressed) { - const error51 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); - cb(error51); - return; - } - if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { - const error51 = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"); - cb(error51); - return; - } - } else { - const error51 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"); - cb(error51); + async stop() { + await this.queue; + } + enqueueOperation(type, ...args) { + const newPromise = this.queue.then(() => { + return this.cache[type](...args); + }); + this.queue = newPromise.then(() => { return; - } - if (!this._fin && !this._fragmented) - this._fragmented = this._opcode; - this._masked = (buf[1] & 128) === 128; - if (this._isServer) { - if (!this._masked) { - const error51 = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"); - cb(error51); - return; - } - } else if (this._masked) { - const error51 = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"); - cb(error51); + }, () => { return; - } - if (this._payloadLength === 126) - this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) - this._state = GET_PAYLOAD_LENGTH_64; - else - this.haveLength(cb); + }); + return newPromise; } - getPayloadLength16(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - this._payloadLength = this.consume(2).readUInt16BE(0); - this.haveLength(cb); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/messages.js +function isChatGenerationChunk3(x) { + return isBaseMessage(x?.message); +} +function normalizeStreamMetadata2(metadata, tags, name) { + if (!metadata) + return; + const streamNamespace = metadata.langgraph_checkpoint_ns; + const checkpointNs = metadata.checkpoint_ns; + const namespace = streamNamespace ?? checkpointNs; + if (!namespace) + return; + return [namespace.split("|"), { + tags, + name, + ...metadata + }]; +} +var StreamMessagesHandler2; +var init_messages6 = __esm(() => { + init_constants5(); + init_base2(); + init_messages(); + StreamMessagesHandler2 = class extends BaseCallbackHandler { + name = "StreamMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + emittedChatModelRunIds = {}; + stableMessageIdMap = {}; + lc_prefer_streaming = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; } - getPayloadLength64(cb) { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - if (num > Math.pow(2, 53 - 32) - 1) { - const error51 = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"); - cb(error51); + _emit(meta3, message, runId, dedupe = false) { + if (dedupe && message.id !== undefined && this.seen[message.id] !== undefined) return; - } - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - this.haveLength(cb); - } - haveLength(cb) { - if (this._payloadLength && this._opcode < 8) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - const error51 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"); - cb(error51); - return; + let messageId = message.id; + if (runId != null) + if (isToolMessage(message)) + messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) + messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; } - if (this._masked) - this._state = GET_MASK; - else - this._state = GET_DATA; + if (message.id != null) + this.seen[message.id] = message; + this.streamFn([ + meta3[0], + "messages", + [message, meta3[1]] + ]); } - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - this._mask = this.consume(4); - this._state = GET_DATA; + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) + this.metadatas[runId] = normalizeStreamMetadata2(metadata, tags, name); } - getData(cb) { - let data = EMPTY_BUFFER; - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - data = this.consume(this._payloadLength); - if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { - unmask(data, this._mask); - } - } - if (this._opcode > 7) { - this.controlMessage(data, cb); - return; - } - if (this._compressed) { - this._state = INFLATING; - this.decompress(data, cb); + handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { + const chunk = fields?.chunk; + this.emittedChatModelRunIds[runId] = true; + if (this.metadatas[runId] !== undefined) + if (isChatGenerationChunk3(chunk)) + this._emit(this.metadatas[runId], chunk.message, runId); + else + this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); + } + handleLLMEnd(output, runId) { + if (this.metadatas[runId] === undefined) return; + if (!this.emittedChatModelRunIds[runId]) { + const chatGeneration = output.generations?.[0]?.[0]; + if (isBaseMessage(chatGeneration?.message)) + this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); + delete this.emittedChatModelRunIds[runId]; } - if (data.length) { - this._messageLength = this._totalPayloadLength; - this._fragments.push(data); - } - this.dataMessage(cb); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; } - decompress(data, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - perMessageDeflate.decompress(data, this._fin, (err, buf) => { - if (err) - return cb(err); - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - const error51 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"); - cb(error51); - return; - } - this._fragments.push(buf); - } - this.dataMessage(cb); - if (this._state === GET_INFO) - this.startLoop(cb); - }); + handleLLMError(_err, runId) { + delete this.metadatas[runId]; } - dataMessage(cb) { - if (!this._fin) { - this._state = GET_INFO; - return; - } - const messageLength = this._messageLength; - const fragments = this._fragments; - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - if (this._opcode === 2) { - let data; - if (this._binaryType === "nodebuffer") { - data = concat3(fragments, messageLength); - } else if (this._binaryType === "arraybuffer") { - data = toArrayBuffer(concat3(fragments, messageLength)); - } else if (this._binaryType === "blob") { - data = new Blob(fragments); - } else { - data = fragments; - } - if (this._allowSynchronousEvents) { - this.emit("message", data, true); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", data, true); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } else { - const buf = concat3(fragments, messageLength); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error51 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"); - cb(error51); - return; - } - if (this._state === INFLATING || this._allowSynchronousEvents) { - this.emit("message", buf, false); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit("message", buf, false); - this._state = GET_INFO; - this.startLoop(cb); - }); + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = normalizeStreamMetadata2(metadata, tags, name); + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) + if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) + this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) + if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) + this.seen[item.id] = item; + } } } } - controlMessage(data, cb) { - if (this._opcode === 8) { - if (data.length === 0) { - this._loop = false; - this.emit("conclude", 1005, EMPTY_BUFFER); - this.end(); - } else { - const code = data.readUInt16BE(0); - if (!isValidStatusCode(code)) { - const error51 = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"); - cb(error51); - return; - } - const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2); - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error51 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"); - cb(error51); - return; - } - this._loop = false; - this.emit("conclude", code, buf); - this.end(); + handleChainEnd(outputs, runId) { + const metadata = this.metadatas[runId]; + delete this.metadatas[runId]; + if (metadata !== undefined) { + if (isBaseMessage(outputs)) + this._emit(metadata, outputs, runId, true); + else if (Array.isArray(outputs)) { + for (const value of outputs) + if (isBaseMessage(value)) + this._emit(metadata, value, runId, true); + } else if (outputs != null && typeof outputs === "object") { + for (const value of Object.values(outputs)) + if (isBaseMessage(value)) + this._emit(metadata, value, runId, true); + else if (Array.isArray(value)) { + for (const item of value) + if (isBaseMessage(item)) + this._emit(metadata, item, runId, true); + } } - this._state = GET_INFO; - return; - } - if (this._allowSynchronousEvents) { - this.emit(this._opcode === 9 ? "ping" : "pong", data); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit(this._opcode === 9 ? "ping" : "pong", data); - this._state = GET_INFO; - this.startLoop(cb); - }); } } - createError(ErrorCtor, message, prefix, statusCode, errorCode) { - this._loop = false; - this._errored = true; - const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message); - Error.captureStackTrace(err, this.createError); - err.code = errorCode; - err[kStatusCode] = statusCode; - return err; + handleChainError(_err, runId) { + delete this.metadatas[runId]; } - } - module.exports = Receiver; + }; }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/sender.js -var require_sender = __commonJS((exports, module) => { - var { Duplex } = __require("stream"); - var { randomFillSync: randomFillSync2 } = __require("crypto"); - var PerMessageDeflate = require_permessage_deflate(); - var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants4(); - var { isBlob, isValidStatusCode } = require_validation(); - var { mask: applyMask, toBuffer } = require_buffer_util(); - var kByteLength = Symbol("kByteLength"); - var maskBuffer = Buffer.alloc(4); - var RANDOM_POOL_SIZE = 8 * 1024; - var randomPool; - var randomPoolPointer = RANDOM_POOL_SIZE; - var DEFAULT = 0; - var DEFLATING = 1; - var GET_BLOB_DATA = 2; - - class Sender { - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - this._socket = socket; - this._firstFragment = true; - this._compress = false; - this._bufferedBytes = 0; - this._queue = []; - this._state = DEFAULT; - this.onerror = NOOP; - this[kWebSocket] = undefined; - } - static frame(data, options) { - let mask; - let merge2 = false; - let offset = 2; - let skipMasking = false; - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - if (options.generateMask) { - options.generateMask(mask); - } else { - if (randomPoolPointer === RANDOM_POOL_SIZE) { - if (randomPool === undefined) { - randomPool = Buffer.alloc(RANDOM_POOL_SIZE); - } - randomFillSync2(randomPool, 0, RANDOM_POOL_SIZE); - randomPoolPointer = 0; - } - mask[0] = randomPool[randomPoolPointer++]; - mask[1] = randomPool[randomPoolPointer++]; - mask[2] = randomPool[randomPoolPointer++]; - mask[3] = randomPool[randomPoolPointer++]; - } - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - let dataLength; - if (typeof data === "string") { - if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) { - dataLength = options[kByteLength]; - } else { - data = Buffer.from(data); - dataLength = data.length; - } - } else { - dataLength = data.length; - merge2 = options.mask && options.readOnly && !skipMasking; - } - let payloadLength = dataLength; - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - const target = Buffer.allocUnsafe(merge2 ? dataLength + offset : offset); - target[0] = options.fin ? options.opcode | 128 : options.opcode; - if (options.rsv1) - target[0] |= 64; - target[1] = payloadLength; - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - if (!options.mask) - return [target, data]; - target[1] |= 128; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - if (skipMasking) - return [target, data]; - if (merge2) { - applyMask(data, mask, target, offset, dataLength); - return [target]; - } - applyMask(data, mask, data, 0, dataLength); - return [target, data]; - } - close(code, data, mask, cb) { - let buf; - if (code === undefined) { - buf = EMPTY_BUFFER; - } else if (typeof code !== "number" || !isValidStatusCode(code)) { - throw new TypeError("First argument must be a valid error code number"); - } else if (data === undefined || !data.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data); - if (length > 123) { - throw new RangeError("The message must not be greater than 123 bytes"); - } - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - if (typeof data === "string") { - buf.write(data, 2); - } else { - buf.set(data, 2); - } - } - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 8, - readOnly: false, - rsv1: false +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/messages-v2.js +function getResponseMetadata2(message) { + if ("response_metadata" in message && typeof message.response_metadata === "object" && message.response_metadata != null) + return message.response_metadata; +} +function getUsageMetadata2(message) { + if ("usage_metadata" in message && typeof message.usage_metadata === "object" && message.usage_metadata != null) + return message.usage_metadata; +} +function startBlockFor2(block) { + switch (block.type) { + case "text": + return { + type: "text", + text: "" }; - if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(Sender.frame(buf, options), cb); - } - } - ping(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 9, - readOnly, - rsv1: false + case "reasoning": + return { + type: "reasoning", + reasoning: "" }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); + case "tool_call": + case "tool_call_chunk": + return { + type: "tool_call_chunk", + ...block.id != null ? { id: block.id } : {}, + ...block.name != null ? { name: block.name } : {}, + args: "" + }; + default: + return block; + } +} +function deltaFor2(block) { + switch (block.type) { + case "text": { + const text = typeof block.text === "string" ? block.text : ""; + return text.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "text-delta", + text } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } + } : undefined; } - pong(data, mask, cb) { - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (byteLength > 125) { - throw new RangeError("The data size must not be greater than 125 bytes"); - } - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 10, - readOnly, - rsv1: false - }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); + case "reasoning": { + const reasoning = typeof block.reasoning === "string" ? block.reasoning : ""; + return reasoning.length > 0 ? { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "reasoning-delta", + reasoning } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } + } : undefined; } - send(data, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - let byteLength; - let readOnly; - if (typeof data === "string") { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer(data); - byteLength = data.length; - readOnly = toBuffer.readOnly; - } - if (this._firstFragment) { - this._firstFragment = false; - if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { - rsv1 = byteLength >= perMessageDeflate._threshold; + case "tool_call_chunk": + return { + event: "content-block-delta", + index: typeof block.index === "number" ? block.index : 0, + delta: { + type: "block-delta", + fields: { + ...block, + type: "tool_call_chunk" + } } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - if (options.fin) - this._firstFragment = true; - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 }; - if (isBlob(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, this._compress, opts, cb]); - } else { - this.getBlobData(data, this._compress, opts, cb); + default: + return; + } +} +var StreamProtocolMessagesHandler2; +var init_messages_v22 = __esm(() => { + init_constants5(); + init_base2(); + init_messages(); + StreamProtocolMessagesHandler2 = class extends BaseCallbackHandler { + name = "StreamProtocolMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + streamedRunIds = /* @__PURE__ */ new Set; + stableMessageIdMap = {}; + lc_prefer_chat_model_stream_events = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; + } + normalizeMessageId(message, runId) { + let messageId = message.id; + if (runId != null) + if (ToolMessage.isInstance(message)) + messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) + messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, this._compress, opts, cb]); - } else { - this.dispatch(data, this._compress, opts, cb); + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; } + if (message.id != null) + this.seen[message.id] = message; + return message.id; } - getBlobData(blob, compress, options, cb) { - this._bufferedBytes += options[kByteLength]; - this._state = GET_BLOB_DATA; - blob.arrayBuffer().then((arrayBuffer) => { - if (this._socket.destroyed) { - const err = new Error("The socket was closed while the blob was being read"); - process.nextTick(callCallbacks, this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - const data = toBuffer(arrayBuffer); - if (!compress) { - this._state = DEFAULT; - this.sendFrame(Sender.frame(data, options), cb); - this.dequeue(); - } else { - this.dispatch(data, compress, options, cb); - } - }).catch((err) => { - process.nextTick(onError2, this, err, cb); - }); + emit(meta3, data, runId) { + const metadata = runId != null ? { + ...meta3[1], + run_id: runId + } : meta3[1]; + this.streamFn([ + meta3[0], + "messages", + [data, metadata] + ]); } - dispatch(data, compress, options, cb) { - if (!compress) { - this.sendFrame(Sender.frame(data, options), cb); + emitFinalMessage(meta3, message, runId, dedupe = false) { + const existingId = message.id ?? (runId != null ? this.stableMessageIdMap[runId] : undefined); + if (dedupe && existingId != null && this.seen[existingId] !== undefined) return; - } - const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; - this._bufferedBytes += options[kByteLength]; - this._state = DEFLATING; - perMessageDeflate.compress(data, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error("The socket was closed while data was being compressed"); - callCallbacks(this, err, cb); - return; - } - this._bufferedBytes -= options[kByteLength]; - this._state = DEFAULT; - options.readOnly = false; - this.sendFrame(Sender.frame(buf, options), cb); - this.dequeue(); + const messageId = this.normalizeMessageId(message, runId); + const role = message.type === "human" ? "human" : message.type === "system" ? "system" : message.type === "tool" ? "tool" : "ai"; + const toolCallId = role === "tool" && ToolMessage.isInstance(message) ? message.tool_call_id : undefined; + this.emit(meta3, { + event: "message-start", + ...messageId != null ? { id: messageId } : {}, + ...role !== "ai" ? { role } : {}, + ...typeof toolCallId === "string" ? { tool_call_id: toolCallId } : {} + }, runId); + (Array.isArray(message.content) ? message.content : typeof message.content === "string" && message.content.length > 0 ? [{ + type: "text", + text: message.content + }] : []).forEach((block, offset) => { + const index2 = typeof block.index === "number" ? block.index : offset; + this.emit(meta3, { + event: "content-block-start", + index: index2, + content: startBlockFor2(block) + }, runId); + const delta = deltaFor2({ + ...block, + index: index2 + }); + if (delta != null) + this.emit(meta3, delta, runId); + this.emit(meta3, { + event: "content-block-finish", + index: index2, + content: block + }, runId); }); + this.emit(meta3, { + event: "message-finish", + ...getUsageMetadata2(message) != null ? { usage: getUsageMetadata2(message) } : {}, + ...getResponseMetadata2(message) != null ? { responseMetadata: getResponseMetadata2(message) } : {} + }, runId); } - dequeue() { - while (this._state === DEFAULT && this._queue.length) { - const params = this._queue.shift(); - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; } - sendFrame(list, cb) { - if (list.length === 2) { - this._socket.cork(); - this._socket.write(list[0]); - this._socket.write(list[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list[0], cb); + handleLLMNewToken() {} + handleChatModelStreamEvent(event, runId) { + const meta3 = this.metadatas[runId]; + if (meta3 === undefined) + return; + let forwarded = event; + if (event.event === "message-start") { + this.streamedRunIds.add(runId); + const id = event.id ?? `run-${runId}`; + this.seen[id] = true; + this.stableMessageIdMap[runId] ??= id; + if (event.id == null) + forwarded = { + ...event, + id + }; } + this.emit(meta3, forwarded, runId); } - } - module.exports = Sender; - function callCallbacks(sender, err, cb) { - if (typeof cb === "function") - cb(err); - for (let i = 0;i < sender._queue.length; i++) { - const params = sender._queue[i]; - const callback = params[params.length - 1]; - if (typeof callback === "function") - callback(err); - } - } - function onError2(sender, err, cb) { - callCallbacks(sender, err, cb); - sender.onerror(err); - } -}); - -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/event-target.js -var require_event_target = __commonJS((exports, module) => { - var { kForOnEventAttribute, kListener } = require_constants4(); - var kCode = Symbol("kCode"); - var kData = Symbol("kData"); - var kError = Symbol("kError"); - var kMessage = Symbol("kMessage"); - var kReason = Symbol("kReason"); - var kTarget = Symbol("kTarget"); - var kType = Symbol("kType"); - var kWasClean = Symbol("kWasClean"); - - class Event { - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - get target() { - return this[kTarget]; + handleLLMEnd(output, runId) { + const meta3 = this.metadatas[runId]; + if (meta3 === undefined) + return; + const chatGeneration = output.generations?.[0]?.[0]; + const message = BaseMessage.isInstance(chatGeneration?.message) ? chatGeneration.message : undefined; + if (message != null) + if (this.streamedRunIds.has(runId)) { + const messageId = this.normalizeMessageId(message, runId); + if (messageId != null) + this.seen[messageId] = message; + } else + this.emitFinalMessage(meta3, message, runId, true); + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; } - get type() { - return this[kType]; + handleLLMError(_err, runId) { + this.streamedRunIds.delete(runId); + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; } - } - Object.defineProperty(Event.prototype, "target", { enumerable: true }); - Object.defineProperty(Event.prototype, "type", { enumerable: true }); - - class CloseEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kCode] = options.code === undefined ? 0 : options.code; - this[kReason] = options.reason === undefined ? "" : options.reason; - this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; - } - get code() { - return this[kCode]; + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) + if ((BaseMessage.isInstance(value) || BaseMessageChunk.isInstance(value)) && value.id !== undefined) + this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) + if ((BaseMessage.isInstance(item) || BaseMessageChunk.isInstance(item)) && item.id !== undefined) + this.seen[item.id] = item; + } + } + } } - get reason() { - return this[kReason]; + handleChainEnd(outputs, runId) { + const meta3 = this.metadatas[runId]; + delete this.metadatas[runId]; + if (meta3 === undefined) + return; + const emitMessage = (value) => { + if (BaseMessage.isInstance(value) && !ToolMessage.isInstance(value)) + this.emitFinalMessage(meta3, value, runId, true); + }; + if (BaseMessage.isInstance(outputs)) + emitMessage(outputs); + else if (Array.isArray(outputs)) + for (const value of outputs) + emitMessage(value); + else if (outputs != null && typeof outputs === "object") + for (const value of Object.values(outputs)) + if (Array.isArray(value)) + for (const item of value) + emitMessage(item); + else + emitMessage(value); + delete this.stableMessageIdMap[runId]; } - get wasClean() { - return this[kWasClean]; + handleChainError(_err, runId) { + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; } - } - Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); - Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); + }; +}); - class ErrorEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kError] = options.error === undefined ? null : options.error; - this[kMessage] = options.message === undefined ? "" : options.message; - } - get error() { - return this[kError]; - } - get message() { - return this[kMessage]; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/retry.js +async function _runWithRetry2(pregelTask, retryPolicy, configurable, signal) { + const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; + let interval = resolvedRetryPolicy !== undefined ? resolvedRetryPolicy.initialInterval ?? 500 : 0; + let attempts = 0; + let error90; + let result; + let config3 = pregelTask.config ?? {}; + if (configurable) + config3 = patchConfigurable4(config3, configurable); + config3 = { + ...config3, + signal + }; + const firstAttemptTime = Date.now(); + if (config3.executionInfo != null) + config3.executionInfo = { + ...config3.executionInfo, + nodeFirstAttemptTime: firstAttemptTime + }; + while (true) { + if (signal?.aborted) + break; + pregelTask.writes.splice(0, pregelTask.writes.length); + error90 = undefined; + try { + result = await pregelTask.proc.invoke(pregelTask.input, config3); + break; + } catch (e) { + error90 = e; + error90.pregelTaskId = pregelTask.id; + if (isParentCommand2(error90)) { + const ns3 = config3?.configurable?.checkpoint_ns; + const cmd = error90.command; + if (cmd.graph === ns3) { + for (const writer2 of pregelTask.writers) + await writer2.invoke(cmd, config3); + error90 = undefined; + break; + } else if (cmd.graph === Command2.PARENT) { + const parentNs = getParentCheckpointNamespace2(ns3); + error90.command = new Command2({ + ...error90.command, + graph: parentNs + }); + } + } + if (isGraphBubbleUp2(error90)) + break; + if (resolvedRetryPolicy === undefined) + break; + attempts += 1; + if (attempts >= (resolvedRetryPolicy.maxAttempts ?? 3)) + break; + if (!(resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER2)(error90)) + break; + interval = Math.min(resolvedRetryPolicy.maxInterval ?? 128000, interval * (resolvedRetryPolicy.backoffFactor ?? 2)); + const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1000) : interval; + await new Promise((resolve2) => setTimeout(resolve2, intervalWithJitter)); + const errorName = error90.name ?? error90.constructor.unminifiable_name ?? error90.constructor.name; + if (resolvedRetryPolicy?.logWarning ?? true) + console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error90}`); + config3 = patchConfigurable4(config3, { [CONFIG_KEY_RESUMING2]: true }); + if (config3.executionInfo != null) + config3.executionInfo = { + ...config3.executionInfo, + nodeAttempt: attempts + 1, + nodeFirstAttemptTime: firstAttemptTime + }; } } - Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); - Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); + return { + task: pregelTask, + result, + error: error90, + signalAborted: signal?.aborted + }; +} +var DEFAULT_STATUS_NO_RETRY2, DEFAULT_RETRY_ON_HANDLER2 = (error90) => { + if (error90.message.startsWith("Cancel") || error90.message.startsWith("AbortError") || error90.name === "AbortError") + return false; + if (error90.name === "GraphValueError") + return false; + if (error90?.code === "ECONNABORTED") + return false; + const status = error90?.response?.status ?? error90?.status; + if (status && DEFAULT_STATUS_NO_RETRY2.includes(+status)) + return false; + if (error90?.error?.code === "insufficient_quota") + return false; + return true; +}; +var init_retry2 = __esm(() => { + init_constants5(); + init_errors9(); + init_config3(); + init_utils15(); + DEFAULT_STATUS_NO_RETRY2 = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 + ]; +}); - class MessageEvent extends Event { - constructor(type, options = {}) { - super(type); - this[kData] = options.data === undefined ? null : options.data; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/runner.js +function createPromiseBarrier2() { + const barrier = { + next: () => { + return; + }, + wait: Promise.resolve(PROMISE_ADDED_SYMBOL2) + }; + function waitHandler(resolve2) { + barrier.next = () => { + barrier.wait = new Promise(waitHandler); + resolve2(PROMISE_ADDED_SYMBOL2); + }; + } + barrier.wait = new Promise(waitHandler); + return barrier; +} +async function call3(runner, task2, func, name, input, options = {}) { + const scratchpad = task2.config?.configurable?.[CONFIG_KEY_SCRATCHPAD2]; + if (!scratchpad) + throw new Error(`BUG: No scratchpad found on task ${task2.name}__${task2.id}`); + const cnt = scratchpad.callCounter; + scratchpad.callCounter += 1; + const wcall = new Call2({ + func, + name, + input, + cache: options.cache, + retry: options.retry, + callbacks: options.callbacks + }); + const nextTask = await this.scheduleTask(task2, cnt, wcall); + if (!nextTask) + return; + const existingPromise = this.executingTasksMap[nextTask.id]; + if (existingPromise !== undefined) + return existingPromise; + if (nextTask.writes.length > 0) { + const returns = nextTask.writes.filter(([c]) => c === RETURN2); + const errors6 = nextTask.writes.filter(([c]) => c === ERROR4); + if (returns.length > 0) { + if (returns.length === 1) + return Promise.resolve(returns[0][1]); + throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); } - get data() { - return this[kData]; + if (errors6.length > 0) { + if (errors6.length === 1) { + const errorValue = errors6[0][1]; + const error90 = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); + return Promise.reject(error90); + } + throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); } + return; + } else { + const prom = _runWithRetry2(nextTask, options.retry, { [CONFIG_KEY_CALL2]: call3.bind(this, runner, nextTask) }); + this.executingTasksMap[nextTask.id] = prom; + this.barrier.next(); + return prom.then(({ result, error: error90 }) => { + if (error90) + return Promise.reject(error90); + return result; + }); } - Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); - var EventTarget = { - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { - return; - } - } - let wrapper; - if (type === "message") { - wrapper = function onMessage(data, isBinary) { - const event = new MessageEvent("message", { - data: isBinary ? data : data.toString() - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "close") { - wrapper = function onClose(code, message) { - const event = new CloseEvent("close", { - code, - reason: message.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "error") { - wrapper = function onError2(error51) { - const event = new ErrorEvent("error", { - error: error51, - message: error51.message - }); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === "open") { - wrapper = function onOpen() { - const event = new Event("open"); - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; +} +var PROMISE_ADDED_SYMBOL2, PregelRunner2 = class { + nodeFinished; + loop; + constructor({ loop, nodeFinished }) { + this.loop = loop; + this.nodeFinished = nodeFinished; + } + async tick(options = {}) { + const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; + const nodeErrors = /* @__PURE__ */ new Set; + let graphBubbleUp; + const exceptionSignalController = new AbortController; + const exceptionSignal = exceptionSignalController.signal; + const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : undefined; + const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); + const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ + exceptionSignal, + stepTimeoutSignal, + signal: options.signal + }); + const taskStream = this._executeTasksWithRetry(pendingTasks, { + signals, + retryPolicy, + maxConcurrency + }); + for await (const { task: task2, error: error90, signalAborted } of taskStream) { + this._commit(task2, error90); + if (isGraphInterrupt2(error90)) + graphBubbleUp = error90; + else if (isGraphBubbleUp2(error90) && !isGraphInterrupt2(graphBubbleUp)) + graphBubbleUp = error90; + else if (error90 && (nodeErrors.size === 0 || !signalAborted)) { + exceptionSignalController.abort(); + nodeErrors.add(error90); } - wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; - wrapper[kListener] = handler; - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); + } + disposeCombinedSignal?.(); + onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task2) => task2.writes).flat()); + if (nodeErrors.size === 1) + throw Array.from(nodeErrors)[0]; + else if (nodeErrors.size > 1) + throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); + if (isGraphInterrupt2(graphBubbleUp)) + throw graphBubbleUp; + if (isGraphBubbleUp2(graphBubbleUp) && this.loop.isNested) + throw graphBubbleUp; + } + _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { + const previousSignals = this.loop.config.configurable?.["__pregel_abort_signals"] ?? {}; + const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; + const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; + const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals2(externalAbortSignal, timeoutAbortSignal, exceptionSignal); + const signals = { + externalAbortSignal, + timeoutAbortSignal, + composedAbortSignal + }; + this.loop.config = patchConfigurable4(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS2]: signals }); + return { + signals, + disposeCombinedSignal + }; + } + async* _executeTasksWithRetry(tasks, options) { + const { retryPolicy, maxConcurrency, signals } = options ?? {}; + const barrier = createPromiseBarrier2(); + const executingTasksMap = {}; + const thisCall = { + executingTasksMap, + barrier, + retryPolicy, + scheduleTask: async (task2, writeIdx, call3) => this.loop.acceptPush(task2, writeIdx, call3) + }; + if (signals?.composedAbortSignal?.aborted) + throw new Error("Abort"); + let startedTasksCount = 0; + let listener; + const timeoutOrCancelSignal = combineAbortSignals2(signals?.externalAbortSignal, signals?.timeoutAbortSignal); + const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { + listener = () => reject(/* @__PURE__ */ new Error("Abort")); + timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); + }) : undefined; + while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { + for (;Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { + const task2 = tasks[startedTasksCount]; + executingTasksMap[task2.id] = _runWithRetry2(task2, retryPolicy, { [CONFIG_KEY_CALL2]: call3?.bind(thisCall, this, task2) }, signals?.composedAbortSignal).catch((error90) => { + return { + task: task2, + error: error90, + signalAborted: signals?.composedAbortSignal?.aborted + }; + }); } - }, - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { - this.removeListener(type, listener); - break; - } + const settledTask = await Promise.race([ + ...Object.values(executingTasksMap), + ...abortPromise ? [abortPromise] : [], + barrier.wait + ]); + if (settledTask === PROMISE_ADDED_SYMBOL2) + continue; + yield settledTask; + if (listener != null) { + timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); + timeoutOrCancelSignal.dispose?.(); } + delete executingTasksMap[settledTask.task.id]; } - }; - module.exports = { - CloseEvent, - ErrorEvent, - Event, - EventTarget, - MessageEvent - }; - function callListener(listener, thisArg, event) { - if (typeof listener === "object" && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); + } + _commit(task2, error90) { + if (error90 !== undefined) + if (isGraphInterrupt2(error90)) { + if (error90.interrupts.length) { + const interrupts = error90.interrupts.map((interrupt3) => [INTERRUPT3, interrupt3]); + const resumes = task2.writes.filter((w) => w[0] === RESUME3); + if (resumes.length) + interrupts.push(...resumes); + this.loop.putWrites(task2.id, interrupts); + } + } else if (isGraphBubbleUp2(error90) && task2.writes.length) + this.loop.putWrites(task2.id, task2.writes); + else + this.loop.putWrites(task2.id, [[ERROR4, { + message: error90.message, + name: error90.name + }]]); + else { + if (this.nodeFinished && (task2.config?.tags == null || !task2.config.tags.includes("langsmith:hidden"))) + this.nodeFinished(String(task2.name)); + if (task2.writes.length === 0) + task2.writes.push([NO_WRITES2, null]); + this.loop.putWrites(task2.id, task2.writes); } } +}; +var init_runner2 = __esm(() => { + init_constants5(); + init_errors9(); + init_types12(); + init_utils15(); + init_retry2(); + PROMISE_ADDED_SYMBOL2 = Symbol.for("promiseAdded"); }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/extension.js -var require_extension = __commonJS((exports, module) => { - var { tokenChars } = require_validation(); - function push2(dest, name, elem) { - if (dest[name] === undefined) - dest[name] = [elem]; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/validate.js +function validateGraph2({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { + if (!channels) + throw new GraphValidationError2("Channels not provided"); + const subscribedChannels = /* @__PURE__ */ new Set; + const allOutputChannels = /* @__PURE__ */ new Set; + for (const [name, node] of Object.entries(nodes)) { + if (name === "__interrupt__") + throw new GraphValidationError2(`"Node name ${INTERRUPT3} is reserved"`); + if (node.constructor === PregelNode3) + node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); else - dest[name].push(elem); + throw new GraphValidationError2(`Invalid node type ${typeof node}, expected PregelNode`); } - function parse11(header) { - const offers = Object.create(null); - let params = Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i = 0; - for (;i < header.length; i++) { - code = header.charCodeAt(i); - if (extensionName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (i !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) - end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) - end = i; - const name = header.slice(start, end); - if (code === 44) { - push2(offers, name, params); - params = Object.create(null); - } else { - extensionName = name; - } - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (paramName === undefined) { - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (code === 32 || code === 9) { - if (end === -1 && start !== -1) - end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) - end = i; - push2(params, header.slice(start, end), true); - if (code === 44) { - push2(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - start = end = -1; - } else if (code === 61 && start !== -1 && end === -1) { - paramName = header.slice(start, i); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else { - if (isEscaping) { - if (tokenChars[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1) - start = i; - else if (!mustUnescape) - mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (code === 34 && start !== -1) { - inQuotes = false; - end = i; - } else if (code === 92) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (code === 34 && header.charCodeAt(i - 1) === 61) { - inQuotes = true; - } else if (end === -1 && tokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (start !== -1 && (code === 32 || code === 9)) { - if (end === -1) - end = i; - } else if (code === 59 || code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) - end = i; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ""); - mustUnescape = false; - } - push2(params, paramName, value); - if (code === 44) { - push2(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - paramName = undefined; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - } - if (start === -1 || inQuotes || code === 32 || code === 9) { - throw new SyntaxError("Unexpected end of input"); - } - if (end === -1) - end = i; - const token = header.slice(start, end); - if (extensionName === undefined) { - push2(offers, token, params); - } else { - if (paramName === undefined) { - push2(params, token, true); - } else if (mustUnescape) { - push2(params, paramName, token.replace(/\\/g, "")); - } else { - push2(params, paramName, token); - } - push2(offers, extensionName, params); - } - return offers; + for (const chan of subscribedChannels) + if (!(chan in channels)) + throw new GraphValidationError2(`Subscribed channel '${String(chan)}' not in channels`); + if (!Array.isArray(inputChannels)) { + if (!subscribedChannels.has(inputChannels)) + throw new GraphValidationError2(`Input channel ${String(inputChannels)} is not subscribed to by any node`); + } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) + throw new GraphValidationError2(`None of the input channels ${inputChannels} are subscribed to by any node`); + if (!Array.isArray(outputChannels)) + allOutputChannels.add(outputChannels); + else + outputChannels.forEach((chan) => allOutputChannels.add(chan)); + if (streamChannels && !Array.isArray(streamChannels)) + allOutputChannels.add(streamChannels); + else if (Array.isArray(streamChannels)) + streamChannels.forEach((chan) => allOutputChannels.add(chan)); + for (const chan of allOutputChannels) + if (!(chan in channels)) + throw new GraphValidationError2(`Output channel '${String(chan)}' not in channels`); + if (interruptAfterNodes && interruptAfterNodes !== "*") { + for (const node of interruptAfterNodes) + if (!(node in nodes)) + throw new GraphValidationError2(`Node ${String(node)} not in nodes`); } - function format3(extensions) { - return Object.keys(extensions).map((extension) => { - let configurations = extensions[extension]; - if (!Array.isArray(configurations)) - configurations = [configurations]; - return configurations.map((params) => { - return [extension].concat(Object.keys(params).map((k) => { - let values = params[k]; - if (!Array.isArray(values)) - values = [values]; - return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); - })).join("; "); - }).join(", "); - }).join(", "); + if (interruptBeforeNodes && interruptBeforeNodes !== "*") { + for (const node of interruptBeforeNodes) + if (!(node in nodes)) + throw new GraphValidationError2(`Node ${String(node)} not in nodes`); } - module.exports = { format: format3, parse: parse11 }; +} +function validateKeys2(keys, channels) { + if (Array.isArray(keys)) { + for (const key of keys) + if (!(key in channels)) + throw new Error(`Key ${String(key)} not found in channels`); + } else if (!(keys in channels)) + throw new Error(`Key ${String(keys)} not found in channels`); +} +var GraphValidationError2; +var init_validate5 = __esm(() => { + init_constants5(); + init_read2(); + GraphValidationError2 = class extends Error { + constructor(message) { + super(message); + this.name = "GraphValidationError"; + } + }; }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket.js -var require_websocket = __commonJS((exports, module) => { - var EventEmitter2 = __require("events"); - var https = __require("https"); - var http = __require("http"); - var net = __require("net"); - var tls = __require("tls"); - var { randomBytes, createHash: createHash4 } = __require("crypto"); - var { Duplex, Readable: Readable2 } = __require("stream"); - var { URL: URL5 } = __require("url"); - var PerMessageDeflate = require_permessage_deflate(); - var Receiver = require_receiver(); - var Sender = require_sender(); - var { isBlob } = require_validation(); - var { - BINARY_TYPES, - CLOSE_TIMEOUT, - EMPTY_BUFFER, - GUID, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket, - NOOP - } = require_constants4(); - var { - EventTarget: { addEventListener: addEventListener2, removeEventListener } - } = require_event_target(); - var { format: format3, parse: parse11 } = require_extension(); - var { toBuffer } = require_buffer_util(); - var kAborted = Symbol("kAborted"); - var protocolVersions = [8, 13]; - var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; - var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - - class WebSocket2 extends EventEmitter2 { - constructor(address, protocols, options) { +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/topic.js +var Topic3; +var init_topic2 = __esm(() => { + init_errors9(); + init_base16(); + Topic3 = class Topic4 extends BaseChannel2 { + lc_graph_name = "Topic"; + unique = false; + accumulate = false; + seen; + values; + constructor(fields) { super(); - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER; - this._closeTimer = null; - this._errorEmitted = false; - this._extensions = {}; - this._paused = false; - this._protocol = ""; - this._readyState = WebSocket2.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - if (protocols === undefined) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === "object" && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - initAsClient(this, address, protocols, options); - } else { - this._autoPong = options.autoPong; - this._closeTimeout = options.closeTimeout; - this._isServer = true; + this.unique = fields?.unique ?? this.unique; + this.accumulate = fields?.accumulate ?? this.accumulate; + this.seen = /* @__PURE__ */ new Set; + this.values = []; + } + fromCheckpoint(checkpoint) { + const empty = new Topic4({ + unique: this.unique, + accumulate: this.accumulate + }); + if (typeof checkpoint !== "undefined") { + empty.seen = new Set(checkpoint[0]); + empty.values = checkpoint[1]; } + return empty; } - get binaryType() { - return this._binaryType; + update(values) { + let updated = false; + if (!this.accumulate) { + updated = this.values.length > 0; + this.values = []; + } + const flatValues = values.flat(); + if (flatValues.length > 0) + if (this.unique) { + for (const value of flatValues) + if (!this.seen.has(value)) { + updated = true; + this.seen.add(value); + this.values.push(value); + } + } else { + updated = true; + this.values.push(...flatValues); + } + return updated; } - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) - return; - this._binaryType = type; - if (this._receiver) - this._receiver._binaryType = type; + get() { + if (this.values.length === 0) + throw new EmptyChannelError2; + return this.values; } - get bufferedAmount() { - if (!this._socket) - return this._bufferedAmount; - return this._socket._writableState.length + this._sender._bufferedBytes; + checkpoint() { + return [[...this.seen], this.values]; } - get extensions() { - return Object.keys(this._extensions).join(); + isAvailable() { + return this.values.length !== 0; } - get isPaused() { - return this._paused; + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/pregel/index.js +function protocolEventsToEventStream2(run2) { + const encoder2 = new TextEncoder; + return new ReadableStream({ async start(controller) { + try { + for await (const event of run2) { + const namespace = event.params.namespace; + const eventName = namespace.length ? `${event.method}|${namespace.join("|")}` : event.method; + controller.enqueue(encoder2.encode(`event: ${eventName} +data: ${JSON.stringify(event.params.data ?? {})} + +`)); + } + } catch (error90) { + controller.enqueue(encoder2.encode(`event: error +data: ${JSON.stringify({ message: String(error90) })} + +`)); + } finally { + controller.close(); } - get onclose() { - return null; + } }); +} +function _buildServerInfo2(config3) { + const metadata = config3.metadata ?? {}; + const configurable = config3.configurable ?? {}; + const assistantId = configurable.assistant_id ?? metadata.assistant_id; + const graphId = configurable.graph_id ?? metadata.graph_id; + const authUserData = configurable.langgraph_auth_user; + let user; + if (authUserData != null && typeof authUserData === "object" && "identity" in authUserData) + user = authUserData; + if (assistantId != null || graphId != null || user != null) + return { + assistantId: assistantId != null ? String(assistantId) : "", + graphId: graphId != null ? String(graphId) : "", + user + }; +} +function _excludeAsMetadata2(key, value) { + const keyLower = key.toLowerCase(); + let hasOmittedSubstring = false; + for (const substr of OMITTED_KEYS2) + if (keyLower.includes(substr)) { + hasOmittedSubstring = true; + break; } - get onerror() { - return null; + return key.startsWith("__") || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || hasOmittedSubstring; +} +function _getTracingMetadataDefaults2(config3) { + const configurable = config3.configurable; + if (!configurable) + return; + const metadata = {}; + for (const [key, value] of Object.entries(configurable)) { + if (_excludeAsMetadata2(key, value)) + continue; + metadata[key] = value; + } + return Object.keys(metadata).length > 0 ? metadata : undefined; +} +var PartialRunnable2, Pregel2, OMITTED_KEYS2; +var init_pregel2 = __esm(() => { + init_constants5(); + init_errors9(); + init_base16(); + init_config3(); + init_utils14(); + init_write2(); + init_read2(); + init_io2(); + init_utils15(); + init_algo2(); + init_subgraph2(); + init_debug2(); + init_stream8(); + init_loop2(); + init_messages6(); + init_messages_v22(); + init_runner2(); + init_convert2(); + init_run_stream2(); + init_stream7(); + init_validate5(); + init_topic2(); + init_interrupt2(); + init_dist3(); + init_runnables(); + init_manager(); + PartialRunnable2 = class extends Runnable { + lc_namespace = ["langgraph", "pregel"]; + invoke(_input, _options) { + throw new Error("Not implemented"); } - get onopen() { - return null; + withConfig(_config) { + return super.withConfig(_config); } - get onmessage() { - return null; + stream(input, options) { + return super.stream(input, options); } - get protocol() { - return this._protocol; + }; + Pregel2 = class extends PartialRunnable2 { + static lc_name() { + return "LangGraph"; } - get readyState() { - return this._readyState; + lc_namespace = ["langgraph", "pregel"]; + lg_is_pregel = true; + nodes; + channels; + inputChannels; + outputChannels; + autoValidate = true; + streamMode = ["values"]; + streamChannels; + interruptAfter; + interruptBefore; + stepTimeout; + debug = false; + checkpointer; + retryPolicy; + config; + store; + cache; + userInterrupt; + streamTransformers; + triggerToNodes = {}; + constructor(fields) { + super(fields); + let { streamMode } = fields; + if (streamMode != null && !Array.isArray(streamMode)) + streamMode = [streamMode]; + this.nodes = fields.nodes; + this.channels = fields.channels; + if ("__pregel_tasks" in this.channels && "lc_graph_name" in this.channels["__pregel_tasks"] && this.channels["__pregel_tasks"].lc_graph_name !== "Topic") + throw new Error(`Channel '${TASKS3}' is reserved and cannot be used in the graph.`); + else + this.channels[TASKS3] = new Topic3({ accumulate: false }); + this.autoValidate = fields.autoValidate ?? this.autoValidate; + this.streamMode = streamMode ?? this.streamMode; + this.inputChannels = fields.inputChannels; + this.outputChannels = fields.outputChannels; + this.streamChannels = fields.streamChannels ?? this.streamChannels; + this.interruptAfter = fields.interruptAfter; + this.interruptBefore = fields.interruptBefore; + this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; + this.debug = fields.debug ?? this.debug; + this.checkpointer = fields.checkpointer; + this.retryPolicy = fields.retryPolicy; + this.config = fields.config; + this.store = fields.store; + this.cache = fields.cache; + this.name = fields.name; + this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; + this.userInterrupt = fields.userInterrupt; + this.streamTransformers = fields.streamTransformers ?? []; + if (this.autoValidate) + this.validate(); } - get url() { - return this._url; + withConfig(config3) { + const { streamTransformers, ...restConfig } = config3; + const mergedConfig = mergeConfigs(this.config, restConfig); + const mergedStreamTransformers = [...this.streamTransformers, ...streamTransformers ?? []]; + return new this.constructor({ + ...this, + config: mergedConfig, + streamTransformers: mergedStreamTransformers + }); } - setSocket(socket, head, options) { - const receiver = new Receiver({ - allowSynchronousEvents: options.allowSynchronousEvents, - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation + validate() { + validateGraph2({ + nodes: this.nodes, + channels: this.channels, + outputChannels: this.outputChannels, + inputChannels: this.inputChannels, + streamChannels: this.streamChannels, + interruptAfterNodes: this.interruptAfter, + interruptBeforeNodes: this.interruptBefore }); - const sender = new Sender(socket, this._extensions, options.generateMask); - this._receiver = receiver; - this._sender = sender; - this._socket = socket; - receiver[kWebSocket] = this; - sender[kWebSocket] = this; - socket[kWebSocket] = this; - receiver.on("conclude", receiverOnConclude); - receiver.on("drain", receiverOnDrain); - receiver.on("error", receiverOnError); - receiver.on("message", receiverOnMessage); - receiver.on("ping", receiverOnPing); - receiver.on("pong", receiverOnPong); - sender.onerror = senderOnError; - if (socket.setTimeout) - socket.setTimeout(0); - if (socket.setNoDelay) - socket.setNoDelay(); - if (head.length > 0) - socket.unshift(head); - socket.on("close", socketOnClose); - socket.on("data", socketOnData); - socket.on("end", socketOnEnd); - socket.on("error", socketOnError); - this._readyState = WebSocket2.OPEN; - this.emit("open"); + for (const [name, node] of Object.entries(this.nodes)) + for (const trigger of node.triggers) { + this.triggerToNodes[trigger] ??= []; + this.triggerToNodes[trigger].push(name); + } + return this; } - emitClose() { - if (!this._socket) { - this._readyState = WebSocket2.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); - return; - } - if (this._extensions[PerMessageDeflate.extensionName]) { - this._extensions[PerMessageDeflate.extensionName].cleanup(); - } - this._receiver.removeAllListeners(); - this._readyState = WebSocket2.CLOSED; - this.emit("close", this._closeCode, this._closeMessage); + get streamChannelsList() { + if (Array.isArray(this.streamChannels)) + return this.streamChannels; + else if (this.streamChannels) + return [this.streamChannels]; + else + return Object.keys(this.channels); } - close(code, data) { - if (this.readyState === WebSocket2.CLOSED) - return; - if (this.readyState === WebSocket2.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this.readyState === WebSocket2.CLOSING) { - if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { - this._socket.end(); + get streamChannelsAsIs() { + if (this.streamChannels) + return this.streamChannels; + else + return Object.keys(this.channels); + } + async getGraphAsync(config3) { + return this.getGraph(config3); + } + *getSubgraphs(namespace, recurse) { + for (const [name, node] of Object.entries(this.nodes)) { + if (namespace !== undefined) { + if (!namespace.startsWith(name)) + continue; } - return; - } - this._readyState = WebSocket2.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - if (err) - return; - this._closeFrameSent = true; - if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { - this._socket.end(); + const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; + for (const candidate of candidates) { + const graph = findSubgraphPregel2(candidate); + if (graph !== undefined) { + if (name === namespace) { + yield [name, graph]; + return; + } + if (namespace === undefined) + yield [name, graph]; + if (recurse) { + let newNamespace = namespace; + if (namespace !== undefined) + newNamespace = namespace.slice(name.length + 1); + for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) + yield [`${name}|${subgraphName}`, subgraph]; + } + } } - }); - setCloseTimer(this); - } - pause() { - if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) { - return; } - this._paused = true; - this._socket.pause(); } - ping(data, mask, cb) { - if (this.readyState === WebSocket2.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof data === "function") { - cb = data; - data = mask = undefined; - } else if (typeof mask === "function") { - cb = mask; - mask = undefined; - } - if (typeof data === "number") - data = data.toString(); - if (this.readyState !== WebSocket2.OPEN) { - sendAfterClose(this, data, cb); - return; - } - if (mask === undefined) - mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); + async* getSubgraphsAsync(namespace, recurse) { + yield* this.getSubgraphs(namespace, recurse); } - pong(data, mask, cb) { - if (this.readyState === WebSocket2.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); + async _prepareStateSnapshot({ config: config3, saved, subgraphCheckpointer, applyPendingWrites = false }) { + if (saved === undefined) + return { + values: {}, + next: [], + config: config3, + tasks: [] + }; + const channels = emptyChannels2(this.channels, saved.checkpoint); + if (saved.pendingWrites?.length) { + const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID2).map(([_, channel, value]) => [String(channel), value]); + if (nullWrites.length > 0) + _applyWrites2(saved.checkpoint, channels, [{ + name: INPUT2, + writes: nullWrites, + triggers: [] + }], undefined, this.triggerToNodes); } - if (typeof data === "function") { - cb = data; - data = mask = undefined; - } else if (typeof mask === "function") { - cb = mask; - mask = undefined; + const nextTasks = Object.values(_prepareNextTasks2(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + store: this.store + })); + const subgraphs = await gatherIterator2(this.getSubgraphsAsync()); + const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; + const taskStates = {}; + for (const task2 of nextTasks) { + const matchingSubgraph = subgraphs.find(([name]) => name === task2.name); + if (!matchingSubgraph) + continue; + let taskNs = `${String(task2.name)}:${task2.id}`; + if (parentNamespace) + taskNs = `${parentNamespace}|${taskNs}`; + if (subgraphCheckpointer === undefined) { + const config4 = { configurable: { + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + taskStates[task2.id] = config4; + } else { + const subgraphConfig = { configurable: { + [CONFIG_KEY_CHECKPOINTER2]: subgraphCheckpointer, + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + const pregel = matchingSubgraph[1]; + taskStates[task2.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); + } } - if (typeof data === "number") - data = data.toString(); - if (this.readyState !== WebSocket2.OPEN) { - sendAfterClose(this, data, cb); - return; + if (applyPendingWrites && saved.pendingWrites?.length) { + const nextTaskById = Object.fromEntries(nextTasks.map((task2) => [task2.id, task2])); + for (const [taskId, channel, value] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(channel)) + continue; + if (!(taskId in nextTaskById)) + continue; + nextTaskById[taskId].writes.push([String(channel), value]); + } + const tasksWithWrites3 = nextTasks.filter((task2) => task2.writes.length > 0); + if (tasksWithWrites3.length > 0) + _applyWrites2(saved.checkpoint, channels, tasksWithWrites3, undefined, this.triggerToNodes); } - if (mask === undefined) - mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); + let metadata = saved?.metadata; + if (metadata && saved?.config?.configurable?.thread_id) + metadata = { + ...metadata, + thread_id: saved.config.configurable.thread_id + }; + const nextList = nextTasks.filter((task2) => task2.writes.length === 0).map((task2) => task2.name); + return { + values: readChannels2(channels, this.streamChannelsAsIs), + next: nextList, + tasks: tasksWithWrites2(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), + metadata, + config: patchCheckpointMap2(saved.config, saved.metadata), + createdAt: saved.checkpoint.ts, + parentConfig: saved.parentConfig + }; } - resume() { - if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) { - return; + async getState(config3, options) { + const checkpointer = config3.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config3.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config3.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); + for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) + if (name === recastNamespace) + return await subgraph.getState(patchConfigurable3(config3, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), { subgraphs: options?.subgraphs }); } - this._paused = false; - if (!this._receiver._writableState.needDrain) - this._socket.resume(); + const mergedConfig = mergeConfigs(this.config, config3); + const saved = await checkpointer.getTuple(config3); + return await this._prepareStateSnapshot({ + config: mergedConfig, + saved, + subgraphCheckpointer: options?.subgraphs ? checkpointer : undefined, + applyPendingWrites: !config3.configurable?.checkpoint_id + }); } - send(data, options, cb) { - if (this.readyState === WebSocket2.CONNECTING) { - throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); - } - if (typeof options === "function") { - cb = options; - options = {}; - } - if (typeof data === "number") - data = data.toString(); - if (this.readyState !== WebSocket2.OPEN) { - sendAfterClose(this, data, cb); - return; - } - const opts = { - binary: typeof data !== "string", - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - if (!this._extensions[PerMessageDeflate.extensionName]) { - opts.compress = false; + async* getStateHistory(config3, options) { + const checkpointer = config3.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config3.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config3.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); + for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) + if (name === recastNamespace) { + yield* pregel.getStateHistory(patchConfigurable3(config3, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), options); + return; + } } - this._sender.send(data || EMPTY_BUFFER, opts, cb); + const mergedConfig = mergeConfigs(this.config, config3, { configurable: { checkpoint_ns: checkpointNamespace } }); + for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) + yield this._prepareStateSnapshot({ + config: checkpointTuple.config, + saved: checkpointTuple + }); } - terminate() { - if (this.readyState === WebSocket2.CLOSED) - return; - if (this.readyState === WebSocket2.CONNECTING) { - const msg = "WebSocket was closed before the connection was established"; - abortHandshake(this, this._req, msg); - return; - } - if (this._socket) { - this._readyState = WebSocket2.CLOSING; - this._socket.destroy(); + async bulkUpdateState(startConfig, supersteps) { + const checkpointer = startConfig.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; + if (!checkpointer) + throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + if (supersteps.length === 0) + throw new Error("No supersteps provided"); + if (supersteps.some((s) => s.updates.length === 0)) + throw new Error("No updates provided"); + const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && startConfig.configurable?.["__pregel_checkpointer"] === undefined) { + const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); + for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) + return await pregel.bulkUpdateState(patchConfigurable3(startConfig, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), supersteps); + throw new Error(`Subgraph "${recastNamespace}" not found`); } - } - } - Object.defineProperty(WebSocket2, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket2.prototype, "CONNECTING", { - enumerable: true, - value: readyStates.indexOf("CONNECTING") - }); - Object.defineProperty(WebSocket2, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket2.prototype, "OPEN", { - enumerable: true, - value: readyStates.indexOf("OPEN") - }); - Object.defineProperty(WebSocket2, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket2.prototype, "CLOSING", { - enumerable: true, - value: readyStates.indexOf("CLOSING") - }); - Object.defineProperty(WebSocket2, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - Object.defineProperty(WebSocket2.prototype, "CLOSED", { - enumerable: true, - value: readyStates.indexOf("CLOSED") - }); - [ - "binaryType", - "bufferedAmount", - "extensions", - "isPaused", - "protocol", - "readyState", - "url" - ].forEach((property) => { - Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); - }); - ["open", "error", "close", "message"].forEach((method) => { - Object.defineProperty(WebSocket2.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) - return listener[kListener]; + const updateSuperStep = async (inputConfig, updates) => { + const config3 = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; + const saved = await checkpointer.getTuple(config3); + const checkpoint = saved !== undefined ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); + const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; + const step = saved?.metadata?.step ?? -1; + let checkpointConfig = patchConfigurable3(config3, { checkpoint_ns: config3.configurable?.checkpoint_ns ?? "" }); + let checkpointMetadata = config3.metadata ?? {}; + if (saved?.config.configurable) { + checkpointConfig = patchConfigurable3(config3, saved.config.configurable); + checkpointMetadata = { + ...saved.metadata, + ...checkpointMetadata + }; } - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; + const { values, asNode } = updates[0]; + if (values == null && asNode === undefined) { + if (updates.length > 1) + throw new InvalidUpdateError2(`Cannot create empty checkpoint with multiple updates`); + return patchCheckpointMap2(await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, undefined, step), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, {}), saved ? saved.metadata : undefined); + } + const channels = emptyChannels2(this.channels, checkpoint); + if (values === null && asNode === "__end__") { + if (updates.length > 1) + throw new InvalidUpdateError2(`Cannot apply multiple updates when clearing state`); + if (saved) { + const nextTasks = _prepareNextTasks2(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + checkpointer, + store: this.store + }); + const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites2(checkpoint, channels, [{ + name: INPUT2, + writes: nullWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + for (const [taskId, k, v] of saved.pendingWrites || []) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(k)) + continue; + if (!(taskId in nextTasks)) + continue; + nextTasks[taskId].writes.push([k, v]); + } + _applyWrites2(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); } + return patchCheckpointMap2(await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, step), { + ...checkpointMetadata, + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : undefined); } - if (typeof handler !== "function") - return; - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); - }); - WebSocket2.prototype.addEventListener = addEventListener2; - WebSocket2.prototype.removeEventListener = removeEventListener; - module.exports = WebSocket2; - function initAsClient(websocket, address, protocols, options) { - const opts = { - allowSynchronousEvents: true, - autoPong: true, - closeTimeout: CLOSE_TIMEOUT, - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - socketPath: undefined, - hostname: undefined, - protocol: undefined, - timeout: undefined, - method: "GET", - host: undefined, - path: undefined, - port: undefined - }; - websocket._autoPong = opts.autoPong; - websocket._closeTimeout = opts.closeTimeout; - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`); - } - let parsedUrl; - if (address instanceof URL5) { - parsedUrl = address; - } else { - try { - parsedUrl = new URL5(address); - } catch { - throw new SyntaxError(`Invalid URL: ${address}`); - } - } - if (parsedUrl.protocol === "http:") { - parsedUrl.protocol = "ws:"; - } else if (parsedUrl.protocol === "https:") { - parsedUrl.protocol = "wss:"; + if (asNode === "__copy__") { + if (updates.length > 1) + throw new InvalidUpdateError2(`Cannot copy checkpoint with multiple updates`); + if (saved == null) + throw new InvalidUpdateError2(`Cannot copy a non-existent checkpoint`); + const isCopyWithUpdates = (values2) => { + if (!Array.isArray(values2)) + return false; + if (values2.length === 0) + return false; + return values2.every((v) => Array.isArray(v) && v.length === 2); + }; + const nextCheckpoint = createCheckpoint2(checkpoint, undefined, step); + const nextConfig2 = await checkpointer.put(saved.parentConfig ?? patchConfigurable3(saved.config, { checkpoint_id: undefined }), nextCheckpoint, { + source: "fork", + step: step + 1, + parents: saved.metadata?.parents ?? {} + }, {}); + if (isCopyWithUpdates(values)) { + const nextTasks = _prepareNextTasks2(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig2, false, { step: step + 2 }); + const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { + acc[name] ??= []; + acc[name].push({ id }); + return acc; + }, {}); + const userGroupBy = values.reduce((acc, item) => { + const [values2, asNode2] = item; + acc[asNode2] ??= []; + const targetIdx = acc[asNode2].length; + const taskId = tasksGroupBy[asNode2]?.[targetIdx]?.id; + acc[asNode2].push({ + values: values2, + asNode: asNode2, + taskId + }); + return acc; + }, {}); + return updateSuperStep(patchCheckpointMap2(nextConfig2, saved.metadata), Object.values(userGroupBy).flat()); + } + return patchCheckpointMap2(nextConfig2, saved.metadata); + } + if (asNode === "__input__") { + if (updates.length > 1) + throw new InvalidUpdateError2(`Cannot apply multiple updates when updating as input`); + const inputWrites = await gatherIterator2(mapInput2(this.inputChannels, values)); + if (inputWrites.length === 0) + throw new InvalidUpdateError2(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); + _applyWrites2(checkpoint, channels, [{ + name: INPUT2, + writes: inputWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; + const nextConfig2 = await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, nextStep), { + source: "input", + step: nextStep, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions)); + await checkpointer.putWrites(nextConfig2, inputWrites, uuid52(INPUT2, checkpoint.id)); + return patchCheckpointMap2(nextConfig2, saved ? saved.metadata : undefined); + } + if (config3.configurable?.checkpoint_id === undefined && saved?.pendingWrites !== undefined && saved.pendingWrites.length > 0) { + const nextTasks = _prepareNextTasks2(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + store: this.store, + checkpointer: this.checkpointer, + step: (saved.metadata?.step ?? -1) + 1 + }); + const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); + if (nullWrites.length > 0) + _applyWrites2(saved.checkpoint, channels, [{ + name: INPUT2, + writes: nullWrites, + triggers: [] + }], undefined, this.triggerToNodes); + for (const [tid, k, v] of saved.pendingWrites) { + if ([ + "__error__", + "__interrupt__", + SCHEDULED + ].includes(k) || nextTasks[tid] === undefined) + continue; + nextTasks[tid].writes.push([k, v]); + } + const tasks2 = Object.values(nextTasks).filter((task2) => { + return task2.writes.length > 0; + }); + if (tasks2.length > 0) + _applyWrites2(checkpoint, channels, tasks2, undefined, this.triggerToNodes); + } + const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { + return Object.values(seenVersions); + }).flat().find((v) => !!v); + const validUpdates = []; + if (updates.length === 1) { + let { values: values2, asNode: asNode2, taskId } = updates[0]; + if (asNode2 === undefined && Object.keys(this.nodes).length === 1) + [asNode2] = Object.keys(this.nodes); + else if (asNode2 === undefined && nonNullVersion === undefined) { + if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== undefined) + asNode2 = this.inputChannels; + } else if (asNode2 === undefined) { + const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n4, seen]) => { + return Object.values(seen).map((v) => { + return [v, n4]; + }); + }).flat().filter(([_, v]) => v !== INTERRUPT3).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); + if (lastSeenByNode) { + if (lastSeenByNode.length === 1) + asNode2 = lastSeenByNode[0][1]; + else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) + asNode2 = lastSeenByNode[lastSeenByNode.length - 1][1]; + } + } + if (asNode2 === undefined) + throw new InvalidUpdateError2(`Ambiguous update, specify "asNode"`); + validUpdates.push({ + values: values2, + asNode: asNode2, + taskId + }); + } else + for (const { asNode: asNode2, values: values2, taskId } of updates) { + if (asNode2 == null) + throw new InvalidUpdateError2(`"asNode" is required when applying multiple updates`); + validUpdates.push({ + values: values2, + asNode: asNode2, + taskId + }); + } + const tasks = []; + for (const { asNode: asNode2, values: values2, taskId } of validUpdates) { + if (this.nodes[asNode2] === undefined) + throw new InvalidUpdateError2(`Node "${asNode2.toString()}" does not exist`); + const writers = this.nodes[asNode2].getWriters(); + if (!writers.length) + throw new InvalidUpdateError2(`No writers found for node "${asNode2.toString()}"`); + tasks.push({ + name: asNode2, + input: values2, + proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], + writes: [], + triggers: [INTERRUPT3], + id: taskId ?? uuid52("__interrupt__", checkpoint.id), + writers: [] + }); + } + for (const task2 of tasks) + await task2.proc.invoke(task2.input, patchConfig({ + ...config3, + store: config3?.store ?? this.store + }, { + runName: config3.runName ?? `${this.getName()}UpdateState`, + configurable: { + [CONFIG_KEY_SEND2]: (items) => task2.writes.push(...items), + [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, task2, select_, fresh_) + } + })); + for (const task2 of tasks) { + const channelWrites = task2.writes.filter((w) => w[0] !== PUSH2); + if (saved !== undefined && channelWrites.length > 0) + await checkpointer.putWrites(checkpointConfig, channelWrites, task2.id); + } + _applyWrites2(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const newVersions = getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions); + const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, step + 1), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, newVersions); + for (const task2 of tasks) { + const pushWrites = task2.writes.filter((w) => w[0] === PUSH2); + if (pushWrites.length > 0) + await checkpointer.putWrites(nextConfig, pushWrites, task2.id); + } + return patchCheckpointMap2(nextConfig, saved ? saved.metadata : undefined); + }; + let currentConfig = startConfig; + for (const { updates } of supersteps) + currentConfig = await updateSuperStep(currentConfig, updates); + return currentConfig; } - websocket._url = parsedUrl.href; - const isSecure = parsedUrl.protocol === "wss:"; - const isIpcUrl = parsedUrl.protocol === "ws+unix:"; - let invalidUrlMessage; - if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { - invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"'; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = "The URL contains a fragment identifier"; + async updateState(inputConfig, values, asNode) { + return this.bulkUpdateState(inputConfig, [{ updates: [{ + values, + asNode + }] }]); } - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - if (websocket._redirects === 0) { - throw err; + _defaults(config3) { + const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config3; + let streamModeSingle = true; + const defaultDebug = debug !== undefined ? debug : this.debug; + let defaultOutputKeys = outputKeys; + if (defaultOutputKeys === undefined) + defaultOutputKeys = this.streamChannelsAsIs; + else + validateKeys2(defaultOutputKeys, this.channels); + let defaultInputKeys = inputKeys; + if (defaultInputKeys === undefined) + defaultInputKeys = this.inputChannels; + else + validateKeys2(defaultInputKeys, this.channels); + const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; + const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; + let defaultStreamMode; + if (streamMode !== undefined) { + defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; + streamModeSingle = typeof streamMode === "string"; } else { - emitErrorAndClose(websocket, err); - return; + if (config3.configurable?.["__pregel_task_id"] !== undefined) + defaultStreamMode = ["values"]; + else + defaultStreamMode = this.streamMode; + streamModeSingle = true; } + let defaultCheckpointer; + if (this.checkpointer === false) + defaultCheckpointer = undefined; + else if (config3 !== undefined && config3.configurable?.["__pregel_checkpointer"] !== undefined) + defaultCheckpointer = config3.configurable[CONFIG_KEY_CHECKPOINTER2]; + else if (this.checkpointer === true) + throw new Error("checkpointer: true cannot be used for root graphs."); + else + defaultCheckpointer = this.checkpointer; + const defaultStore = config3.store ?? this.store; + const defaultCache = config3.cache ?? this.cache; + if (config3.durability != null && config3.checkpointDuring != null) + throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); + const checkpointDuringDurability = (() => { + if (config3.checkpointDuring == null) + return; + if (config3.checkpointDuring === false) + return "exit"; + return "async"; + })(); + const defaultDurability = config3.durability ?? checkpointDuringDurability ?? config3?.configurable?.["__pregel_durability"] ?? "async"; + return [ + defaultDebug, + defaultStreamMode, + defaultInputKeys, + defaultOutputKeys, + rest, + defaultInterruptBefore, + defaultInterruptAfter, + defaultCheckpointer, + defaultStore, + streamModeSingle, + defaultCache, + defaultDurability + ]; } - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString("base64"); - const request = isSecure ? https.request : http.request; - const protocolSet = new Set; - let perMessageDeflate; - opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - "Sec-WebSocket-Version": opts.protocolVersion, - "Sec-WebSocket-Key": key, - Connection: "Upgrade", - Upgrade: "websocket" - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate({ - ...opts.perMessageDeflate, - isServer: false, - maxPayload: opts.maxPayload - }); - opts.headers["Sec-WebSocket-Extensions"] = format3({ - [PerMessageDeflate.extensionName]: perMessageDeflate.offer() - }); + async stream(input, options) { + const abortController = new AbortController; + const config3 = { + recursionLimit: this.config?.recursionLimit, + ...options, + signal: combineAbortSignals2(options?.signal, abortController.signal).signal + }; + const stream2 = await super.stream(input, config3); + return new IterableReadableStreamWithAbortSignal2(options?.encoding === "text/event-stream" ? toEventStream2(stream2) : stream2, abortController); } - if (protocols.length) { - for (const protocol of protocols) { - if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { - throw new SyntaxError("An invalid or duplicated subprotocol was specified"); - } - protocolSet.add(protocol); + async#streamEventsV3(input, options) { + const { version: version6, encoding, transformers: userTransformers, ...restOptions } = options; + const streamOptions = { + recursionLimit: this.config?.recursionLimit, + ...restOptions, + configurable: { + ...this.config?.configurable, + ...restOptions?.configurable + }, + version: version6, + streamMode: STREAM_EVENTS_V3_MODES2, + subgraphs: true, + encoding: undefined + }; + const sourcePromise = this.stream(input, streamOptions); + const graphRun = createGraphRunStream2({ [Symbol.asyncIterator]: async function* () { + const src = await sourcePromise; + for await (const chunk of src) + yield chunk; + } }, [...this.streamTransformers ?? [], ...userTransformers ?? []]); + if (encoding === "text/event-stream") { + const abortController = new AbortController; + abortController.signal.addEventListener("abort", () => graphRun.abort(abortController.signal.reason), { once: true }); + return new IterableReadableStreamWithAbortSignal2(protocolEventsToEventStream2(graphRun), abortController); } - opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); + return graphRun; } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers["Sec-WebSocket-Origin"] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } + streamEvents(input, options, streamOptions) { + if (options.version === "v3") + return this.#streamEventsV3(input, options); + const abortController = new AbortController; + const config3 = { + recursionLimit: this.config?.recursionLimit, + ...options, + callbacks: combineCallbacks2(this.config?.callbacks, options?.callbacks), + signal: combineAbortSignals2(options?.signal, abortController.signal).signal + }; + return new IterableReadableStreamWithAbortSignal2(super.streamEvents(input, config3, streamOptions), abortController); } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + async _validateInput(input) { + return input; } - if (isIpcUrl) { - const parts = opts.path.split(":"); - opts.socketPath = parts[0]; - opts.path = parts[1]; + async _validateContext(context2) { + return context2; } - let req; - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; - const headers = options && options.headers; - options = { ...options, headers: {} }; - if (headers) { - for (const [key2, value] of Object.entries(headers)) { - options.headers[key2.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount("redirect") === 0) { - const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; - if (!isSameHost || websocket._originalSecure && !isSecure) { - delete opts.headers.authorization; - delete opts.headers.cookie; - if (!isSameHost) - delete opts.headers.host; - opts.auth = undefined; - } - } - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); - } - req = websocket._req = request(opts); - if (websocket._redirects) { - websocket.emit("redirect", websocket.url, req); + async* _streamIterator(input, options) { + const streamEncoding = "version" in (options ?? {}) ? undefined : options?.encoding ?? undefined; + const streamSubgraphs = options?.subgraphs; + const inputConfig = ensureLangGraphConfig2(this.config, options); + if (inputConfig.recursionLimit === undefined || inputConfig.recursionLimit < 1) + throw new Error(`Passed "recursionLimit" must be at least 1.`); + if (this.checkpointer !== undefined && this.checkpointer !== false && inputConfig.configurable === undefined) + throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); + const validInput = await this._validateInput(input); + const { runId, ...restConfig } = inputConfig; + const [debug, streamMode, , outputKeys, config3, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache2, durability] = this._defaults(restConfig); + config3.metadata = { + ls_integration: "langgraph", + ...config3.metadata + }; + if (typeof config3.context !== "undefined") + config3.context = await this._validateContext(config3.context); + else + config3.configurable = await this._validateContext(config3.configurable); + const stream2 = new IterableReadableWritableStream2({ modes: new Set(streamMode) }); + if (this.checkpointer === true) { + config3.configurable ??= {}; + const ns3 = config3.configurable["checkpoint_ns"] ?? ""; + config3.configurable[CONFIG_KEY_CHECKPOINT_NS2] = ns3.split("|").map((part) => part.split(":")[0]).join("|"); } - } else { - req = websocket._req = request(opts); - } - if (opts.timeout) { - req.on("timeout", () => { - abortHandshake(websocket, req, "Opening handshake has timed out"); - }); - } - req.on("error", (err) => { - if (req === null || req[kAborted]) - return; - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - req.on("response", (res) => { - const location2 = res.headers.location; - const statusCode = res.statusCode; - if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake(websocket, req, "Maximum redirects exceeded"); - return; - } - req.abort(); - let addr; - try { - addr = new URL5(location2, address); - } catch (e) { - const err = new SyntaxError(`Invalid URL: ${location2}`); - emitErrorAndClose(websocket, err); - return; + if (streamMode.includes("messages")) { + const messageStreamer = options?.version === "v3" ? new StreamProtocolMessagesHandler2((chunk) => stream2.push(chunk)) : new StreamMessagesHandler2((chunk) => stream2.push(chunk)); + const { callbacks } = config3; + if (callbacks === undefined) + config3.callbacks = [messageStreamer]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat(messageStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(messageStreamer, true); + config3.callbacks = copiedCallbacks; } - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit("unexpected-response", req, res)) { - abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`); - } - }); - req.on("upgrade", (res, socket, head) => { - websocket.emit("upgrade", res); - if (websocket.readyState !== WebSocket2.CONNECTING) - return; - req = websocket._req = null; - const upgrade = res.headers.upgrade; - if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") { - abortHandshake(websocket, socket, "Invalid Upgrade header"); - return; - } - const digest = createHash4("sha1").update(key + GUID).digest("base64"); - if (res.headers["sec-websocket-accept"] !== digest) { - abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); - return; } - const serverProt = res.headers["sec-websocket-protocol"]; - let protError; - if (serverProt !== undefined) { - if (!protocolSet.size) { - protError = "Server sent a subprotocol but none was requested"; - } else if (!protocolSet.has(serverProt)) { - protError = "Server sent an invalid subprotocol"; + if (streamMode.includes("tools")) { + const toolStreamer = new StreamToolsHandler2((chunk) => stream2.push(chunk)); + const { callbacks } = config3; + if (callbacks === undefined) + config3.callbacks = [toolStreamer]; + else if (Array.isArray(callbacks)) + config3.callbacks = callbacks.concat(toolStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(toolStreamer, true); + config3.callbacks = copiedCallbacks; } - } else if (protocolSet.size) { - protError = "Server sent no subprotocol"; - } - if (protError) { - abortHandshake(websocket, socket, protError); - return; } - if (serverProt) - websocket._protocol = serverProt; - const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; - if (secWebSocketExtensions !== undefined) { - if (!perMessageDeflate) { - const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested"; - abortHandshake(websocket, socket, message); + config3.writer ??= (chunk) => { + if (!streamMode.includes("custom")) return; - } - let extensions; + const ns3 = getConfig2()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS2]?.split("|").slice(0, -1); + stream2.push([ + ns3 ?? [], + "custom", + chunk + ]); + }; + config3.interrupt ??= this.userInterrupt ?? interrupt2; + if (config3.serverInfo == null) + config3.serverInfo = _buildServerInfo2(config3); + const callbackManagerOptions = { tracerInheritableMetadata: _getTracingMetadataDefaults2(config3) }; + const runManager = await (await CallbackManager._configureSync(config3?.callbacks, undefined, config3?.tags, undefined, config3?.metadata, undefined, callbackManagerOptions))?.handleChainStart(this.toJSON(), _coerceToDict4(input, "input"), runId, undefined, undefined, undefined, config3?.runName ?? this.getName()); + const channelSpecs = getOnlyChannels2(this.channels); + let loop; + let loopError; + const createAndRunLoop = async () => { try { - extensions = parse11(secWebSocketExtensions); - } catch (err) { - const message = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message); - return; - } - const extensionNames = Object.keys(extensions); - if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { - const message = "Server indicated an extension that was not requested"; - abortHandshake(websocket, socket, message); - return; + loop = await PregelLoop3.initialize({ + input: validInput, + config: config3, + checkpointer, + nodes: this.nodes, + channelSpecs, + outputKeys, + streamKeys: this.streamChannelsAsIs, + store, + cache: cache2, + stream: stream2, + interruptAfter, + interruptBefore, + manager: runManager, + debug: this.debug, + triggerToNodes: this.triggerToNodes, + durability + }); + const runner = new PregelRunner2({ + loop, + nodeFinished: config3.configurable?.[CONFIG_KEY_NODE_FINISHED2] + }); + if (options?.subgraphs) + loop.config.configurable = { + ...loop.config.configurable, + [CONFIG_KEY_STREAM2]: loop.stream + }; + await this._runLoop({ + loop, + runner, + debug, + config: config3 + }); + if (durability === "sync") + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = e; + } finally { + try { + if (loop) { + await loop.store?.stop(); + await loop.cache?.stop(); + } + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = loopError ?? e; + } + if (loopError) + stream2.error(loopError); + else + stream2.close(); } - try { - perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); - } catch (err) { - const message = "Invalid Sec-WebSocket-Extensions header"; - abortHandshake(websocket, socket, message); - return; + }; + const runLoopPromise = createAndRunLoop(); + try { + for await (const chunk of stream2) { + if (chunk === undefined) + throw new Error("Data structure error."); + const [namespace, mode, payload, meta3] = chunk; + if (streamMode.includes(mode)) { + if (streamEncoding === "text/event-stream") { + if (streamSubgraphs) + yield [ + namespace, + mode, + payload + ]; + else + yield [ + null, + mode, + payload + ]; + continue; + } + if (streamSubgraphs && !streamModeSingle) + yield meta3 !== undefined ? [ + namespace, + mode, + payload, + meta3 + ] : [ + namespace, + mode, + payload + ]; + else if (!streamModeSingle) + yield [mode, payload]; + else if (streamSubgraphs) + yield [namespace, payload]; + else + yield payload; + } } - websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } catch (e) { + await runManager?.handleChainError(loopError); + throw e; + } finally { + await runLoopPromise; } - websocket.setSocket(socket, head, { - allowSynchronousEvents: opts.allowSynchronousEvents, - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } - } - function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket2.CLOSING; - websocket._errorEmitted = true; - websocket.emit("error", err); - websocket.emitClose(); - } - function netConnect(options) { - options.path = options.socketPath; - return net.connect(options); - } - function tlsConnect(options) { - options.path = undefined; - if (!options.servername && options.servername !== "") { - options.servername = net.isIP(options.host) ? "" : options.host; + await runManager?.handleChainEnd(loop?.output ?? {}, runId, undefined, undefined, undefined); } - return tls.connect(options); - } - function abortHandshake(websocket, stream2, message) { - websocket._readyState = WebSocket2.CLOSING; - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake); - if (stream2.setHeader) { - stream2[kAborted] = true; - stream2.abort(); - if (stream2.socket && !stream2.socket.destroyed) { - stream2.socket.destroy(); + async invoke(input, options) { + const streamMode = options?.streamMode ?? "values"; + const config3 = { + ...options, + outputKeys: options?.outputKeys ?? this.outputChannels, + streamMode, + encoding: undefined + }; + const chunks = []; + const stream2 = await this.stream(input, config3); + const interruptChunks = []; + let latest; + for await (const chunk of stream2) + if (streamMode === "values") + if (isInterrupted2(chunk)) + interruptChunks.push(chunk[INTERRUPT3]); + else + latest = chunk; + else + chunks.push(chunk); + if (streamMode === "values") { + if (interruptChunks.length > 0) { + const interrupts = interruptChunks.flat(1); + if (latest == null) + return { [INTERRUPT3]: interrupts }; + if (typeof latest === "object") + return { + ...latest, + [INTERRUPT3]: interrupts + }; + } + return latest; } - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream2.destroy(err); - stream2.once("error", websocket.emit.bind(websocket, "error")); - stream2.once("close", websocket.emitClose.bind(websocket)); - } - } - function sendAfterClose(websocket, data, cb) { - if (data) { - const length = isBlob(data) ? data.size : toBuffer(data).length; - if (websocket._socket) - websocket._sender._bufferedBytes += length; - else - websocket._bufferedAmount += length; + return chunks; } - if (cb) { - const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`); - process.nextTick(cb, err); - } - } - function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket]; - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - if (websocket._socket[kWebSocket] === undefined) - return; - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - if (code === 1005) - websocket.close(); - else - websocket.close(code, reason); - } - function receiverOnDrain() { - const websocket = this[kWebSocket]; - if (!websocket.isPaused) - websocket._socket.resume(); - } - function receiverOnError(err) { - const websocket = this[kWebSocket]; - if (websocket._socket[kWebSocket] !== undefined) { - websocket._socket.removeListener("data", socketOnData); - process.nextTick(resume, websocket._socket); - websocket.close(err[kStatusCode]); + async _runLoop(params) { + const { loop, runner, debug, config: config3 } = params; + let tickError; + try { + while (await loop.tick({ inputKeys: this.inputChannels })) { + for (const { task: task2 } of await loop._matchCachedWrites()) + loop._outputWrites(task2.id, task2.writes, true); + if (debug) + printStepCheckpoint2(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); + if (debug) + printStepTasks2(loop.step, Object.values(loop.tasks)); + await runner.tick({ + timeout: this.stepTimeout, + retryPolicy: this.retryPolicy, + onStepWrite: (step, writes) => { + if (debug) + printStepWrites2(step, writes, this.streamChannelsList); + }, + maxConcurrency: config3.maxConcurrency, + signal: config3.signal + }); + } + if (loop.status === "out_of_steps") + throw new GraphRecursionError2([ + `Recursion limit of ${config3.recursionLimit} reached`, + "without hitting a stop condition. You can increase the", + `limit by setting the "recursionLimit" config key.` + ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); + } catch (e) { + tickError = e; + if (!await loop.finishAndHandleError(tickError)) + throw e; + } finally { + if (tickError === undefined) + await loop.finishAndHandleError(); + } } - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); + async clearCache() { + await this.cache?.clear([]); } - } - function receiverOnFinish() { - this[kWebSocket].emitClose(); - } - function receiverOnMessage(data, isBinary) { - this[kWebSocket].emit("message", data, isBinary); - } - function receiverOnPing(data) { - const websocket = this[kWebSocket]; - if (websocket._autoPong) - websocket.pong(data, !this._isServer, NOOP); - websocket.emit("ping", data); - } - function receiverOnPong(data) { - this[kWebSocket].emit("pong", data); - } - function resume(stream2) { - stream2.resume(); - } - function senderOnError(err) { - const websocket = this[kWebSocket]; - if (websocket.readyState === WebSocket2.CLOSED) - return; - if (websocket.readyState === WebSocket2.OPEN) { - websocket._readyState = WebSocket2.CLOSING; - setCloseTimer(websocket); + }; + OMITTED_KEYS2 = new Set([ + "key", + "token", + "secret", + "password", + "auth" + ]); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js +var EphemeralValue3; +var init_ephemeral_value2 = __esm(() => { + init_errors9(); + init_base16(); + EphemeralValue3 = class EphemeralValue4 extends BaseChannel2 { + lc_graph_name = "EphemeralValue"; + guard; + value = []; + constructor(guard = true) { + super(); + this.guard = guard; } - this._socket.end(); - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit("error", err); + fromCheckpoint(checkpoint) { + const empty = new EphemeralValue4(this.guard); + if (typeof checkpoint !== "undefined") + empty.value = [checkpoint]; + return empty; } - } - function setCloseTimer(websocket) { - websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout); - } - function socketOnClose() { - const websocket = this[kWebSocket]; - this.removeListener("close", socketOnClose); - this.removeListener("data", socketOnData); - this.removeListener("end", socketOnEnd); - websocket._readyState = WebSocket2.CLOSING; - if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) { - const chunk = this.read(this._readableState.length); - websocket._receiver.write(chunk); + update(values) { + if (values.length === 0) { + const updated = this.value.length > 0; + this.value = []; + return updated; + } + if (values.length !== 1 && this.guard) + throw new InvalidUpdateError2("EphemeralValue can only receive one value per step."); + this.value = [values[values.length - 1]]; + return true; } - websocket._receiver.end(); - this[kWebSocket] = undefined; - clearTimeout(websocket._closeTimer); - if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { - websocket.emitClose(); - } else { - websocket._receiver.on("error", receiverOnFinish); - websocket._receiver.on("finish", receiverOnFinish); + get() { + if (this.value.length === 0) + throw new EmptyChannelError2; + return this.value[0]; } - } - function socketOnData(chunk) { - if (!this[kWebSocket]._receiver.write(chunk)) { - this.pause(); + checkpoint() { + if (this.value.length === 0) + throw new EmptyChannelError2; + return this.value[0]; } - } - function socketOnEnd() { - const websocket = this[kWebSocket]; - websocket._readyState = WebSocket2.CLOSING; - websocket._receiver.end(); - this.end(); - } - function socketOnError() { - const websocket = this[kWebSocket]; - this.removeListener("error", socketOnError); - this.on("error", NOOP); - if (websocket) { - websocket._readyState = WebSocket2.CLOSING; - this.destroy(); + isAvailable() { + return this.value.length !== 0; } - } + }; }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/stream.js -var require_stream5 = __commonJS((exports, module) => { - var WebSocket2 = require_websocket(); - var { Duplex } = __require("stream"); - function emitClose(stream2) { - stream2.emit("close"); - } - function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } - } - function duplexOnError(err) { - this.removeListener("error", duplexOnError); - this.destroy(); - if (this.listenerCount("error") === 0) { - this.emit("error", err); +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/index.js +var init_classic2 = __esm(() => { + init_external(); + init_external(); +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/index.js +var init_v44 = __esm(() => { + init_classic2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/graph.js +var init_graph4 = __esm(() => { + init_constants5(); + init_errors9(); + init_utils14(); + init_write2(); + init_read2(); + init_subgraph2(); + init_pregel2(); + init_ephemeral_value2(); + init_runnables(); + init_graph(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/types.js +function isStandardSchema3(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; +} +function isStandardJSONSchema2(schema) { + return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; +} +var init_types13 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/adapter.js +function getJsonSchemaFromSchema2(schema) { + if (isStandardJSONSchema2(schema)) + try { + return schema["~standard"].jsonSchema.input({ target: "draft-07" }); + } catch { + return; } - } - function createWebSocketStream(ws, options) { - let terminateOnDestroy = true; - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - ws.on("message", function message(msg, isBinary) { - const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; - if (!duplex.push(data)) - ws.pause(); - }); - ws.once("error", function error51(err) { - if (duplex.destroyed) - return; - terminateOnDestroy = false; - duplex.destroy(err); - }); - ws.once("close", function close() { - if (duplex.destroyed) - return; - duplex.push(null); - }); - duplex._destroy = function(err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose, duplex); - return; - } - let called = false; - ws.once("error", function error51(err2) { - called = true; - callback(err2); - }); - ws.once("close", function close() { - if (!called) - callback(err); - process.nextTick(emitClose, duplex); - }); - if (terminateOnDestroy) - ws.terminate(); - }; - duplex._final = function(callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open() { - duplex._final(callback); - }); - return; - } - if (ws._socket === null) - return; - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) - duplex.destroy(); - } else { - ws._socket.once("finish", function finish() { - callback(); - }); - ws.close(); - } - }; - duplex._read = function() { - if (ws.isPaused) - ws.resume(); - }; - duplex._write = function(chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once("open", function open() { - duplex._write(chunk, encoding, callback); - }); - return; +} +function getSchemaDefaultGetter2(schema) { + if (schema == null) + return; + if (!isStandardSchema3(schema)) + return; + try { + const result = schema["~standard"].validate(undefined); + if (result && typeof result === "object" && !(("then" in result) && typeof result.then === "function")) { + const syncResult = result; + if (!syncResult.issues) { + const defaultValue = syncResult.value; + return () => defaultValue; } - ws.send(chunk, callback); - }; - duplex.on("end", duplexOnEnd); - duplex.on("error", duplexOnError); - return duplex; - } - module.exports = createWebSocketStream; + } + } catch {} +} +var init_adapter2 = __esm(() => { + init_types13(); }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/subprotocol.js -var require_subprotocol = __commonJS((exports, module) => { - var { tokenChars } = require_validation(); - function parse11(header) { - const protocols = new Set; - let start = -1; - let end = -1; - let i = 0; - for (i;i < header.length; i++) { - const code = header.charCodeAt(i); - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) - start = i; - } else if (i !== 0 && (code === 32 || code === 9)) { - if (end === -1 && start !== -1) - end = i; - } else if (code === 44) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (end === -1) - end = i; - const protocol2 = header.slice(start, end); - if (protocols.has(protocol2)) { - throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); - } - protocols.add(protocol2); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/untracked_value.js +var MISSING2, UntrackedValueChannel3; +var init_untracked_value2 = __esm(() => { + init_errors9(); + init_base16(); + MISSING2 = Symbol.for("langgraph.channel.missing"); + UntrackedValueChannel3 = class UntrackedValueChannel4 extends BaseChannel2 { + lc_graph_name = "UntrackedValue"; + guard; + _value = MISSING2; + initialValueFactory; + constructor(options) { + super(); + this.guard = options?.guard ?? true; + this.initialValueFactory = options?.initialValueFactory; + if (this.initialValueFactory) + this._value = this.initialValueFactory(); } - if (start === -1 || end !== -1) { - throw new SyntaxError("Unexpected end of input"); + fromCheckpoint(_checkpoint) { + return new UntrackedValueChannel4({ + guard: this.guard, + initialValueFactory: this.initialValueFactory + }); } - const protocol = header.slice(start, i); - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + update(values) { + if (values.length === 0) + return false; + if (values.length !== 1 && this.guard) + throw new InvalidUpdateError2("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this._value = values[values.length - 1]; + return true; } - protocols.add(protocol); - return protocols; - } - module.exports = { parse: parse11 }; + get() { + if (this._value === MISSING2) + throw new EmptyChannelError2; + return this._value; + } + checkpoint() {} + isAvailable() { + return this._value !== MISSING2; + } + }; }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/lib/websocket-server.js -var require_websocket_server = __commonJS((exports, module) => { - var EventEmitter2 = __require("events"); - var http = __require("http"); - var { Duplex } = __require("stream"); - var { createHash: createHash4 } = __require("crypto"); - var extension = require_extension(); - var PerMessageDeflate = require_permessage_deflate(); - var subprotocol = require_subprotocol(); - var WebSocket2 = require_websocket(); - var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants4(); - var keyRegex = /^[+/0-9A-Za-z]{22}==$/; - var RUNNING = 0; - var CLOSING = 1; - var CLOSED = 2; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/values/reduced.js +var REDUCED_VALUE_SYMBOL2, ReducedValue2; +var init_reduced2 = __esm(() => { + REDUCED_VALUE_SYMBOL2 = Symbol.for("langgraph.state.reduced_value"); + ReducedValue2 = class { + [REDUCED_VALUE_SYMBOL2] = true; + valueSchema; + inputSchema; + reducer; + jsonSchemaExtra; + constructor(valueSchema, init) { + this.reducer = init.reducer; + this.jsonSchemaExtra = init.jsonSchemaExtra; + this.valueSchema = valueSchema; + this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; + this.jsonSchemaExtra = init.jsonSchemaExtra; + } + static isInstance(value) { + return typeof value === "object" && value !== null && REDUCED_VALUE_SYMBOL2 in value && value[REDUCED_VALUE_SYMBOL2] === true; + } + }; +}); - class WebSocketServer extends EventEmitter2 { - constructor(options, callback) { - super(); - options = { - allowSynchronousEvents: true, - autoPong: true, - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - closeTimeout: CLOSE_TIMEOUT, - verifyClient: null, - noServer: false, - backlog: null, - server: null, - host: null, - path: null, - port: null, - WebSocket: WebSocket2, - ...options - }; - if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { - throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified"); - } - if (options.port != null) { - this._server = http.createServer((req, res) => { - const body = http.STATUS_CODES[426]; - res.writeHead(426, { - "Content-Length": body.length, - "Content-Type": "text/plain" - }); - res.end(body); - }); - this._server.listen(options.port, options.host, options.backlog, callback); - } else if (options.server) { - this._server = options.server; - } - if (this._server) { - const emitConnection = this.emit.bind(this, "connection"); - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, "listening"), - error: this.emit.bind(this, "error"), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - if (options.perMessageDeflate === true) - options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = new Set; - this._shouldEmitClose = false; - } - this.options = options; - this._state = RUNNING; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/values/untracked.js +var UNTRACKED_VALUE_SYMBOL2, UntrackedValue2; +var init_untracked2 = __esm(() => { + UNTRACKED_VALUE_SYMBOL2 = Symbol.for("langgraph.state.untracked_value"); + UntrackedValue2 = class { + [UNTRACKED_VALUE_SYMBOL2] = true; + schema; + guard; + constructor(schema, init) { + this.schema = schema; + this.guard = init?.guard ?? true; } - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - if (!this._server) - return null; - return this._server.address(); + static isInstance(value) { + return typeof value === "object" && value !== null && UNTRACKED_VALUE_SYMBOL2 in value; } - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once("close", () => { - cb(new Error("The server is not running")); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js +var init_named_barrier_value2 = __esm(() => { + init_errors9(); + init_base16(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/any_value.js +var init_any_value2 = __esm(() => { + init_errors9(); + init_base16(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js +var init_dynamic_barrier_value2 = __esm(() => { + init_errors9(); + init_base16(); + init_named_barrier_value2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/channels/index.js +var init_channels2 = __esm(() => { + init_base16(); + init_binop2(); + init_last_value2(); + init_topic2(); + init_ephemeral_value2(); + init_named_barrier_value2(); + init_any_value2(); + init_dynamic_barrier_value2(); + init_untracked_value2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/schema.js +var STATE_SCHEMA_SYMBOL2, StateSchema2; +var init_schema2 = __esm(() => { + init_binop2(); + init_last_value2(); + init_types13(); + init_adapter2(); + init_untracked_value2(); + init_channels2(); + init_reduced2(); + init_untracked2(); + STATE_SCHEMA_SYMBOL2 = Symbol.for("langgraph.state.state_schema"); + StateSchema2 = class { + [STATE_SCHEMA_SYMBOL2] = true; + constructor(fields) { + this.fields = fields; + } + getChannels() { + const channels = {}; + for (const [key, value] of Object.entries(this.fields)) + if (ReducedValue2.isInstance(value)) { + const defaultGetter = getSchemaDefaultGetter2(value.valueSchema); + channels[key] = new BinaryOperatorAggregate3(value.reducer, defaultGetter); + } else if (UntrackedValue2.isInstance(value)) { + const defaultGetter = value.schema ? getSchemaDefaultGetter2(value.schema) : undefined; + channels[key] = new UntrackedValueChannel3({ + guard: value.guard, + initialValueFactory: defaultGetter }); + } else if (isStandardSchema3(value)) + channels[key] = new LastValue3(getSchemaDefaultGetter2(value)); + else + throw new Error(`Invalid state field "${key}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`); + return channels; + } + getJsonSchema() { + const properties = {}; + const required3 = []; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (ReducedValue2.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema2(value.valueSchema); + if (value.jsonSchemaExtra) + fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue2.isInstance(value)) + fieldSchema = value.schema ? getJsonSchemaFromSchema2(value.schema) : undefined; + else if (isStandardSchema3(value)) + fieldSchema = getJsonSchemaFromSchema2(value); + if (fieldSchema) { + properties[key] = fieldSchema; + let hasDefault = false; + if (ReducedValue2.isInstance(value)) + hasDefault = getSchemaDefaultGetter2(value.valueSchema) !== undefined; + else if (UntrackedValue2.isInstance(value)) + hasDefault = value.schema ? getSchemaDefaultGetter2(value.schema) !== undefined : false; + else + hasDefault = getSchemaDefaultGetter2(value) !== undefined; + if (!hasDefault) + required3.push(key); } - process.nextTick(emitClose, this); - return; - } - if (cb) - this.once("close", cb); - if (this._state === CLOSING) - return; - this._state = CLOSING; - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - this._removeListeners(); - this._removeListeners = this._server = null; - server.close(() => { - emitClose(this); - }); } + return { + type: "object", + properties, + required: required3.length > 0 ? required3 : undefined + }; } - shouldHandle(req) { - if (this.options.path) { - const index2 = req.url.indexOf("?"); - const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url; - if (pathname !== this.options.path) - return false; + getInputJsonSchema() { + const properties = {}; + for (const [key, value] of Object.entries(this.fields)) { + let fieldSchema; + if (ReducedValue2.isInstance(value)) { + fieldSchema = getJsonSchemaFromSchema2(value.inputSchema); + if (value.jsonSchemaExtra) + fieldSchema = { + ...fieldSchema ?? {}, + ...value.jsonSchemaExtra + }; + } else if (UntrackedValue2.isInstance(value)) + fieldSchema = value.schema ? getJsonSchemaFromSchema2(value.schema) : undefined; + else if (isStandardSchema3(value)) + fieldSchema = getJsonSchemaFromSchema2(value); + if (fieldSchema) + properties[key] = fieldSchema; } - return true; + return { + type: "object", + properties + }; } - handleUpgrade(req, socket, head, cb) { - socket.on("error", socketOnError); - const key = req.headers["sec-websocket-key"]; - const upgrade = req.headers.upgrade; - const version4 = +req.headers["sec-websocket-version"]; - if (req.method !== "GET") { - const message = "Invalid HTTP method"; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); - return; - } - if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") { - const message = "Invalid Upgrade header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (key === undefined || !keyRegex.test(key)) { - const message = "Missing or invalid Sec-WebSocket-Key header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - if (version4 !== 13 && version4 !== 8) { - const message = "Missing or invalid Sec-WebSocket-Version header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { - "Sec-WebSocket-Version": "13, 8" - }); - return; - } - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; - let protocols = new Set; - if (secWebSocketProtocol !== undefined) { - try { - protocols = subprotocol.parse(secWebSocketProtocol); - } catch (err) { - const message = "Invalid Sec-WebSocket-Protocol header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; - const extensions = {}; - if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) { - const perMessageDeflate = new PerMessageDeflate({ - ...this.options.perMessageDeflate, - isServer: true, - maxPayload: this.options.maxPayload - }); - try { - const offers = extension.parse(secWebSocketExtensions); - if (offers[PerMessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); - extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - if (this.options.verifyClient) { - const info = { - origin: req.headers[`${version4 === 8 ? "sec-websocket-origin" : "origin"}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - }); - return; - } - if (!this.options.verifyClient(info)) - return abortHandshake(socket, 401); - } - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + getChannelKeys() { + return Object.entries(this.fields).map(([key]) => key); } - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - if (!socket.readable || !socket.writable) - return socket.destroy(); - if (socket[kWebSocket]) { - throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration"); - } - if (this._state > RUNNING) - return abortHandshake(socket, 503); - const digest = createHash4("sha1").update(key + GUID).digest("base64"); - const headers = [ - "HTTP/1.1 101 Switching Protocols", - "Upgrade: websocket", - "Connection: Upgrade", - `Sec-WebSocket-Accept: ${digest}` - ]; - const ws = new this.options.WebSocket(null, undefined, this.options); - if (protocols.size) { - const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; + getAllKeys() { + return Object.keys(this.fields); + } + async validateInput(data) { + if (data == null || typeof data !== "object") + return data; + const result = {}; + for (const [key, value] of Object.entries(data)) { + const fieldDef = this.fields[key]; + if (fieldDef === undefined) { + result[key] = value; + continue; } + let schema; + if (ReducedValue2.isInstance(fieldDef)) + schema = fieldDef.inputSchema; + else if (UntrackedValue2.isInstance(fieldDef)) + schema = fieldDef.schema; + else if (isStandardSchema3(fieldDef)) + schema = fieldDef; + if (schema) { + const validationResult = await schema["~standard"].validate(value); + if (validationResult.issues) + throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); + result[key] = validationResult.value; + } else + result[key] = value; } - if (extensions[PerMessageDeflate.extensionName]) { - const params = extensions[PerMessageDeflate.extensionName].params; - const value = extension.format({ - [PerMessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - this.emit("headers", headers, req); - socket.write(headers.concat(`\r -`).join(`\r -`)); - socket.removeListener("error", socketOnError); - ws.setSocket(socket, head, { - allowSynchronousEvents: this.options.allowSynchronousEvents, - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - if (this.clients) { - this.clients.add(ws); - ws.on("close", () => { - this.clients.delete(ws); - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - cb(ws, req); + return result; + } + static isInstance(value) { + return typeof value === "object" && value !== null && STATE_SCHEMA_SYMBOL2 in value && value[STATE_SCHEMA_SYMBOL2] === true; + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/messages_reducer.js +function messagesStateReducer2(left, right) { + const leftArray = Array.isArray(left) ? left : [left]; + const rightArray = Array.isArray(right) ? right : [right]; + const leftMessages = leftArray.map(coerceMessageLikeToMessage); + const rightMessages = rightArray.map(coerceMessageLikeToMessage); + for (const m of leftMessages) + if (m.id === null || m.id === undefined) { + m.id = v44(); + m.lc_kwargs.id = m.id; + } + let removeAllIdx; + for (let i = 0;i < rightMessages.length; i += 1) { + const m = rightMessages[i]; + if (m.id === null || m.id === undefined) { + m.id = v44(); + m.lc_kwargs.id = m.id; } + if (RemoveMessage.isInstance(m) && m.id === "__remove_all__") + removeAllIdx = i; } - module.exports = WebSocketServer; - function addListeners(server, map2) { - for (const event of Object.keys(map2)) - server.on(event, map2[event]); - return function removeListeners() { - for (const event of Object.keys(map2)) { - server.removeListener(event, map2[event]); + if (removeAllIdx != null) + return rightMessages.slice(removeAllIdx + 1); + const merged = [...leftMessages]; + const mergedById = new Map(merged.map((m, i) => [m.id, i])); + const idsToRemove = /* @__PURE__ */ new Set; + for (const m of rightMessages) { + const existingIdx = mergedById.get(m.id); + if (existingIdx !== undefined) + if (RemoveMessage.isInstance(m)) + idsToRemove.add(m.id); + else { + idsToRemove.delete(m.id); + merged[existingIdx] = m; } - }; - } - function emitClose(server) { - server._state = CLOSED; - server.emit("close"); - } - function socketOnError() { - this.destroy(); - } - function abortHandshake(socket, code, message, headers) { - message = message || http.STATUS_CODES[code]; - headers = { - Connection: "close", - "Content-Type": "text/html", - "Content-Length": Buffer.byteLength(message), - ...headers - }; - socket.once("finish", socket.destroy); - socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r -` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r -`) + `\r -\r -` + message); - } - function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) { - if (server.listenerCount("wsClientError")) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - server.emit("wsClientError", err, socket, req); - } else { - abortHandshake(socket, code, message, headers); + else { + if (RemoveMessage.isInstance(m)) + throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); + mergedById.set(m.id, merged.length); + merged.push(m); } } + return merged.filter((m) => !idsToRemove.has(m.id)); +} +var REMOVE_ALL_MESSAGES2 = "__remove_all__"; +var init_messages_reducer2 = __esm(() => { + init_wrapper(); + init_messages(); }); -// ../../node_modules/.pnpm/ws@8.20.0/node_modules/ws/wrapper.mjs -var exports_wrapper = {}; -__export(exports_wrapper, { - subprotocol: () => import_subprotocol.default, - extension: () => import_extension3.default, - default: () => wrapper_default, - createWebSocketStream: () => import_stream37.default, - WebSocketServer: () => import_websocket_server.default, - WebSocket: () => import_websocket7.default, - Sender: () => import_sender.default, - Receiver: () => import_receiver.default, - PerMessageDeflate: () => import_permessage_deflate.default +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/prebuilt/messages.js +var MessagesValue2; +var init_messages7 = __esm(() => { + init_reduced2(); + init_messages_reducer2(); + init_v44(); + MessagesValue2 = new ReducedValue2(exports_external.custom().default(() => []), { + inputSchema: exports_external.custom(), + reducer: messagesStateReducer2, + jsonSchemaExtra: { + langgraph_type: "messages", + description: "A list of chat messages" + } + }); }); -var import_stream37, import_extension3, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket7, import_websocket_server, wrapper_default; -var init_wrapper2 = __esm(() => { - import_stream37 = __toESM(require_stream5(), 1); - import_extension3 = __toESM(require_extension(), 1); - import_permessage_deflate = __toESM(require_permessage_deflate(), 1); - import_receiver = __toESM(require_receiver(), 1); - import_sender = __toESM(require_sender(), 1); - import_subprotocol = __toESM(require_subprotocol(), 1); - import_websocket7 = __toESM(require_websocket(), 1); - import_websocket_server = __toESM(require_websocket_server(), 1); - wrapper_default = import_websocket7.default; + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/prebuilt/index.js +var init_prebuilt2 = __esm(() => { + init_messages7(); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/ws_execute.js -async function ensureWs() { - try { - const ws = await Promise.resolve().then(() => (init_wrapper2(), exports_wrapper)); - return { WebSocket: ws.default || ws.WebSocket || ws }; - } catch { - throw new Error("WebSocket-based execution requires the 'ws' package. Install it with: npm install ws"); +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/values/index.js +var init_values4 = __esm(() => { + init_reduced2(); + init_untracked2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/state/index.js +var init_state3 = __esm(() => { + init_types13(); + init_adapter2(); + init_reduced2(); + init_untracked2(); + init_schema2(); + init_messages7(); + init_prebuilt2(); + init_values4(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/zod/meta.js +function withLangGraph2(schema, meta3) { + if (meta3.reducer && !meta3.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) + meta3.default = defaultValueGetter; } -} -function buildWsUrl(dataplaneUrl) { - const wsUrl = dataplaneUrl.replace("https://", "wss://").replace("http://", "ws://"); - return `${wsUrl}/execute/ws`; -} -function buildAuthHeaders(apiKey) { - if (apiKey) { - return { "X-Api-Key": apiKey }; + if (meta3.reducer) { + const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta3.reducer?.schema ?? schema }); + schemaMetaRegistry2.extend(schemaWithReducer, () => meta3); + return schemaWithReducer; + } else { + schemaMetaRegistry2.extend(schema, () => meta3); + return schema; } - return {}; } - -class WSStreamControl { - constructor() { - Object.defineProperty(this, "_ws", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "_closed", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "_killed", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); +var SchemaMetaRegistry2 = class { + _map = /* @__PURE__ */ new Map; + _extensionCache = /* @__PURE__ */ new Map; + get(schema) { + return this._map.get(schema); } - _bind(ws) { - this._ws = ws; + extend(schema, predicate) { + const existingMeta = this.get(schema); + this._map.set(schema, predicate(existingMeta)); } - _unbind() { - this._closed = true; - this._ws = null; - } - get killed() { - return this._killed; + remove(schema) { + this._map.delete(schema); + return this; } - sendKill() { - this._killed = true; - if (this._ws && !this._closed && this._ws.readyState === 1) { - this._ws.send(JSON.stringify({ type: "kill" })); - } + has(schema) { + return this._map.has(schema); } - sendInput(data) { - if (this._ws && !this._closed && this._ws.readyState === 1) { - this._ws.send(JSON.stringify({ type: "input", data })); + getChannelsForSchema(schema) { + const channels = {}; + const shape = getInteropZodObjectShape(schema); + for (const [key, channelSchema] of Object.entries(shape)) { + const meta3 = this.get(channelSchema); + if (meta3?.reducer) + channels[key] = new BinaryOperatorAggregate3(meta3.reducer.fn, meta3.default); + else + channels[key] = new LastValue3(meta3?.default); } + return channels; } -} -function raiseForWsError(msg, commandId = "") { - const errorType = msg.error_type ?? "CommandError"; - const errorMsg = msg.error ?? "Unknown error"; - if (errorType === "CommandTimeout") { - throw new LangSmithCommandTimeoutError(errorMsg); - } - if (errorType === "CommandNotFound") { - throw new LangSmithSandboxOperationError(commandId ? `Command not found: ${commandId}` : errorMsg, commandId ? "reconnect" : "command", errorType); - } - if (errorType === "SessionExpired") { - throw new LangSmithSandboxOperationError(commandId ? `Session expired: ${commandId}` : errorMsg, commandId ? "reconnect" : "command", errorType); - } - throw new LangSmithSandboxOperationError(errorMsg, commandId ? "reconnect" : "command", errorType); -} -async function connectWs(url2, headers) { - const { WebSocket: WS } = await ensureWs(); - return new Promise((resolve2, reject) => { - const ws = new WS(url2, { headers }); - ws.on("open", () => { - ws.removeAllListeners("error"); - resolve2(ws); - }); - ws.on("error", (err) => { - ws.removeAllListeners("open"); - reject(new LangSmithSandboxConnectionError(`Failed to connect to sandbox WebSocket: ${err.message}`)); - }); - }); -} -async function* readWsMessages(ws) { - const messageQueue = []; - let resolve2 = null; - let error51 = null; - let done = false; - const onMessage = (data) => { - const raw2 = typeof data === "string" ? data : data.toString(); - const msg = JSON.parse(raw2); - messageQueue.push(msg); - if (resolve2) { - const r = resolve2; - resolve2 = null; - r(); - } - }; - const onClose = (code, reason) => { - done = true; - if (code === 1001) { - error51 = new LangSmithSandboxServerReloadError("Server is reloading, reconnect to resume"); - } else if (code !== 1000) { - error51 = new LangSmithSandboxConnectionError(`WebSocket connection closed unexpectedly (code: ${code}, reason: ${reason.toString()})`); - } - if (resolve2) { - const r = resolve2; - resolve2 = null; - r(); - } - }; - const onError2 = (err) => { - done = true; - if (!error51) { - error51 = new LangSmithSandboxConnectionError(`WebSocket connection error: ${err.message}`); - } - if (resolve2) { - const r = resolve2; - resolve2 = null; - r(); - } - }; - ws.on("message", onMessage); - ws.on("close", onClose); - ws.on("error", onError2); - try { - while (true) { - while (messageQueue.length > 0) { - yield messageQueue.shift(); - } - if (done) { - if (error51) { - throw error51; + getExtendedChannelSchemas(schema, effects) { + if (Object.keys(effects).length === 0) + return schema; + const cacheKey2 = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); + const cache2 = this._extensionCache.get(cacheKey2) ?? /* @__PURE__ */ new Map; + if (cache2.has(schema)) + return cache2.get(schema); + let modifiedSchema = schema; + if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { + const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema2]) => { + const meta3 = this.get(schema2); + let outputSchema = effects.withReducerSchema ? meta3?.reducer?.schema ?? schema2 : schema2; + if (effects.withJsonSchemaExtrasAsDescription && meta3?.jsonSchemaExtra) { + const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema2); + const strExtras = JSON.stringify({ + ...meta3.jsonSchemaExtra, + description + }); + outputSchema = outputSchema.describe(`lg:${strExtras}`); } - return; - } - await new Promise((r) => { - resolve2 = r; + return [key, outputSchema]; }); + modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); + if (isZodSchemaV3(modifiedSchema)) + modifiedSchema._def.unknownKeys = "strip"; } - } finally { - ws.removeListener("message", onMessage); - ws.removeListener("close", onClose); - ws.removeListener("error", onError2); - } -} -async function runWsStream(dataplaneUrl, apiKey, command, options = {}) { - const { timeout = 60, env, cwd, shell = "/bin/bash", onStdout, onStderr, commandId, idleTimeout = 300, killOnDisconnect = false, ttlSeconds = 600, pty } = options; - const wsUrl = buildWsUrl(dataplaneUrl); - const headers = buildAuthHeaders(apiKey); - const control = new WSStreamControl; - async function* stream2() { - let ws; - try { - ws = await connectWs(wsUrl, headers); - control._bind(ws); - const payload = { - type: "execute", - command, - timeout_seconds: timeout, - shell, - idle_timeout_seconds: idleTimeout, - kill_on_disconnect: killOnDisconnect, - ttl_seconds: ttlSeconds - }; - if (env) - payload.env = env; - if (cwd) - payload.cwd = cwd; - if (commandId) - payload.command_id = commandId; - if (pty) - payload.pty = true; - ws.send(JSON.stringify(payload)); - for await (const msg of readWsMessages(ws)) { - const msgType = msg.type; - if (msgType === "started") { - yield msg; - } else if (msgType === "stdout") { - if (onStdout) - onStdout(msg.data); - yield msg; - } else if (msgType === "stderr") { - if (onStderr) - onStderr(msg.data); - yield msg; - } else if (msgType === "exit") { - yield msg; - return; - } else if (msgType === "error") { - raiseForWsError(msg); - } - } - } finally { - control._unbind(); - if (ws && ws.readyState === 1) { - ws.close(); - } - } - } - return [stream2(), control]; -} -async function reconnectWsStream(dataplaneUrl, apiKey, commandId, options = {}) { - const { stdoutOffset = 0, stderrOffset = 0 } = options; - const wsUrl = buildWsUrl(dataplaneUrl); - const headers = buildAuthHeaders(apiKey); - const control = new WSStreamControl; - async function* stream2() { - let ws; - try { - ws = await connectWs(wsUrl, headers); - control._bind(ws); - ws.send(JSON.stringify({ - type: "reconnect", - command_id: commandId, - stdout_offset: stdoutOffset, - stderr_offset: stderrOffset - })); - for await (const msg of readWsMessages(ws)) { - const msgType = msg.type; - if (msgType === "stdout" || msgType === "stderr") { - yield msg; - } else if (msgType === "exit") { - yield msg; - return; - } else if (msgType === "error") { - raiseForWsError(msg, commandId); - } - } - } finally { - control._unbind(); - if (ws && ws.readyState === 1) { - ws.close(); - } - } + if (effects.asPartial) + modifiedSchema = interopZodObjectPartial(modifiedSchema); + cache2.set(schema, modifiedSchema); + this._extensionCache.set(cacheKey2, cache2); + return modifiedSchema; } - return [stream2(), control]; -} -var init_ws_execute = __esm(() => { - init_errors8(); +}, schemaMetaRegistry2; +var init_meta2 = __esm(() => { + init_binop2(); + init_last_value2(); + init_types3(); + schemaMetaRegistry2 = new SchemaMetaRegistry2; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/sandbox.js -class Sandbox { - constructor(data, client2) { - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "dataplane_url", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "status_message", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "created_at", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "updated_at", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "idle_ttl_seconds", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "delete_after_stop_seconds", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "stopped_at", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "snapshot_id", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "vCpus", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "mem_bytes", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "fs_capacity_bytes", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_client", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.name = data.name; - this.dataplane_url = data.dataplane_url; - this.status = data.status; - this.status_message = data.status_message; - this.id = data.id; - this.created_at = data.created_at; - this.updated_at = data.updated_at; - this.idle_ttl_seconds = data.idle_ttl_seconds; - this.delete_after_stop_seconds = data.delete_after_stop_seconds; - this.stopped_at = data.stopped_at ?? undefined; - this.snapshot_id = data.snapshot_id; - this.vCpus = data.vcpus; - this.mem_bytes = data.mem_bytes; - this.fs_capacity_bytes = data.fs_capacity_bytes; - this._client = client2; - } - requireDataplaneUrl() { - if (this.status && this.status !== "ready") { - throw new LangSmithSandboxNotReadyError(`Sandbox '${this.name}' is not ready (status: ${this.status}). ` + "Use waitForSandbox() to wait for the sandbox to become ready."); - } - if (!this.dataplane_url) { - throw new LangSmithDataplaneNotConfiguredError(`Sandbox '${this.name}' does not have a dataplane_url configured. ` + "Runtime operations require a dataplane URL."); - } - return this.dataplane_url; - } - async run(command, options = {}) { - const { wait = true, onStdout, onStderr, idleTimeout, killOnDisconnect, ttlSeconds, pty, ...restOptions } = options; - const hasCallbacks = onStdout !== undefined || onStderr !== undefined; - if (!wait || hasCallbacks) { - const handle = await this._runWs(command, { - ...restOptions, - idleTimeout, - killOnDisconnect, - ttlSeconds, - pty, - onStdout, - onStderr - }); - if (!wait) { - return handle; - } - return handle.result; - } - try { - const handle = await this._runWs(command, { - ...restOptions, - idleTimeout, - killOnDisconnect, - ttlSeconds, - pty - }); - return await handle.result; - } catch (e) { - const name = e != null && typeof e === "object" ? e.name : ""; - const message = e != null && typeof e === "object" ? e.message ?? "" : ""; - if (name === "LangSmithSandboxConnectionError" || name === "LangSmithSandboxServerReloadError" || message.includes("'ws' package")) { - return this._runHttp(command, restOptions); - } - throw e; - } - } - async _runWs(command, options = {}) { - const { timeout = 60, env, cwd, shell = "/bin/bash", onStdout, onStderr, idleTimeout, killOnDisconnect, ttlSeconds, pty } = options; - const dataplaneUrl = this.requireDataplaneUrl(); - const [stream2, control] = await runWsStream(dataplaneUrl, this._client.getApiKey(), command, { - timeout, - env, - cwd, - shell, - onStdout, - onStderr, - idleTimeout, - killOnDisconnect, - ttlSeconds, - pty - }); - const handle = new CommandHandle(stream2, control, this); - await handle._ensureStarted(); - return handle; +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/types.js +var init_types14 = __esm(() => { + init_constants5(); + init_base16(); + init_schema2(); + init_types3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/state.js +var PartialStateSchema2; +var init_state4 = __esm(() => { + init_constants5(); + init_errors9(); + init_last_value2(); + init_annotation3(); + init_utils14(); + init_write2(); + init_read2(); + init_subgraph2(); + init_ephemeral_value2(); + init_graph4(); + init_named_barrier_value2(); + init_schema2(); + init_state3(); + init_meta2(); + init_types14(); + init_runnables(); + init_types3(); + PartialStateSchema2 = Symbol.for("langgraph.state.partial"); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/message.js +var init_message3 = __esm(() => { + init_config3(); + init_messages_reducer2(); + init_state4(); + init_messages(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/func/index.js +var entrypoint3 = function entrypoint4(optionsOrName, func) { + const { name, checkpointer, store, cache: cache2 } = typeof optionsOrName === "string" ? { + name: optionsOrName, + checkpointer: undefined, + store: undefined + } : optionsOrName; + if (isAsyncGeneratorFunction2(func) || isGeneratorFunction2(func)) + throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); + const streamMode = "updates"; + const bound = getRunnableForEntrypoint2(name, func); + function isEntrypointFinal(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; } - async _runHttp(command, options = {}) { - const { timeout = 60, env, cwd, shell = "/bin/bash" } = options; - const dataplaneUrl = this.requireDataplaneUrl(); - const url2 = `${dataplaneUrl}/execute`; - const payload = { - command, - timeout, - shell - }; - if (env !== undefined) { - payload.env = env; - } - if (cwd !== undefined) { - payload.cwd = cwd; + const pluckReturnValue = new RunnableCallable3({ + name: "pluckReturnValue", + func: (value) => { + return isEntrypointFinal(value) ? value.value : value; } - const response = await this._client._fetch(url2, { - method: "POST", - headers: { - "Content-Type": "application/json" - }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout((timeout + 10) * 1000) - }); - if (!response.ok) { - await handleSandboxHttpError(response); + }); + const pluckSaveValue = new RunnableCallable3({ + name: "pluckSaveValue", + func: (value) => { + return isEntrypointFinal(value) ? value.save : value; } - const data = await response.json(); + }); + const entrypointNode = new PregelNode3({ + bound, + triggers: [START2], + channels: [START2], + writers: [new ChannelWrite3([{ + channel: END2, + value: PASSTHROUGH2, + mapper: pluckReturnValue + }, { + channel: PREVIOUS2, + value: PASSTHROUGH2, + mapper: pluckSaveValue + }], [TAG_HIDDEN2])] + }); + return new Pregel2({ + name, + checkpointer, + nodes: { [name]: entrypointNode }, + channels: { + [START2]: new EphemeralValue3, + [END2]: new LastValue3, + [PREVIOUS2]: new LastValue3 + }, + inputChannels: START2, + outputChannels: END2, + streamChannels: END2, + streamMode, + store, + cache: cache2 + }); +}; +var init_func2 = __esm(() => { + init_constants5(); + init_last_value2(); + init_utils14(); + init_write2(); + init_read2(); + init_call2(); + init_pregel2(); + init_ephemeral_value2(); + init_singletons(); + entrypoint3.final = function final2({ value, save }) { return { - stdout: data.stdout ?? "", - stderr: data.stderr ?? "", - exit_code: data.exit_code ?? -1 + value, + save, + __lg_type: "__pregel_final" }; - } - async reconnect(commandId, options = {}) { - const { stdoutOffset = 0, stderrOffset = 0 } = options; - const dataplaneUrl = this.requireDataplaneUrl(); - const [stream2, control] = await reconnectWsStream(dataplaneUrl, this._client.getApiKey(), commandId, { stdoutOffset, stderrOffset }); - return new CommandHandle(stream2, control, this, { - commandId, - stdoutOffset, - stderrOffset - }); - } - async write(path2, content, timeout = 60) { - const dataplaneUrl = this.requireDataplaneUrl(); - const url2 = `${dataplaneUrl}/upload?path=${encodeURIComponent(path2)}`; - const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content; - const formData = new FormData; - const buffer = new Uint8Array(bytes).buffer; - const blob = new Blob([buffer], { type: "application/octet-stream" }); - formData.append("file", blob, "file"); - const response = await this._client._fetch(url2, { - method: "POST", - body: formData, - signal: AbortSignal.timeout(timeout * 1000) - }); - if (!response.ok) { - await handleSandboxHttpError(response); - } - } - async read(path2, timeout = 60) { - const dataplaneUrl = this.requireDataplaneUrl(); - const url2 = `${dataplaneUrl}/download?path=${encodeURIComponent(path2)}`; - const response = await this._client._fetch(url2, { - method: "GET", - signal: AbortSignal.timeout(timeout * 1000) - }); - if (!response.ok) { - await handleSandboxHttpError(response); - } - const buffer = await response.arrayBuffer(); - return new Uint8Array(buffer); - } - async delete() { - await this._client.deleteSandbox(this.name); - } - async start(options = {}) { - const refreshed = await this._client.startSandbox(this.name, options); - this.status = refreshed.status; - this.dataplane_url = refreshed.dataplane_url; - } - async stop() { - await this._client.stopSandbox(this.name); - this.status = "stopped"; - this.dataplane_url = undefined; - } - async captureSnapshot(name, options = {}) { - return this._client.captureSnapshot(this.name, name, options); - } -} -var init_sandbox = __esm(() => { - init_errors8(); - init_helpers2(); - init_command_handle(); - init_ws_execute(); + }; }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/client.js -function sleepWithSignal(ms, signal) { - if (!signal) { - return new Promise((resolve2) => setTimeout(resolve2, ms)); - } - signal.throwIfAborted(); - return new Promise((resolve2, reject) => { - const timer = setTimeout(() => { - signal.removeEventListener("abort", onAbort); - resolve2(); - }, ms); - function onAbort() { - clearTimeout(timer); - reject(signal.reason); - } - signal.addEventListener("abort", onAbort, { once: true }); - }); -} -function getDefaultApiEndpoint() { - const base = getLangSmithEnvironmentVariable("ENDPOINT") ?? "https://api.smith.langchain.com"; - return `${base.replace(/\/$/, "")}/v2/sandboxes`; -} -function getDefaultApiKey() { - return getLangSmithEnvironmentVariable("API_KEY"); -} -var SandboxClient; -var init_client4 = __esm(() => { - init_env2(); - init_fetch(); - init_async_caller(); - init_sandbox(); - init_errors8(); - init_helpers2(); - SandboxClient = class SandboxClient { - constructor(config2 = {}) { - Object.defineProperty(this, "_baseUrl", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_fetchImpl", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "_caller", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this._baseUrl = (config2.apiEndpoint ?? getDefaultApiEndpoint()).replace(/\/$/, ""); - this._apiKey = config2.apiKey ?? getDefaultApiKey(); - this._fetchImpl = _getFetchImplementation(); - this._caller = new AsyncCaller({ - maxRetries: config2.maxRetries ?? 3, - maxConcurrency: config2.maxConcurrency ?? Infinity - }); - } - async _fetch(url2, init = {}) { - const headers = new Headers(init.headers); - if (this._apiKey) { - headers.set("X-Api-Key", this._apiKey); - } - return this._caller.call(() => this._fetchImpl(url2, { - ...init, - headers - })); - } - getApiKey() { - return this._apiKey; - } - async _postJson(url2, body, options) { - const response = await this._fetch(url2, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: options?.signal - }); - if (!response.ok) { - await handleClientHttpError(response); - } - return response; - } - async createSandbox(snapshotIdOrOptions, options = {}) { - const snapshotId = typeof snapshotIdOrOptions === "string" ? snapshotIdOrOptions : undefined; - const resolvedOptions = typeof snapshotIdOrOptions === "object" && snapshotIdOrOptions !== null ? snapshotIdOrOptions : options; - const { snapshotName, name, timeout = 30, waitForReady = true, idleTtlSeconds, deleteAfterStopSeconds, vCpus, memBytes, fsCapacityBytes, proxyConfig } = resolvedOptions; - if (snapshotId && snapshotName) { - throw new LangSmithValidationError("At most one of snapshotId or options.snapshotName may be set", "snapshotId"); - } - validateTtl(idleTtlSeconds, "idleTtlSeconds"); - validateTtl(deleteAfterStopSeconds, "deleteAfterStopSeconds"); - const url2 = `${this._baseUrl}/boxes`; - const payload = { - wait_for_ready: waitForReady - }; - if (snapshotId) { - payload.snapshot_id = snapshotId; - } - if (snapshotName) { - payload.snapshot_name = snapshotName; - } - if (waitForReady) { - payload.timeout = timeout; +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/util.js +var util3, objectUtil2, ZodParsedType2, getParsedType4 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType2.undefined; + case "string": + return ZodParsedType2.string; + case "number": + return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; + case "boolean": + return ZodParsedType2.boolean; + case "function": + return ZodParsedType2.function; + case "bigint": + return ZodParsedType2.bigint; + case "symbol": + return ZodParsedType2.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType2.array; } - if (name) { - payload.name = name; + if (data === null) { + return ZodParsedType2.null; } - if (idleTtlSeconds !== undefined) { - payload.idle_ttl_seconds = idleTtlSeconds; + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType2.promise; } - if (deleteAfterStopSeconds !== undefined) { - payload.delete_after_stop_seconds = deleteAfterStopSeconds; + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType2.map; } - if (vCpus !== undefined) { - payload.vcpus = vCpus; + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType2.set; } - if (memBytes !== undefined) { - payload.mem_bytes = memBytes; + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType2.date; } - if (fsCapacityBytes !== undefined) { - payload.fs_capacity_bytes = fsCapacityBytes; + return ZodParsedType2.object; + default: + return ZodParsedType2.unknown; + } +}; +var init_util4 = __esm(() => { + (function(util4) { + util4.assertEqual = (_) => {}; + function assertIs3(_arg) {} + util4.assertIs = assertIs3; + function assertNever3(_x) { + throw new Error; + } + util4.assertNever = assertNever3; + util4.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; } - if (proxyConfig !== undefined) { - payload.proxy_config = proxyConfig; + return obj; + }; + util4.getValidEnumValues = (obj) => { + const validKeys = util4.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; } - const httpTimeout = waitForReady ? (timeout + 30) * 1000 : 30 * 1000; - const response = await this._fetch(url2, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout(httpTimeout) + return util4.objectValues(filtered); + }; + util4.objectValues = (obj) => { + return util4.objectKeys(obj).map(function(e) { + return obj[e]; }); - if (!response.ok) { - await handleSandboxCreationError(response); - } - const data = await response.json(); - return new Sandbox(data, this); - } - async getSandbox(name, options) { - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; - const response = await this._fetch(url2, { signal: options?.signal }); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + }; + util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { + const keys = []; + for (const key in object3) { + if (Object.prototype.hasOwnProperty.call(object3, key)) { + keys.push(key); } - await handleClientHttpError(response); } - const data = await response.json(); - return new Sandbox(data, this); - } - async listSandboxes() { - const url2 = `${this._baseUrl}/boxes`; - const response = await this._fetch(url2); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithSandboxAPIError(`API endpoint not found: ${url2}. Check that apiEndpoint is correct.`); - } - await handleClientHttpError(response); + return keys; + }; + util4.find = (arr3, checker) => { + for (const item of arr3) { + if (checker(item)) + return item; } - const data = await response.json(); - return (data.sandboxes ?? []).map((s) => new Sandbox(s, this)); + return; + }; + util4.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues3(array3, separator = " | ") { + return array3.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } - async updateSandbox(name, newNameOrOptions) { - const options = typeof newNameOrOptions === "string" ? { newName: newNameOrOptions } : newNameOrOptions; - const { newName, idleTtlSeconds, deleteAfterStopSeconds } = options; - validateTtl(idleTtlSeconds, "idleTtlSeconds"); - validateTtl(deleteAfterStopSeconds, "deleteAfterStopSeconds"); - if (newName === undefined && idleTtlSeconds === undefined && deleteAfterStopSeconds === undefined) { - return this.getSandbox(name); - } - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; - const payload = {}; - if (newName !== undefined) { - payload.name = newName; - } - if (idleTtlSeconds !== undefined) { - payload.idle_ttl_seconds = idleTtlSeconds; - } - if (deleteAfterStopSeconds !== undefined) { - payload.delete_after_stop_seconds = deleteAfterStopSeconds; - } - const response = await this._fetch(url2, { - method: "PATCH", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload) - }); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); - } - if (response.status === 409) { - throw new LangSmithResourceNameConflictError(newName !== undefined ? `Sandbox name '${newName}' already in use` : "Sandbox update conflict (name may already be in use)", "sandbox"); - } - await handleClientHttpError(response); + util4.joinValues = joinValues3; + util4.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); } - const data = await response.json(); - return new Sandbox(data, this); + return value; + }; + })(util3 || (util3 = {})); + (function(objectUtil3) { + objectUtil3.mergeShapes = (first, second) => { + return { + ...first, + ...second + }; + }; + })(objectUtil2 || (objectUtil2 = {})); + ZodParsedType2 = util3.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/ZodError.js +var ZodIssueCode4, quotelessJson2 = (obj) => { + const json3 = JSON.stringify(obj, null, 2); + return json3.replace(/"([^"]+)":/g, "$1:"); +}, ZodError5; +var init_ZodError2 = __esm(() => { + init_util4(); + ZodIssueCode4 = util3.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + ZodError5 = class ZodError5 extends Error { + get errors() { + return this.issues; } - async deleteSandbox(name) { - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; - const response = await this._fetch(url2, { method: "DELETE" }); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); - } - await handleClientHttpError(response); + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; } + this.name = "ZodError"; + this.issues = issues; } - async getSandboxStatus(name, options) { - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/status`; - const response = await this._fetch(url2, { signal: options?.signal }); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + format(_mapper) { + const mapper = _mapper || function(issue3) { + return issue3.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error90) => { + for (const issue3 of error90.issues) { + if (issue3.code === "invalid_union") { + issue3.unionErrors.map(processError); + } else if (issue3.code === "invalid_return_type") { + processError(issue3.returnTypeError); + } else if (issue3.code === "invalid_arguments") { + processError(issue3.argumentsError); + } else if (issue3.path.length === 0) { + fieldErrors._errors.push(mapper(issue3)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue3.path.length) { + const el = issue3.path[i]; + const terminal = i === issue3.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue3)); + } + curr = curr[el]; + i++; + } + } } - await handleClientHttpError(response); - } - return await response.json(); + }; + processError(this); + return fieldErrors; } - async waitForSandbox(name, options = {}) { - const { timeout = 120, pollInterval = 1, signal } = options; - const deadline = Date.now() + timeout * 1000; - let lastStatus = "provisioning"; - while (Date.now() < deadline) { - signal?.throwIfAborted(); - const statusResult = await this.getSandboxStatus(name, { signal }); - lastStatus = statusResult.status; - if (statusResult.status === "ready") { - return this.getSandbox(name, { signal }); - } - if (statusResult.status === "failed") { - throw new LangSmithResourceCreationError(statusResult.status_message ?? `Sandbox '${name}' creation failed`, "sandbox"); - } - const remaining = deadline - Date.now(); - const jitter = pollInterval * 200 * (Math.random() - 0.5); - const delay = Math.min(pollInterval * 1000 + jitter, remaining); - if (delay > 0) { - await sleepWithSignal(delay, signal); - } + static assert(value) { + if (!(value instanceof ZodError5)) { + throw new Error(`Not a ZodError: ${value}`); } - throw new LangSmithResourceTimeoutError(`Sandbox '${name}' did not become ready within ${timeout}s`, "sandbox", lastStatus); } - async startSandbox(name, options = {}) { - const { timeout = 120, signal } = options; - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/start`; - await this._postJson(url2, {}, { signal }); - return this.waitForSandbox(name, { timeout, signal }); + toString() { + return this.message; } - async stopSandbox(name) { - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/stop`; - await this._postJson(url2, {}); + get message() { + return JSON.stringify(this.issues, util3.jsonStringifyReplacer, 2); } - async createSnapshot(name, dockerImage, fsCapacityBytes, options = {}) { - const { registryId, registryUrl, registryUsername, registryPassword, timeout = 60, signal } = options; - const url2 = `${this._baseUrl}/snapshots`; - const payload = { - name, - docker_image: dockerImage, - fs_capacity_bytes: fsCapacityBytes - }; - if (registryId !== undefined) { - payload.registry_id = registryId; - } - if (registryUrl !== undefined) { - payload.registry_url = registryUrl; - } - if (registryUsername !== undefined) { - payload.registry_username = registryUsername; - } - if (registryPassword !== undefined) { - payload.registry_password = registryPassword; - } - const response = await this._postJson(url2, payload, { signal }); - const snapshot = await response.json(); - return this.waitForSnapshot(snapshot.id, { timeout, signal }); + get isEmpty() { + return this.issues.length === 0; } - async captureSnapshot(sandboxName, name, options = {}) { - const { timeout = 60, signal } = options; - const url2 = `${this._baseUrl}/boxes/${encodeURIComponent(sandboxName)}/snapshot`; - const payload = { name }; - const response = await this._postJson(url2, payload, { signal }); - const snapshot = await response.json(); - return this.waitForSnapshot(snapshot.id, { timeout, signal }); - } - async getSnapshot(snapshotId, options) { - const url2 = `${this._baseUrl}/snapshots/${encodeURIComponent(snapshotId)}`; - const response = await this._fetch(url2, { signal: options?.signal }); - if (!response.ok) { - if (response.status === 404) { - throw new LangSmithResourceNotFoundError(`Snapshot '${snapshotId}' not found`, "snapshot"); + flatten(mapper = (issue3) => issue3.message) { + const fieldErrors = Object.create(null); + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); } - await handleClientHttpError(response); } - return await response.json(); + return { formErrors, fieldErrors }; } - async listSnapshots(options = {}) { - const { nameContains, limit, offset, signal } = options; - const params = new URLSearchParams; - if (nameContains !== undefined) { - params.set("name_contains", nameContains); - } - if (limit !== undefined) { - params.set("limit", String(limit)); - } - if (offset !== undefined) { - params.set("offset", String(offset)); - } - const query3 = params.toString(); - const url2 = query3 ? `${this._baseUrl}/snapshots?${query3}` : `${this._baseUrl}/snapshots`; - const response = await this._fetch(url2, { signal }); - if (!response.ok) { - await handleClientHttpError(response); - } - const data = await response.json(); - return data.snapshots ?? []; + get formErrors() { + return this.flatten(); } - async deleteSnapshot(snapshotId) { - const url2 = `${this._baseUrl}/snapshots/${encodeURIComponent(snapshotId)}`; - const response = await this._fetch(url2, { method: "DELETE" }); - if (!response.ok) { - await handleClientHttpError(response); + }; + ZodError5.create = (issues) => { + const error90 = new ZodError5(issues); + return error90; + }; +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/locales/en.js +var errorMap2 = (issue3, _ctx) => { + let message; + switch (issue3.code) { + case ZodIssueCode4.invalid_type: + if (issue3.received === ZodParsedType2.undefined) { + message = "Required"; + } else { + message = `Expected ${issue3.expected}, received ${issue3.received}`; } - } - async waitForSnapshot(snapshotId, options = {}) { - const { timeout = 300, pollInterval = 2, signal } = options; - const deadline = Date.now() + timeout * 1000; - let lastStatus = "building"; - while (Date.now() < deadline) { - signal?.throwIfAborted(); - const snapshot = await this.getSnapshot(snapshotId, { signal }); - lastStatus = snapshot.status; - if (snapshot.status === "ready") { - return snapshot; - } - if (snapshot.status === "failed") { - throw new LangSmithResourceCreationError(snapshot.status_message ?? `Snapshot '${snapshotId}' build failed`, "snapshot"); - } - const remaining = deadline - Date.now(); - const jitter = pollInterval * 200 * (Math.random() - 0.5); - const delay = Math.min(pollInterval * 1000 + jitter, remaining); - if (delay > 0) { - await sleepWithSignal(delay, signal); + break; + case ZodIssueCode4.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue3.expected, util3.jsonStringifyReplacer)}`; + break; + case ZodIssueCode4.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util3.joinValues(issue3.keys, ", ")}`; + break; + case ZodIssueCode4.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode4.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util3.joinValues(issue3.options)}`; + break; + case ZodIssueCode4.invalid_enum_value: + message = `Invalid enum value. Expected ${util3.joinValues(issue3.options)}, received '${issue3.received}'`; + break; + case ZodIssueCode4.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode4.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode4.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode4.invalid_string: + if (typeof issue3.validation === "object") { + if ("includes" in issue3.validation) { + message = `Invalid input: must include "${issue3.validation.includes}"`; + if (typeof issue3.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue3.validation.position}`; + } + } else if ("startsWith" in issue3.validation) { + message = `Invalid input: must start with "${issue3.validation.startsWith}"`; + } else if ("endsWith" in issue3.validation) { + message = `Invalid input: must end with "${issue3.validation.endsWith}"`; + } else { + util3.assertNever(issue3.validation); } + } else if (issue3.validation !== "regex") { + message = `Invalid ${issue3.validation}`; + } else { + message = "Invalid"; } - throw new LangSmithResourceTimeoutError(`Snapshot '${snapshotId}' did not become ready within ${timeout}s`, "snapshot", lastStatus); + break; + case ZodIssueCode4.too_small: + if (issue3.type === "array") + message = `Array must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `more than`} ${issue3.minimum} element(s)`; + else if (issue3.type === "string") + message = `String must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `over`} ${issue3.minimum} character(s)`; + else if (issue3.type === "number") + message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; + else if (issue3.type === "bigint") + message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; + else if (issue3.type === "date") + message = `Date must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue3.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode4.too_big: + if (issue3.type === "array") + message = `Array must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `less than`} ${issue3.maximum} element(s)`; + else if (issue3.type === "string") + message = `String must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `under`} ${issue3.maximum} character(s)`; + else if (issue3.type === "number") + message = `Number must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; + else if (issue3.type === "bigint") + message = `BigInt must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; + else if (issue3.type === "date") + message = `Date must be ${issue3.exact ? `exactly` : issue3.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue3.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode4.custom: + message = `Invalid input`; + break; + case ZodIssueCode4.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode4.not_multiple_of: + message = `Number must be a multiple of ${issue3.multipleOf}`; + break; + case ZodIssueCode4.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util3.assertNever(issue3); + } + return { message }; +}, en_default4; +var init_en4 = __esm(() => { + init_ZodError2(); + init_util4(); + en_default4 = errorMap2; +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/errors.js +function setErrorMap4(map3) { + overrideErrorMap2 = map3; +} +function getErrorMap4() { + return overrideErrorMap2; +} +var overrideErrorMap2; +var init_errors10 = __esm(() => { + init_en4(); + overrideErrorMap2 = en_default4; +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/parseUtil.js +function addIssueToContext2(ctx, issueData) { + const overrideMap = getErrorMap4(); + const issue3 = makeIssue2({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + ctx.schemaErrorMap, + overrideMap, + overrideMap === en_default4 ? undefined : en_default4 + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue3); +} + +class ParseStatus2 { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID2; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); } - toString() { - return `[LangSmithSandboxClient apiEndpoint=${JSON.stringify(this._baseUrl)}]`; + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); } - [Symbol.for("nodejs.util.inspect.custom")]() { - return this.toString(); + return ParseStatus2.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID2; + if (value.status === "aborted") + return INVALID2; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } } + return { status: status.value, value: finalObject }; + } +} +var makeIssue2 = (params) => { + const { data, path: path2, errorMaps, issueData } = params; + const fullPath = [...path2, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map3 of maps) { + errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage }; +}, EMPTY_PATH2, INVALID2, DIRTY2 = (value) => ({ status: "dirty", value }), OK2 = (value) => ({ status: "valid", value }), isAborted2 = (x) => x.status === "aborted", isDirty2 = (x) => x.status === "dirty", isValid2 = (x) => x.status === "valid", isAsync2 = (x) => typeof Promise !== "undefined" && x instanceof Promise; +var init_parseUtil2 = __esm(() => { + init_errors10(); + init_en4(); + EMPTY_PATH2 = []; + INVALID2 = Object.freeze({ + status: "aborted" + }); }); -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/dist/sandbox/index.js -var init_sandbox2 = __esm(() => { - init_client4(); - init_sandbox(); - init_command_handle(); - init_errors8(); -}); +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/typeAliases.js +var init_typeAliases2 = () => {}; -// ../../node_modules/.pnpm/langsmith@0.7.1_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_m3ohgakthr7h2pj5l52zrj5cju/node_modules/langsmith/experimental/sandbox.js -var init_sandbox3 = __esm(() => { - init_sandbox2(); +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil2; +var init_errorUtil2 = __esm(() => { + (function(errorUtil3) { + errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil2 || (errorUtil2 = {})); }); -// ../../node_modules/.pnpm/deepagents@1.10.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetr_hwobpohhuc5zvzhsegiv5gurvm/node_modules/deepagents/dist/index.js -var exports_dist2 = {}; -__export(exports_dist2, { - serializeProfile: () => serializeProfile, - resolveBackend: () => resolveBackend, - registerHarnessProfile: () => registerHarnessProfile, - parseSkillMetadata: () => parseSkillMetadata, - parseHarnessProfileConfig: () => parseHarnessProfileConfig, - listSkills: () => listSkills, - isSandboxProtocol: () => isSandboxProtocol, - isSandboxBackend: () => isSandboxBackend, - isAsyncSubAgent: () => isAsyncSubAgent, - harnessProfileConfigSchema: () => harnessProfileConfigSchema, - getHarnessProfile: () => getHarnessProfile, - generalPurposeSubagentConfigSchema: () => generalPurposeSubagentConfigSchema, - findProjectRoot: () => findProjectRoot, - filesValue: () => filesValue, - createSummarizationMiddleware: () => createSummarizationMiddleware, - createSubagentTransformer: () => createSubagentTransformer, - createSubAgentMiddleware: () => createSubAgentMiddleware, - createSkillsMiddleware: () => createSkillsMiddleware, - createSettings: () => createSettings, - createPatchToolCallsMiddleware: () => createPatchToolCallsMiddleware, - createMemoryMiddleware: () => createMemoryMiddleware, - createHarnessProfile: () => createHarnessProfile, - createFilesystemMiddleware: () => createFilesystemMiddleware, - createDeepAgent: () => createDeepAgent, - createCompletionCallbackMiddleware: () => createCompletionCallbackMiddleware, - createAsyncSubAgentMiddleware: () => createAsyncSubAgentMiddleware, - createAgentMemoryMiddleware: () => createAgentMemoryMiddleware, - computeSummarizationDefaults: () => computeSummarizationDefaults, - adaptSandboxProtocol: () => adaptSandboxProtocol, - adaptBackendProtocol: () => adaptBackendProtocol, - TASK_SYSTEM_PROMPT: () => TASK_SYSTEM_PROMPT, - StoreBackend: () => StoreBackend, - StateBackend: () => StateBackend, - SandboxError: () => SandboxError, - REQUIRED_MIDDLEWARE_NAMES: () => REQUIRED_MIDDLEWARE_NAMES, - MAX_SKILL_NAME_LENGTH: () => MAX_SKILL_NAME_LENGTH, - MAX_SKILL_FILE_SIZE: () => MAX_SKILL_FILE_SIZE, - MAX_SKILL_DESCRIPTION_LENGTH: () => MAX_SKILL_DESCRIPTION_LENGTH, - LocalShellBackend: () => LocalShellBackend, - LangSmithSandbox: () => LangSmithSandbox, - GENERAL_PURPOSE_SUBAGENT: () => GENERAL_PURPOSE_SUBAGENT, - FilesystemBackend: () => FilesystemBackend, - EMPTY_HARNESS_PROFILE: () => EMPTY_HARNESS_PROFILE, - DEFAULT_SUBAGENT_PROMPT: () => DEFAULT_SUBAGENT_PROMPT, - DEFAULT_GENERAL_PURPOSE_DESCRIPTION: () => DEFAULT_GENERAL_PURPOSE_DESCRIPTION, - ContextHubBackend: () => ContextHubBackend, - ConfigurationError: () => ConfigurationError, - CompositeBackend: () => CompositeBackend, - BaseSandbox: () => BaseSandbox -}); -import path2, { basename } from "path"; -import fs from "node:fs/promises"; -import fs$1 from "node:fs"; -import path$1 from "node:path"; -import cp, { spawn } from "node:child_process"; -import os from "node:os"; -function sanitizeToolCallId(toolCallId) { - return toolCallId.replace(/\./g, "_").replace(/\//g, "_").replace(/\\/g, "_"); -} -function formatContentWithLineNumbers(content, startLine = 1) { - let lines; - if (typeof content === "string") { - lines = content.split(` -`); - if (lines.length > 0 && lines[lines.length - 1] === "") - lines = lines.slice(0, -1); - } else - lines = content; - const resultLines = []; - for (let i = 0;i < lines.length; i++) { - const line = lines[i]; - const lineNum = i + startLine; - if (line.length <= 5000) - resultLines.push(`${lineNum.toString().padStart(6)} ${line}`); - else { - const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH); - for (let chunkIdx = 0;chunkIdx < numChunks; chunkIdx++) { - const start = chunkIdx * MAX_LINE_LENGTH; - const end = Math.min(start + MAX_LINE_LENGTH, line.length); - const chunk = line.substring(start, end); - if (chunkIdx === 0) - resultLines.push(`${lineNum.toString().padStart(6)} ${chunk}`); - else { - const continuationMarker = `${lineNum}.${chunkIdx}`; - resultLines.push(`${continuationMarker.padStart(6)} ${chunk}`); - } +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/types.js +class ParseInputLazyPath2 { + constructor(parent, value, path2, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path2; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); } } + return this._cachedPath; } - return resultLines.join(` -`); -} -function checkEmptyContent(content) { - if (!content || content.trim() === "") - return EMPTY_CONTENT_WARNING; - return null; -} -function fileDataToString(fileData) { - if (Array.isArray(fileData.content)) - return fileData.content.join(` -`); - if (typeof fileData.content === "string") - return fileData.content; - throw new Error("Cannot convert binary FileData to string"); -} -function isFileDataBinary(data) { - return ArrayBuffer.isView(data.content); } -function createFileData(content, createdAt, fileFormat = "v2", mimeType) { - const now = (/* @__PURE__ */ new Date()).toISOString(); - if (fileFormat === "v1" && ArrayBuffer.isView(content)) - throw new Error("Binary data is not supported with v1 file formats. Please use v2 file format"); - if (fileFormat === "v2") { - if (ArrayBuffer.isView(content)) - return { - content: new Uint8Array(content.buffer, content.byteOffset, content.byteLength), - mimeType: mimeType ?? "application/octet-stream", - created_at: createdAt || now, - modified_at: now - }; - return { - content, - mimeType: mimeType ?? "text/plain", - created_at: createdAt || now, - modified_at: now - }; +function processCreateParams2(params) { + if (!params) + return {}; + const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; + if (errorMap3 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - return { - content: typeof content === "string" ? content.split(` -`) : content, - created_at: createdAt || now, - modified_at: now + if (errorMap3) + return { errorMap: errorMap3, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; + return { errorMap: customMap, description }; } -function updateFileData(fileData, content) { - const now = (/* @__PURE__ */ new Date()).toISOString(); - if (isFileDataV1(fileData)) + +class ZodType4 { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType4(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType4(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { return { - content: typeof content === "string" ? content.split(` -`) : content, - created_at: fileData.created_at, - modified_at: now + status: new ParseStatus2, + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType4(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } }; - return { - content, - mimeType: fileData.mimeType, - created_at: fileData.created_at, - modified_at: now - }; -} -function performStringReplacement(content, oldString, newString, replaceAll) { - if (content === "" && oldString === "") - return [newString, 0]; - if (oldString === "") - return "Error: oldString cannot be empty when file has content"; - const occurrences = content.split(oldString).length - 1; - if (occurrences === 0) - return `Error: String not found in file: '${oldString}'`; - if (occurrences > 1 && !replaceAll) - return `Error: String '${oldString}' has multiple occurrences (appears ${occurrences} times) in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`; - return [content.split(oldString).join(newString), occurrences]; -} -function truncateIfTooLong(result) { - if (Array.isArray(result)) { - const totalChars = result.reduce((sum, item) => sum + item.length, 0); - if (totalChars > 20000 * 4) { - const truncateAt = Math.floor(result.length * TOOL_RESULT_TOKEN_LIMIT * 4 / totalChars); - return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE]; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync2(result)) { + throw new Error("Synchronous parse encountered promise."); } return result; } - if (result.length > 20000 * 4) - return result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) + ` -... [results truncated, try being more specific with your parameters]`; - return result; -} -function validatePath$1(path3) { - const pathStr = path3 || "/"; - if (!pathStr || pathStr.trim() === "") - throw new Error("Path cannot be empty"); - let normalized = pathStr.startsWith("/") ? pathStr : "/" + pathStr; - if (!normalized.endsWith("/")) - normalized += "/"; - return normalized; -} -function globSearchFiles(files, pattern, path3 = "/") { - let normalizedPath; - try { - normalizedPath = validatePath$1(path3); - } catch { - return "No files found"; + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); } - const filtered = Object.fromEntries(Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath))); - const effectivePattern = pattern; - const matches = []; - for (const [filePath, fileData] of Object.entries(filtered)) { - let relative2 = filePath.substring(normalizedPath.length); - if (relative2.startsWith("/")) - relative2 = relative2.substring(1); - if (!relative2) { - const parts = filePath.split("/"); - relative2 = parts[parts.length - 1] || ""; - } - if (import_micromatch.default.isMatch(relative2, effectivePattern, { - dot: true, - nobrace: false - })) - matches.push([filePath, fileData.modified_at]); + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; } - matches.sort((a, b) => b[1].localeCompare(a[1])); - if (matches.length === 0) - return "No files found"; - return matches.map(([fp]) => fp).join(` -`); -} -function grepMatchesFromFiles(files, pattern, path3 = null, glob = null) { - let normalizedPath; - try { - normalizedPath = validatePath$1(path3); - } catch { - return []; + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType4(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult2(ctx, result); } - let filtered = Object.fromEntries(Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath))); - if (glob) - filtered = Object.fromEntries(Object.entries(filtered).filter(([fp]) => import_micromatch.default.isMatch(basename(fp), glob, { - dot: true, - nobrace: false - }))); - const matches = []; - for (const [filePath, fileData] of Object.entries(filtered)) { - if (!isTextMimeType(migrateToFileDataV2(fileData, filePath).mimeType)) - continue; - const lines = fileDataToString(fileData).split(` -`); - for (let i = 0;i < lines.length; i++) { - const line = lines[i]; - const lineNum = i + 1; - if (line.includes(pattern)) - matches.push({ - path: filePath, - line: lineNum, - text: line - }); + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType4(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid2(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); } - return matches; -} -function getMimeType(filePath) { - return MIME_TYPES[path2.extname(filePath).toLocaleLowerCase()] || "text/plain"; -} -function isTextMimeType(mimeType) { - return mimeType.startsWith("text/") || mimeType === "application/json" || mimeType === "application/javascript" || mimeType === "image/svg+xml"; -} -function isFileDataV1(data) { - return Array.isArray(data.content); -} -function migrateToFileDataV2(data, filePath) { - if (isFileDataV1(data)) - return { - content: data.content.join(` -`), - mimeType: getMimeType(filePath), - created_at: data.created_at, - modified_at: data.modified_at + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType4(data) }; - if (!("mimeType" in data) || !data.mimeType) - return { - ...data, - mimeType: getMimeType(filePath) + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult2(ctx, result); + } + refine(check3, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } }; - return data; -} -function adaptBackendProtocol(backend) { - return { - async ls(path3) { - const result = await ("ls" in backend ? backend.ls(path3) : backend.lsInfo(path3)); - if (Array.isArray(result)) - return { files: result }; - return result; - }, - async readRaw(filePath) { - const result = await backend.readRaw(filePath); - if ("data" in result || "error" in result) - return result; - return { data: migrateToFileDataV2(result, filePath) }; - }, - async glob(pattern, path3) { - const result = await ("glob" in backend ? backend.glob(pattern, path3) : backend.globInfo(pattern, path3)); - if (Array.isArray(result)) - return { files: result }; - return result; - }, - write: (filePath, content) => backend.write(filePath, content), - edit: (filePath, oldString, newString, replaceAll) => backend.edit(filePath, oldString, newString, replaceAll), - uploadFiles: backend.uploadFiles ? (files) => backend.uploadFiles(files) : undefined, - downloadFiles: backend.downloadFiles ? (paths) => backend.downloadFiles(paths) : undefined, - async read(filePath, offset, limit) { - const result = await backend.read(filePath, offset, limit); - if (typeof result === "string") - return { content: result }; - return result; - }, - async grep(pattern, path3, glob) { - const result = await ("grep" in backend ? backend.grep(pattern, path3, glob) : backend.grepRaw(pattern, path3, glob)); - if (Array.isArray(result)) - return { matches: result }; - if (typeof result === "string") - return { error: result }; - return result; - } - }; -} -function adaptSandboxProtocol(sandbox2) { - const adapted = adaptBackendProtocol(sandbox2); - adapted.execute = (cmd) => sandbox2.execute(cmd); - Object.defineProperty(adapted, "id", { - value: sandbox2.id, - enumerable: true, - configurable: true - }); - return adapted; -} -function isSandboxBackend(backend) { - return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; -} -function isSandboxProtocol(backend) { - return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; -} -async function resolveBackend(backend, runtime) { - if (typeof backend === "function") { - const resolved = await backend(runtime); - return isSandboxProtocol(resolved) ? adaptSandboxProtocol(resolved) : adaptBackendProtocol(resolved); + return this._refinement((val, ctx) => { + const result = check3(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode4.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check3, refinementData) { + return this._refinement((val, ctx) => { + if (!check3(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects2({ + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional4.create(this, this._def); + } + nullable() { + return ZodNullable4.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray4.create(this); + } + promise() { + return ZodPromise4.create(this, this._def); + } + or(option) { + return ZodUnion4.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection4.create(this, incoming, this._def); + } + transform(transform3) { + return new ZodEffects2({ + ...processCreateParams2(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "transform", transform: transform3 } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault4({ + ...processCreateParams2(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodDefault + }); + } + brand() { + return new ZodBranded2({ + typeName: ZodFirstPartyTypeKind3.ZodBranded, + type: this, + ...processCreateParams2(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch4({ + ...processCreateParams2(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline2.create(this, target); + } + readonly() { + return ZodReadonly4.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; } - return isSandboxProtocol(backend) ? adaptSandboxProtocol(backend) : adaptBackendProtocol(backend); } -function validatePermissionPaths(permissions) { - for (const permission of permissions) - for (const path3 of permission.paths) - validatePath(path3); +function timeRegexSource2(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } -function validatePath(raw2) { - if (typeof raw2 !== "string" || raw2.length === 0) - throw new Error("path must be a non-empty string"); - if (!raw2.startsWith("/")) - throw new Error(`path must be absolute: ${JSON.stringify(raw2)}`); - const segments = raw2.split("/").filter((s) => s.length > 0); - if (segments.includes("..")) - throw new Error(`path must not contain "..": ${JSON.stringify(raw2)}`); - if (segments.includes("~")) - throw new Error(`path must not contain "~": ${JSON.stringify(raw2)}`); - return `/${segments.join("/")}`; +function timeRegex2(args) { + return new RegExp(`^${timeRegexSource2(args)}$`); } -function globMatch(path3, pattern) { - return import_micromatch.default.isMatch(path3, pattern, { dot: true }); +function datetimeRegex2(args) { + let regex2 = `${dateRegexSource2}T${timeRegexSource2(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex2 = `${regex2}(${opts.join("|")})`; + return new RegExp(`^${regex2}$`); } -function decidePathAccess(rules, operation, path3) { - for (const rule of rules) { - if (!rule.operations.includes(operation)) - continue; - if (rule.paths.some((pattern) => globMatch(path3, pattern))) - return rule.mode ?? "allow"; +function isValidIP2(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4Regex2.test(ip)) { + return true; } - return "allow"; + if ((version6 === "v6" || !version6) && ipv6Regex2.test(ip)) { + return true; + } + return false; } -function extractTextFromMessage(message) { - if (typeof message.content === "string") - return message.content; - if (Array.isArray(message.content)) - return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(` -`); - return String(message.content); +function isValidJWT4(jwt3, alg) { + if (!jwtRegex2.test(jwt3)) + return false; + try { + const [header] = jwt3.split("."); + if (!header) + return false; + const base646 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base646)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } } -function buildEvictedHumanContent(message, replacementText) { - if (typeof message.content === "string") - return replacementText; - if (Array.isArray(message.content)) { - const mediaBlocks = message.content.filter((block) => typeof block === "object" && block !== null && block.type !== "text"); - if (mediaBlocks.length === 0) - return replacementText; - return [{ - type: "text", - text: replacementText - }, ...mediaBlocks]; +function isValidCidr2(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4CidrRegex2.test(ip)) { + return true; } - return replacementText; + if ((version6 === "v6" || !version6) && ipv6CidrRegex2.test(ip)) { + return true; + } + return false; } -function buildTruncatedHumanMessage(message, filePath) { - const contentSample = createContentPreview(extractTextFromMessage(message)); - return new HumanMessage({ - content: buildEvictedHumanContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample)), - id: message.id, - additional_kwargs: { ...message.additional_kwargs }, - response_metadata: { ...message.response_metadata } - }); -} -function createContentPreview(contentStr, headLines = 5, tailLines = 5) { - const lines = contentStr.split(` -`); - if (lines.length <= headLines + tailLines) - return formatContentWithLineNumbers(lines.map((line) => line.substring(0, 1000)), 1); - const head = lines.slice(0, headLines).map((line) => line.substring(0, 1000)); - const tail = lines.slice(-tailLines).map((line) => line.substring(0, 1000)); - const headSample = formatContentWithLineNumbers(head, 1); - const truncationNotice = ` -... [${lines.length - headLines - tailLines} lines truncated] ... -`; - const tailSample = formatContentWithLineNumbers(tail, lines.length - tailLines + 1); - return headSample + truncationNotice + tailSample; -} -function fileDataReducer(current, update) { - if (update === undefined) - return current || {}; - if (current === undefined) { - const result2 = {}; - for (const [key, value] of Object.entries(update)) - if (value !== null) - result2[key] = value; - return result2; - } - const result = { ...current }; - for (const [key, value] of Object.entries(update)) - if (value === null) - delete result[key]; - else - result[key] = value; - return result; -} -function enforcePermission(rules, operation, path3) { - if (rules.length === 0) - return; - const canonical = validatePath(path3); - if (decidePathAccess(rules, operation, canonical) === "deny") - throw new Error(`Error: permission denied for ${operation} on ${canonical}`); +function floatSafeRemainder4(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; } -function filterByPermissions(entries, rules, operation, getPath2) { - if (rules.length === 0) - return entries; - return entries.filter((entry) => { - try { - return decidePathAccess(rules, operation, validatePath(getPath2(entry))) !== "deny"; - } catch { - return true; +function deepPartialify2(schema) { + if (schema instanceof ZodObject4) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional4.create(deepPartialify2(fieldSchema)); } - }); -} -function createLsTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "read", input.path ?? "/"); - const resolvedBackend = await resolveBackend(backend, runtime); - const path3 = input.path || "/"; - const lsResult = await resolvedBackend.ls(path3); - if (lsResult.error) - return `Error listing files: ${lsResult.error}`; - const infos = filterByPermissions(lsResult.files ?? [], permissions, "read", (info) => info.path); - if (infos.length === 0) - return `No files found in ${path3}`; - const lines = []; - for (const info of infos) - if (info.is_dir) - lines.push(`${info.path} (directory)`); - else { - const size = info.size ? ` (${info.size} bytes)` : ""; - lines.push(`${info.path}${size}`); - } - const result = truncateIfTooLong(lines); - if (Array.isArray(result)) - return result.join(` -`); - return result; - }, { - name: "ls", - description: customDescription || LS_TOOL_DESCRIPTION, - schema: exports_external.object({ path: exports_external.string().optional().default("/").describe("Directory path to list (default: /)") }) - }); + return new ZodObject4({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray4) { + return new ZodArray4({ + ...schema._def, + type: deepPartialify2(schema.element) + }); + } else if (schema instanceof ZodOptional4) { + return ZodOptional4.create(deepPartialify2(schema.unwrap())); + } else if (schema instanceof ZodNullable4) { + return ZodNullable4.create(deepPartialify2(schema.unwrap())); + } else if (schema instanceof ZodTuple4) { + return ZodTuple4.create(schema.items.map((item) => deepPartialify2(item))); + } else { + return schema; + } } -function createReadFileTool(backend, options) { - const { customDescription, toolTokenLimitBeforeEvict, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "read", input.file_path); - const resolvedBackend = await resolveBackend(backend, runtime); - const { file_path, offset = 0, limit = 100 } = input; - const readResult = await resolvedBackend.read(file_path, offset, limit); - if (readResult.error) - return [{ - type: "text", - text: `Error: ${readResult.error}` - }]; - const mimeType = readResult.mimeType ?? getMimeType(file_path); - if (!isTextMimeType(mimeType)) { - const binaryContent = readResult.content; - if (!binaryContent) - return [{ - type: "text", - text: `Error: expected binary content for '${file_path}'` - }]; - let base64Data; - if (typeof binaryContent === "string") - base64Data = binaryContent; - else if (ArrayBuffer.isView(binaryContent)) - base64Data = Buffer.from(binaryContent).toString("base64"); - else { - const values = Object.values(binaryContent); - base64Data = Buffer.from(new Uint8Array(values)).toString("base64"); +function mergeValues4(a, b) { + const aType = getParsedType4(a); + const bType = getParsedType4(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { + const bKeys = util3.objectKeys(b); + const sharedKeys = util3.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues4(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; } - const sizeBytes = Math.ceil(base64Data.length * 3 / 4); - if (sizeBytes > 10485760) - return [{ - type: "text", - text: `Error: file too large to read (${Math.round(sizeBytes / (1024 * 1024))}MB exceeds ${MAX_BINARY_READ_SIZE_BYTES / (1024 * 1024)}MB limit for binary files)` - }]; - if (mimeType.startsWith("image/")) - return [{ - type: "image", - mimeType, - data: base64Data - }]; - if (mimeType.startsWith("audio/")) - return [{ - type: "audio", - mimeType, - data: base64Data - }]; - if (mimeType.startsWith("video/")) - return [{ - type: "video", - mimeType, - data: base64Data - }]; - return [{ - type: "file", - mimeType, - data: base64Data - }]; + newObj[key] = sharedValue.data; } - let content = typeof readResult.content === "string" ? readResult.content : ""; - const lines = content.split(` -`); - if (lines.length > limit) - content = lines.slice(0, limit).join(` -`); - let formatted = formatContentWithLineNumbers(content, offset + 1); - if (toolTokenLimitBeforeEvict && formatted.length >= 4 * toolTokenLimitBeforeEvict) { - const truncationMsg = READ_FILE_TRUNCATION_MSG.replace("{file_path}", file_path); - const maxContentLength = 4 * toolTokenLimitBeforeEvict - truncationMsg.length; - formatted = formatted.substring(0, maxContentLength) + truncationMsg; + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { + if (a.length !== b.length) { + return { valid: false }; } - return [{ - type: "text", - text: formatted - }]; - }, { - name: "read_file", - description: customDescription || READ_FILE_TOOL_DESCRIPTION, - schema: exports_external.object({ - file_path: exports_external.string().describe("Absolute path to the file to read"), - offset: exports_external.coerce.number().optional().default(0).describe("Line offset to start reading from (0-indexed)"), - limit: exports_external.coerce.number().optional().default(100).describe("Maximum number of lines to read") - }) - }); -} -function createWriteFileTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "write", input.file_path); - const resolvedBackend = await resolveBackend(backend, runtime); - const { file_path, content } = input; - const result = await resolvedBackend.write(file_path, content); - if (result.error) - return result.error; - const message = new ToolMessage({ - content: `Successfully wrote to '${file_path}'`, - tool_call_id: runtime.toolCall?.id, - name: "write_file", - metadata: result.metadata - }); - if (result.filesUpdate) - return new Command({ update: { - files: result.filesUpdate, - messages: [message] - } }); - return message; - }, { - name: "write_file", - description: customDescription || WRITE_FILE_TOOL_DESCRIPTION, - schema: exports_external.object({ - file_path: exports_external.string().describe("Absolute path to the file to write"), - content: exports_external.string().default("").describe("Content to write to the file") - }) - }); -} -function createEditFileTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "write", input.file_path); - const resolvedBackend = await resolveBackend(backend, runtime); - const { file_path, old_string, new_string, replace_all = false } = input; - const result = await resolvedBackend.edit(file_path, old_string, new_string, replace_all); - if (result.error) - return result.error; - const message = new ToolMessage({ - content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`, - tool_call_id: runtime.toolCall?.id, - name: "edit_file", - metadata: result.metadata - }); - if (result.filesUpdate) - return new Command({ update: { - files: result.filesUpdate, - messages: [message] - } }); - return message; - }, { - name: "edit_file", - description: customDescription || EDIT_FILE_TOOL_DESCRIPTION, - schema: exports_external.object({ - file_path: exports_external.string().describe("Absolute path to the file to edit"), - old_string: exports_external.string().describe("String to be replaced (must match exactly)"), - new_string: exports_external.string().describe("String to replace with"), - replace_all: exports_external.boolean().optional().default(false).describe("Whether to replace all occurrences") - }) - }); -} -function createGlobTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "read", input.path ?? "/"); - const resolvedBackend = await resolveBackend(backend, runtime); - const { pattern, path: path3 = "/" } = input; - const globResult = await resolvedBackend.glob(pattern, path3); - if (globResult.error) - return `Error finding files: ${globResult.error}`; - const infos = filterByPermissions(globResult.files ?? [], permissions, "read", (info) => info.path); - if (infos.length === 0) - return `No files found matching pattern '${pattern}'`; - const result = truncateIfTooLong(infos.map((info) => info.path)); - if (Array.isArray(result)) - return result.join(` -`); - return result; - }, { - name: "glob", - description: customDescription || GLOB_TOOL_DESCRIPTION, - schema: exports_external.object({ - pattern: exports_external.string().describe("Glob pattern (e.g., '*.py', '**/*.ts')"), - path: exports_external.string().optional().default("/").describe("Base path to search from (default: /)") - }) - }); -} -function createGrepTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - enforcePermission(permissions, "read", input.path ?? "/"); - const resolvedBackend = await resolveBackend(backend, runtime); - const { pattern, path: path3 = "/", glob = null } = input; - const result = await resolvedBackend.grep(pattern, path3, glob); - if (result.error) - return result.error; - const matches = filterByPermissions(result.matches ?? [], permissions, "read", (m) => m.path); - if (matches.length === 0) - return `No matches found for pattern '${pattern}'`; - const lines = []; - let currentFile = null; - for (const match2 of matches) { - if (match2.path !== currentFile) { - currentFile = match2.path; - lines.push(` -${currentFile}:`); + const newArray = []; + for (let index2 = 0;index2 < a.length; index2++) { + const itemA = a[index2]; + const itemB = b[index2]; + const sharedValue = mergeValues4(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; } - lines.push(` ${match2.line}: ${match2.text}`); + newArray.push(sharedValue.data); } - const truncated = truncateIfTooLong(lines); - if (Array.isArray(truncated)) - return truncated.join(` -`); - return truncated; - }, { - name: "grep", - description: customDescription || GREP_TOOL_DESCRIPTION, - schema: exports_external.object({ - pattern: exports_external.string().describe("Regex pattern to search for"), - path: exports_external.string().optional().default("/").describe("Base path to search from (default: /)"), - glob: exports_external.string().optional().nullable().default(null).describe("Optional glob pattern to filter files (e.g., '*.py')") - }) - }); + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } } -function createExecuteTool(backend, options) { - const { customDescription, permissions } = options; - return tool$1(async (input, runtime) => { - const resolvedBackend = await resolveBackend(backend, runtime); - if (!isSandboxBackend(resolvedBackend)) - return "Error: Execution not available. This agent's backend does not support command execution (SandboxBackendProtocol). To use the execute tool, provide a backend that implements SandboxBackendProtocol."; - if (permissions.length > 0 && !allPathsScopedToRoutes(permissions, resolvedBackend)) - return "Error: Execution not available. Filesystem permissions cannot be used with a backend that supports command execution because shell commands can access any path, making path-based rules ineffective."; - const result = await resolvedBackend.execute(input.command); - const parts = [result.output]; - if (result.exitCode !== null) { - const status = result.exitCode === 0 ? "succeeded" : "failed"; - parts.push(` -[Command ${status} with exit code ${result.exitCode}]`); - } - if (result.truncated) - parts.push(` -[Output was truncated due to size limits]`); - return parts.join(""); - }, { - name: "execute", - description: customDescription || EXECUTE_TOOL_DESCRIPTION, - schema: exports_external.object({ command: exports_external.string().describe("The shell command to execute") }) +function createZodEnum2(values, params) { + return new ZodEnum4({ + values, + typeName: ZodFirstPartyTypeKind3.ZodEnum, + ...processCreateParams2(params) }); } -function allPathsScopedToRoutes(permissions, backend) { - if (!CompositeBackend.isInstance(backend)) - return false; - const prefixes = backend.routePrefixes; - if (prefixes.length === 0) - return false; - return permissions.every((rule) => rule.paths.every((path3) => prefixes.some((prefix) => path3.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`)))); +function cleanParams2(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; } -function createFilesystemMiddleware(options = {}) { - const { backend = (runtime) => new StateBackend(runtime), systemPrompt: customSystemPrompt = null, customToolDescriptions = null, toolTokenLimitBeforeEvict = 20000, humanMessageTokenLimitBeforeEvict = 50000, permissions = [] } = options; - if (permissions.length > 0) - validatePermissionPaths(permissions); - if (permissions.length > 0 && typeof backend !== "function" && isSandboxBackend(backend) && !allPathsScopedToRoutes(permissions, backend)) - throw new Error("Filesystem permissions cannot be used with a backend that supports command execution. Shell commands can access any path, making path-based rules ineffective. Either remove permissions, use a backend without execution support, or use a CompositeBackend with all permission paths scoped to a route prefix."); - const baseSystemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT; - const allToolsByName = { - ls: createLsTool(backend, { - customDescription: customToolDescriptions?.ls, - permissions - }), - read_file: createReadFileTool(backend, { - customDescription: customToolDescriptions?.read_file, - toolTokenLimitBeforeEvict, - permissions - }), - write_file: createWriteFileTool(backend, { - customDescription: customToolDescriptions?.write_file, - permissions - }), - edit_file: createEditFileTool(backend, { - customDescription: customToolDescriptions?.edit_file, - permissions - }), - glob: createGlobTool(backend, { - customDescription: customToolDescriptions?.glob, - permissions - }), - grep: createGrepTool(backend, { - customDescription: customToolDescriptions?.grep, - permissions - }), - execute: createExecuteTool(backend, { - customDescription: customToolDescriptions?.execute, - permissions - }) - }; - return createMiddleware({ - name: "FilesystemMiddleware", - stateSchema: FilesystemStateSchema, - tools: Object.values(allToolsByName), - async beforeAgent(state) { - if (!humanMessageTokenLimitBeforeEvict) - return; - const messages = state.messages; - if (!messages || messages.length === 0) - return; - const last = messages[messages.length - 1]; - if (!HumanMessage.isInstance(last)) - return; - if (last.additional_kwargs?.lc_evicted_to) - return; - const contentStr = extractTextFromMessage(last); - const threshold = 4 * humanMessageTokenLimitBeforeEvict; - if (contentStr.length <= threshold) - return; - const resolvedBackend = await resolveBackend(backend, { state: state || {} }); - const filePath = `/conversation_history/${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`; - const writeResult = await resolvedBackend.write(filePath, contentStr); - if (writeResult.error) - return; - const result = { messages: [new HumanMessage({ - content: last.content, - id: last.id, - additional_kwargs: { - ...last.additional_kwargs, - lc_evicted_to: filePath - }, - response_metadata: { ...last.response_metadata } - })] }; - if (writeResult.filesUpdate) - result.files = writeResult.filesUpdate; - return result; - }, - wrapModelCall: async (request, handler) => { - const supportsExecution = isSandboxBackend(await resolveBackend(backend, { - ...request.runtime, - state: request.state - })); - let tools = request.tools; - if (!supportsExecution) - tools = tools.filter((t) => t.name !== "execute"); - let filesystemPrompt = baseSystemPrompt; - if (supportsExecution) - filesystemPrompt = `${filesystemPrompt} - -${EXECUTION_SYSTEM_PROMPT}`; - const newSystemMessage = request.systemMessage.concat(filesystemPrompt); - let messages = request.messages; - if (humanMessageTokenLimitBeforeEvict && messages) { - if (messages.some((msg) => HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to)) - messages = messages.map((msg) => { - if (HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to) - return buildTruncatedHumanMessage(msg, msg.additional_kwargs.lc_evicted_to); - return msg; - }); - } - return handler({ - ...request, - tools, - messages, - systemMessage: newSystemMessage - }); - }, - wrapToolCall: async (request, handler) => { - if (!toolTokenLimitBeforeEvict) - return handler(request); - const toolName = request.toolCall?.name; - if (toolName && TOOLS_EXCLUDED_FROM_EVICTION.includes(toolName)) - return handler(request); - const result = await handler(request); - async function processToolMessage(msg, toolTokenLimitBeforeEvict2) { - if (typeof msg.content === "string" && msg.content.length > toolTokenLimitBeforeEvict2 * 4) { - const resolvedBackend = await resolveBackend(backend, { - ...request.runtime, - state: request.state - }); - const evictPath = `/large_tool_results/${sanitizeToolCallId(request.toolCall?.id || msg.tool_call_id)}`; - const writeResult = await resolvedBackend.write(evictPath, msg.content); - if (writeResult.error) - return { - message: msg, - filesUpdate: null - }; - const contentSample = createContentPreview(msg.content); - return { - message: new ToolMessage({ - content: TOO_LARGE_TOOL_MSG.replace("{tool_call_id}", msg.tool_call_id).replace("{file_path}", evictPath).replace("{content_sample}", contentSample), - tool_call_id: msg.tool_call_id, - name: msg.name, - id: msg.id, - artifact: msg.artifact, - status: msg.status, - metadata: msg.metadata, - additional_kwargs: msg.additional_kwargs, - response_metadata: msg.response_metadata - }), - filesUpdate: writeResult.filesUpdate - }; - } - return { - message: msg, - filesUpdate: null - }; - } - if (ToolMessage.isInstance(result)) { - const processed = await processToolMessage(result, toolTokenLimitBeforeEvict); - if (processed.filesUpdate) - return new Command({ update: { - files: processed.filesUpdate, - messages: [processed.message] - } }); - return processed.message; +function custom4(check3, _params = {}, fatal) { + if (check3) + return ZodAny4.create().superRefine((data, ctx) => { + const r = check3(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); } - if (isCommand(result)) { - const update = result.update; - if (!update?.messages) - return result; - let hasLargeResults = false; - const accumulatedFiles = update.files ? { ...update.files } : {}; - const processedMessages = []; - for (const msg of update.messages) - if (ToolMessage.isInstance(msg)) { - const processed = await processToolMessage(msg, toolTokenLimitBeforeEvict); - processedMessages.push(processed.message); - if (processed.filesUpdate) { - hasLargeResults = true; - Object.assign(accumulatedFiles, processed.filesUpdate); - } - } else - processedMessages.push(msg); - if (hasLargeResults) - return new Command({ update: { - ...update, - messages: processedMessages, - files: accumulatedFiles - } }); + if (!r) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } - return result; - } - }); -} -function getTaskToolDescription(subagentDescriptions) { - return context` - Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows. - - Available agent types and the tools they have access to: - ${subagentDescriptions.join(` -`)} - - When using the Task tool, you must specify a subagent_type parameter to select which agent type to use. - - ## Usage notes: - 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses - 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. - 3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. - 4. The agent's outputs should generally be trusted - 5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent - 6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. - 7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent. - - ### Example usage of the general-purpose agent: - - - "general-purpose": use this agent for general purpose tasks, it has access to all tools as the main agent. - - - - User: "I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them." - Assistant: *Uses the task tool in parallel to conduct isolated research on each of the three players* - Assistant: *Synthesizes the results of the three isolated research tasks and responds to the User* - - Research is a complex, multi-step task in it of itself. - The research of each individual player is not dependent on the research of the other players. - The assistant uses the task tool to break down the complex objective into three isolated tasks. - Each research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result. - This means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other. - - - - - User: "Analyze a single large code repository for security vulnerabilities and generate a report." - Assistant: *Launches a single \`task\` subagent for the repository analysis* - Assistant: *Receives report and integrates results into final summary* - - Subagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details. - If the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money. - - - - - User: "Schedule two meetings for me and prepare agendas for each." - Assistant: *Calls the task tool in parallel to launch two \`task\` subagents (one per meeting) to prepare agendas* - Assistant: *Returns final schedules and agendas* - - Tasks are simple individually, but subagents help silo agenda preparation. - Each subagent only needs to worry about the agenda for one meeting. - - - - - User: "I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway." - Assistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway* - - The assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls. - It is better to just complete the task directly and NOT use the \`task\`tool. - - - - ### Example usage with custom agents: - - - "content-reviewer": use this agent after you are done creating significant content or documents - "greeting-responder": use this agent when to respond to user greetings with a friendly joke - "research-analyst": use this agent to conduct thorough research on complex topics - - - - user: "Please write a function that checks if a number is prime" - assistant: Sure let me write a function that checks if a number is prime - assistant: First let me use the Write tool to write a function that checks if a number is prime - assistant: I'm going to use the Write tool to write the following code: - - function isPrime(n) {{ - if (n <= 1) return false - for (let i = 2; i * i <= n; i++) {{ - if (n % i === 0) return false - }} - return true - }} - - - Since significant content was created and the task was completed, now use the content-reviewer agent to review the work - - assistant: Now let me use the content-reviewer agent to review the code - assistant: Uses the Task tool to launch with the content-reviewer agent - - - - user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?" - - This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis - - assistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic. - assistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take - - - - user: "Hello" - - Since the user is greeting, use the greeting-responder agent to respond with a friendly joke - - assistant: "I'm going to use the Task tool to launch with the greeting-responder agent" - - `; -} -function filterStateForSubagent(state) { - const filtered = {}; - for (const [key, value] of Object.entries(state)) - if (!EXCLUDED_STATE_KEYS.includes(key)) - filtered[key] = value; - return filtered; -} -function returnCommandWithStateUpdate(result, toolCallId) { - const stateUpdate = filterStateForSubagent(result); - let content; - if (result.structuredResponse != null) - content = JSON.stringify(result.structuredResponse); - else { - const messages = result.messages; - content = messages?.[messages.length - 1]?.content || "Task completed"; - if (Array.isArray(content)) { - content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type)); - if (content.length === 0) - content = "Task completed"; - } - } - return new Command({ update: { - ...stateUpdate, - messages: [new ToolMessage({ - content, - tool_call_id: toolCallId, - name: "task" - })] - } }); -} -function getSubagents(options) { - const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware: gpMiddleware, defaultInterruptOn, subagents, generalPurposeAgent } = options; - const defaultSubagentMiddleware = defaultMiddleware || []; - const generalPurposeMiddlewareBase = gpMiddleware || defaultSubagentMiddleware; - const agents = {}; - const subagentDescriptions = []; - if (generalPurposeAgent) { - const generalPurposeMiddleware = [...generalPurposeMiddlewareBase]; - if (defaultInterruptOn) - generalPurposeMiddleware.push(humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn })); - agents["general-purpose"] = createAgent({ - model: defaultModel, - systemPrompt: DEFAULT_SUBAGENT_PROMPT, - tools: defaultTools, - middleware: generalPurposeMiddleware, - name: "general-purpose" + return; }); - subagentDescriptions.push(`- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`); - } - for (const agentParams of subagents) { - subagentDescriptions.push(`- ${agentParams.name}: ${agentParams.description}`); - if ("runnable" in agentParams) - agents[agentParams.name] = agentParams.runnable; - else { - const middleware = agentParams.middleware ? [...defaultSubagentMiddleware, ...agentParams.middleware] : [...defaultSubagentMiddleware]; - const interruptOn = agentParams.interruptOn || defaultInterruptOn; - if (interruptOn) - middleware.push(humanInTheLoopMiddleware({ interruptOn })); - agents[agentParams.name] = createAgent({ - model: agentParams.model ?? defaultModel, - systemPrompt: agentParams.systemPrompt, - tools: agentParams.tools ?? defaultTools, - middleware, - name: agentParams.name, - ...agentParams.responseFormat != null && { responseFormat: agentParams.responseFormat } - }); - } - } - return { - agents, - descriptions: subagentDescriptions - }; + return ZodAny4.create(); } -function createTaskTool(options) { - const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware, defaultInterruptOn, subagents, generalPurposeAgent, taskDescription } = options; - const { agents: subagentGraphs, descriptions: subagentDescriptions } = getSubagents({ - defaultModel, - defaultTools, - defaultMiddleware, - generalPurposeMiddleware, - defaultInterruptOn, - subagents, - generalPurposeAgent - }); - return tool$1(async (input, config2) => { - const { description, subagent_type } = input; - if (!(subagent_type in subagentGraphs)) { - const allowedTypes = Object.keys(subagentGraphs).map((k) => `\`${k}\``).join(", "); - throw new Error(`Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`); +var handleResult2 = (ctx, result) => { + if (isValid2(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); } - const subagent = subagentGraphs[subagent_type]; - const subagentState = filterStateForSubagent(getCurrentTaskInput()); - subagentState.messages = [new HumanMessage({ content: description })]; - const subagentConfig = { - ...config2, - configurable: { - ...config2.configurable, - ls_agent_type: "subagent" + return { + success: false, + get error() { + if (this._error) + return this._error; + const error90 = new ZodError5(ctx.common.issues); + this._error = error90; + return this._error; } }; - const result = await subagent.invoke(subagentState, subagentConfig); - if (!config2.toolCall?.id) { - if (result.structuredResponse != null) - return JSON.stringify(result.structuredResponse); - const messages = result.messages; - let content = messages?.[messages.length - 1]?.content || "Task completed"; - if (Array.isArray(content)) { - content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type)); - if (content.length === 0) - return "Task completed"; - return content.map((block) => ("text" in block) ? block.text : JSON.stringify(block)).join(` -`); + } +}, cuidRegex2, cuid2Regex2, ulidRegex2, uuidRegex2, nanoidRegex2, jwtRegex2, durationRegex2, emailRegex2, _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex3, ipv4Regex2, ipv4CidrRegex2, ipv6Regex2, ipv6CidrRegex2, base64Regex2, base64urlRegex2, dateRegexSource2 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex2, ZodString4, ZodNumber4, ZodBigInt4, ZodBoolean4, ZodDate4, ZodSymbol4, ZodUndefined4, ZodNull4, ZodAny4, ZodUnknown4, ZodNever4, ZodVoid4, ZodArray4, ZodObject4, ZodUnion4, getDiscriminator2 = (type) => { + if (type instanceof ZodLazy4) { + return getDiscriminator2(type.schema); + } else if (type instanceof ZodEffects2) { + return getDiscriminator2(type.innerType()); + } else if (type instanceof ZodLiteral4) { + return [type.value]; + } else if (type instanceof ZodEnum4) { + return type.options; + } else if (type instanceof ZodNativeEnum2) { + return util3.objectValues(type.enum); + } else if (type instanceof ZodDefault4) { + return getDiscriminator2(type._def.innerType); + } else if (type instanceof ZodUndefined4) { + return [undefined]; + } else if (type instanceof ZodNull4) { + return [null]; + } else if (type instanceof ZodOptional4) { + return [undefined, ...getDiscriminator2(type.unwrap())]; + } else if (type instanceof ZodNullable4) { + return [null, ...getDiscriminator2(type.unwrap())]; + } else if (type instanceof ZodBranded2) { + return getDiscriminator2(type.unwrap()); + } else if (type instanceof ZodReadonly4) { + return getDiscriminator2(type.unwrap()); + } else if (type instanceof ZodCatch4) { + return getDiscriminator2(type._def.innerType); + } else { + return []; + } +}, ZodDiscriminatedUnion4, ZodIntersection4, ZodTuple4, ZodRecord4, ZodMap4, ZodSet4, ZodFunction3, ZodLazy4, ZodLiteral4, ZodEnum4, ZodNativeEnum2, ZodPromise4, ZodEffects2, ZodOptional4, ZodNullable4, ZodDefault4, ZodCatch4, ZodNaN4, BRAND2, ZodBranded2, ZodPipeline2, ZodReadonly4, late2, ZodFirstPartyTypeKind3, instanceOfType2 = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom4((data) => data instanceof cls, params), stringType2, numberType2, nanType2, bigIntType2, booleanType2, dateType2, symbolType2, undefinedType2, nullType2, anyType2, unknownType2, neverType2, voidType2, arrayType2, objectType2, strictObjectType2, unionType2, discriminatedUnionType2, intersectionType2, tupleType2, recordType2, mapType2, setType2, functionType2, lazyType2, literalType2, enumType2, nativeEnumType2, promiseType2, effectsType2, optionalType2, nullableType2, preprocessType2, pipelineType2, ostring2 = () => stringType2().optional(), onumber2 = () => numberType2().optional(), oboolean2 = () => booleanType2().optional(), coerce2, NEVER4; +var init_types15 = __esm(() => { + init_ZodError2(); + init_errors10(); + init_errorUtil2(); + init_parseUtil2(); + init_util4(); + cuidRegex2 = /^c[^\s-]{8,}$/i; + cuid2Regex2 = /^[0-9a-z]+$/; + ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + nanoidRegex2 = /^[a-z0-9_-]{21}$/i; + jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + durationRegex2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + ipv4Regex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv4CidrRegex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + dateRegex2 = new RegExp(`^${dateRegexSource2}$`); + ZodString4 = class ZodString4 extends ZodType4 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); } - return content; - } - return returnCommandWithStateUpdate(result, config2.toolCall.id); - }, { - name: "task", - description: taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions), - schema: exports_external.object({ - description: exports_external.string().describe("The task to execute with the selected agent"), - subagent_type: exports_external.string().describe(`Name of the agent to use. Available: ${Object.keys(subagentGraphs).join(", ")}`) - }) - }); -} -function createSubAgentMiddleware(options) { - const { defaultModel, defaultTools = [], defaultMiddleware = null, generalPurposeMiddleware = null, defaultInterruptOn = null, subagents = [], systemPrompt = TASK_SYSTEM_PROMPT, generalPurposeAgent = true, taskDescription = null } = options; - return createMiddleware({ - name: "subAgentMiddleware", - tools: [createTaskTool({ - defaultModel, - defaultTools, - defaultMiddleware, - generalPurposeMiddleware, - defaultInterruptOn, - subagents, - generalPurposeAgent, - taskDescription - })], - wrapModelCall: async (request, handler) => { - if (systemPrompt !== null) - return handler({ - ...request, - systemMessage: request.systemMessage.concat(new SystemMessage({ content: systemPrompt })) + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.string, + received: ctx2.parsedType }); - return handler(request); - } - }); -} -function patchDanglingToolCalls(messages) { - if (!messages || messages.length === 0) - return { - patchedMessages: [], - needsPatch: false - }; - const allToolCallIds = /* @__PURE__ */ new Set; - for (const msg of messages) - if (AIMessage.isInstance(msg) && msg.tool_calls != null) { - for (const tc of msg.tool_calls) - if (tc.id) - allToolCallIds.add(tc.id); - } - const patchedMessages = []; - let needsPatch = false; - for (let i = 0;i < messages.length; i++) { - const msg = messages[i]; - if (ToolMessage.isInstance(msg)) { - if (!allToolCallIds.has(msg.tool_call_id)) { - needsPatch = true; - continue; + return INVALID2; } - } - patchedMessages.push(msg); - if (AIMessage.isInstance(msg) && msg.tool_calls != null) { - for (const toolCall of msg.tool_calls) - if (!messages.slice(i + 1).find((m) => ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id)) { - needsPatch = true; - const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`; - patchedMessages.push(new ToolMessage({ - content: toolMsg, - name: toolCall.name, - tool_call_id: toolCall.id - })); - } - } - } - return { - patchedMessages, - needsPatch - }; -} -function createPatchToolCallsMiddleware() { - return createMiddleware({ - name: "patchToolCallsMiddleware", - beforeAgent: async (state) => { - const messages = state.messages; - if (!messages || messages.length === 0) - return; - const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); - if (!needsPatch) - return; - return { messages: [new RemoveMessage({ id: REMOVE_ALL_MESSAGES }), ...patchedMessages] }; - }, - wrapModelCall: async (request, handler) => { - const messages = request.messages; - if (!messages || messages.length === 0) - return handler(request); - const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); - if (!needsPatch) - return handler(request); - return handler({ - ...request, - messages: patchedMessages - }); - } - }); -} -function formatMemoryContents(contents, sources) { - if (Object.keys(contents).length === 0) - return "(No memory loaded)"; - const sections = []; - for (const path3 of sources) - if (contents[path3]) - sections.push(`${path3} -${contents[path3]}`); - if (sections.length === 0) - return "(No memory loaded)"; - return sections.join(` - -`); -} -async function loadMemoryFromBackend(backend, path3) { - const adaptedBackend = adaptBackendProtocol(backend); - if (!adaptedBackend.downloadFiles) { - const content = await adaptedBackend.read(path3); - if (content.error) - return null; - if (typeof content.content !== "string") - return null; - return content.content; - } - const results = await adaptedBackend.downloadFiles([path3]); - if (results.length !== 1) - throw new Error(`Expected 1 response for path ${path3}, got ${results.length}`); - const response = results[0]; - if (response.error != null) { - if (response.error === "file_not_found") - return null; - throw new Error(`Failed to download ${path3}: ${response.error}`); - } - if (response.content != null) - return new TextDecoder().decode(response.content); - return null; -} -function createMemoryMiddleware(options) { - const { backend, sources, addCacheControl = false } = options; - return createMiddleware({ - name: "MemoryMiddleware", - stateSchema: MemoryStateSchema, - async beforeAgent(state) { - if ("memoryContents" in state && state.memoryContents != null) - return; - const resolvedBackend = await resolveBackend(backend, { state }); - const contents = {}; - for (const path3 of sources) - try { - const content = await loadMemoryFromBackend(resolvedBackend, path3); - if (content) - contents[path3] = content; - } catch (error51) { - console.debug(`Failed to load memory from ${path3}:`, error51); + const status = new ParseStatus2; + let ctx = undefined; + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + if (input.data.length < check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: check3.value, + type: "string", + inclusive: true, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + if (input.data.length > check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: check3.value, + type: "string", + inclusive: true, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "length") { + const tooBig = input.data.length > check3.value; + const tooSmall = input.data.length < check3.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: check3.value, + type: "string", + inclusive: true, + exact: true, + message: check3.message + }); + } else if (tooSmall) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: check3.value, + type: "string", + inclusive: true, + exact: true, + message: check3.message + }); + } + status.dirty(); + } + } else if (check3.kind === "email") { + if (!emailRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "email", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "emoji") { + if (!emojiRegex3) { + emojiRegex3 = new RegExp(_emojiRegex2, "u"); + } + if (!emojiRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "emoji", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "uuid") { + if (!uuidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "uuid", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "nanoid") { + if (!nanoidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "nanoid", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cuid") { + if (!cuidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cuid", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cuid2") { + if (!cuid2Regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cuid2", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "ulid") { + if (!ulidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "ulid", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "url", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "regex") { + check3.regex.lastIndex = 0; + const testResult = check3.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "regex", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "trim") { + input.data = input.data.trim(); + } else if (check3.kind === "includes") { + if (!input.data.includes(check3.value, check3.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: { includes: check3.value, position: check3.position }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check3.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check3.kind === "startsWith") { + if (!input.data.startsWith(check3.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: { startsWith: check3.value }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "endsWith") { + if (!input.data.endsWith(check3.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: { endsWith: check3.value }, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "datetime") { + const regex2 = datetimeRegex2(check3); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: "datetime", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "date") { + const regex2 = dateRegex2; + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: "date", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "time") { + const regex2 = timeRegex2(check3); + if (!regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_string, + validation: "time", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "duration") { + if (!durationRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "duration", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "ip") { + if (!isValidIP2(input.data, check3.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "ip", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "jwt") { + if (!isValidJWT4(input.data, check3.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "jwt", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "cidr") { + if (!isValidCidr2(input.data, check3.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cidr", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "base64") { + if (!base64Regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "base64", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "base64url") { + if (!base64urlRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "base64url", + code: ZodIssueCode4.invalid_string, + message: check3.message + }); + status.dirty(); + } + } else { + util3.assertNever(check3); } - return { memoryContents: contents }; - }, - wrapModelCall(request, handler) { - const formattedContents = formatMemoryContents(request.state?.memoryContents || {}, sources); - const memorySection = MEMORY_SYSTEM_PROMPT.replace("{memory_contents}", formattedContents); - const existingContent = request.systemMessage.content; - const newSystemMessage = new SystemMessage({ content: [...typeof existingContent === "string" ? [{ - type: "text", - text: existingContent - }] : Array.isArray(existingContent) ? existingContent : [], { - type: "text", - text: memorySection, - ...addCacheControl && { cache_control: { type: "ephemeral" } } - }] }); - return handler({ - ...request, - systemMessage: newSystemMessage + } + return { status: status.value, value: input.data }; + } + _regex(regex2, validation, message) { + return this.refinement((data) => regex2.test(data), { + validation, + code: ZodIssueCode4.invalid_string, + ...errorUtil2.errToObj(message) }); } - }); -} -function skillsMetadataReducer(current, update) { - if (!update || update.length === 0) - return current || []; - if (!current || current.length === 0) - return update; - const merged = /* @__PURE__ */ new Map; - for (const skill of current) - merged.set(skill.name, skill); - for (const skill of update) - merged.set(skill.name, skill); - return Array.from(merged.values()); -} -function validateSkillName$1(name, directoryName) { - if (!name) - return { - valid: false, - error: "name is required" - }; - if (name.length > 64) - return { - valid: false, - error: "name exceeds 64 characters" - }; - if (name.startsWith("-") || name.endsWith("-") || name.includes("--")) - return { - valid: false, - error: "name must be lowercase alphanumeric with single hyphens only" - }; - for (const c of name) { - if (c === "-") - continue; - if (/\p{Ll}/u.test(c) || /\p{Nd}/u.test(c)) - continue; - return { - valid: false, - error: "name must be lowercase alphanumeric with single hyphens only" - }; - } - if (name !== directoryName) - return { - valid: false, - error: `name '${name}' must match directory name '${directoryName}'` - }; - return { - valid: true, - error: "" - }; -} -function validateMetadata(raw2, skillPath) { - if (typeof raw2 !== "object" || raw2 === null || Array.isArray(raw2)) { - if (raw2) - console.warn(`Ignoring non-object metadata in ${skillPath} (got ${typeof raw2})`); - return {}; - } - const result = {}; - for (const [k, v] of Object.entries(raw2)) - result[String(k)] = String(v); - return result; -} -function formatSkillAnnotations(skill) { - const parts = []; - if (skill.license) - parts.push(`License: ${skill.license}`); - if (skill.compatibility) - parts.push(`Compatibility: ${skill.compatibility}`); - return parts.join(", "); -} -function parseSkillMetadataFromContent(content, skillPath, directoryName) { - if (content.length > 10485760) { - console.warn(`Skipping ${skillPath}: content too large (${content.length} bytes)`); - return null; - } - const match2 = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/); - if (!match2) { - console.warn(`Skipping ${skillPath}: no valid YAML frontmatter found`); - return null; - } - const frontmatterStr = match2[1]; - let frontmatterData; - try { - frontmatterData = import_yaml.default.parse(frontmatterStr); - } catch (e) { - console.warn(`Invalid YAML in ${skillPath}:`, e); - return null; - } - if (!frontmatterData || typeof frontmatterData !== "object") { - console.warn(`Skipping ${skillPath}: frontmatter is not a mapping`); - return null; - } - const name = String(frontmatterData.name ?? "").trim(); - const description = String(frontmatterData.description ?? "").trim(); - if (!name || !description) { - console.warn(`Skipping ${skillPath}: missing required 'name' or 'description'`); - return null; - } - const validation = validateSkillName$1(name, directoryName); - if (!validation.valid) - console.warn(`Skill '${name}' in ${skillPath} does not follow Agent Skills specification: ${validation.error}. Consider renaming for spec compliance.`); - let descriptionStr = description; - if (descriptionStr.length > 1024) { - console.warn(`Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} characters in ${skillPath}, truncating`); - descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH); - } - const rawTools = frontmatterData["allowed-tools"]; - let allowedTools; - if (rawTools) - if (Array.isArray(rawTools)) - allowedTools = rawTools.map((t) => String(t).trim()).filter(Boolean); - else - allowedTools = String(rawTools).split(/\s+/).filter(Boolean); - else - allowedTools = []; - let compatibilityStr = String(frontmatterData.compatibility ?? "").trim() || null; - if (compatibilityStr && compatibilityStr.length > 500) { - console.warn(`Compatibility exceeds 500 characters in ${skillPath}, truncating`); - compatibilityStr = compatibilityStr.slice(0, 500); - } - return { - name, - description: descriptionStr, - path: skillPath, - metadata: validateMetadata(frontmatterData.metadata ?? {}, skillPath), - license: String(frontmatterData.license ?? "").trim() || null, - compatibility: compatibilityStr, - allowedTools, - module: validateModulePath(frontmatterData.module) - }; -} -async function listSkillsFromBackend(backend, sourcePath) { - const adaptedBackend = adaptBackendProtocol(backend); - const skills = []; - const pathSep = sourcePath.includes("\\") ? "\\" : "/"; - const normalizedPath = sourcePath.endsWith("/") || sourcePath.endsWith("\\") ? sourcePath : `${sourcePath}${pathSep}`; - let fileInfos; - try { - const lsResult = await adaptedBackend.ls(normalizedPath); - if (lsResult.error || !lsResult.files) - return []; - fileInfos = lsResult.files; - } catch { - return []; - } - const entries = fileInfos.map((info) => ({ - name: info.path.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "", - type: info.is_dir ? "directory" : "file" - })); - for (const entry of entries) { - if (entry.type !== "directory") - continue; - const skillMdPath = `${normalizedPath}${entry.name}${pathSep}SKILL.md`; - let content; - if (adaptedBackend.downloadFiles) { - const results = await adaptedBackend.downloadFiles([skillMdPath]); - if (results.length !== 1) - continue; - const response = results[0]; - if (response.error != null || response.content == null) - continue; - content = new TextDecoder().decode(response.content); - } else { - const readResult = await adaptedBackend.read(skillMdPath); - if (readResult.error) - continue; - if (typeof readResult.content !== "string") - continue; - content = readResult.content; + _addCheck(check3) { + return new ZodString4({ + ...this._def, + checks: [...this._def.checks, check3] + }); } - const metadata = parseSkillMetadataFromContent(content, skillMdPath, entry.name); - if (metadata) - skills.push(metadata); - } - return skills; -} -function formatSkillsLocations(sources) { - if (sources.length === 0) - return "**Skills Sources:** None configured"; - const lines = []; - for (let i = 0;i < sources.length; i++) { - const sourcePath = sources[i]; - const name = sourcePath.replace(/[/\\]$/, "").split(/[/\\]/).filter(Boolean).pop()?.replace(/^./, (c) => c.toUpperCase()) || "Skills"; - const suffix = i === sources.length - 1 ? " (higher priority)" : ""; - lines.push(`**${name} Skills**: \`${sourcePath}\`${suffix}`); - } - return lines.join(` -`); -} -function formatSkillsList(skills, sources) { - if (skills.length === 0) - return `(No skills available yet. You can create skills in ${sources.map((s) => `\`${s}\``).join(" or ")})`; - const lines = []; - for (const skill of skills) { - const annotations = formatSkillAnnotations(skill); - let descLine = `- **${skill.name}**: ${skill.description}`; - if (annotations) - descLine += ` (${annotations})`; - lines.push(descLine); - if (skill.allowedTools && skill.allowedTools.length > 0) - lines.push(` → Allowed tools: ${skill.allowedTools.join(", ")}`); - lines.push(` → Read \`${skill.path}\` for full instructions`); - if (skill.module !== undefined) - lines.push(` → Import: \`await import("@/skills/${skill.name}")\``); - } - return lines.join(` -`); -} -function endsWithModuleExtension(value) { - for (const ext of SKILL_MODULE_EXTENSIONS) - if (value.endsWith(ext)) - return true; - return false; -} -function validateModulePath(raw2) { - if (raw2 === null || raw2 === undefined) - return; - if (typeof raw2 !== "string") - return; - const stripped = raw2.trim(); - if (stripped === "") - return; - const normalized = stripped.startsWith("./") ? stripped.slice(2) : stripped; - if (normalized.startsWith("/")) - return; - if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../") || normalized.endsWith("/..")) - return; - if (normalized.endsWith(".d.ts") || normalized.endsWith(".d.mts") || normalized.endsWith(".d.cts")) - return; - if (!endsWithModuleExtension(normalized)) - return; - return normalized; -} -function createSkillsMiddleware(options) { - const { backend, sources } = options; - let loadedSkills = []; - return createMiddleware({ - name: "SkillsMiddleware", - stateSchema: SkillsStateSchema, - async beforeAgent(state) { - if (loadedSkills.length > 0) - return; - if ("skillsMetadata" in state && Array.isArray(state.skillsMetadata) && state.skillsMetadata.length > 0) { - loadedSkills = state.skillsMetadata; - return; - } - const resolvedBackend = await resolveBackend(backend, { state }); - const allSkills = /* @__PURE__ */ new Map; - for (const sourcePath of sources) - try { - const skills = await listSkillsFromBackend(resolvedBackend, sourcePath); - for (const skill of skills) - allSkills.set(skill.name, skill); - } catch (error51) { - console.debug(`[BackendSkillsMiddleware] Failed to load skills from ${sourcePath}:`, error51); - } - loadedSkills = Array.from(allSkills.values()); - return { skillsMetadata: loadedSkills }; - }, - wrapModelCall(request, handler) { - const skillsMetadata = loadedSkills.length > 0 ? loadedSkills : request.state?.skillsMetadata || []; - const skillsLocations = formatSkillsLocations(sources); - const skillsList = formatSkillsList(skillsMetadata, sources); - const skillsSection = SKILLS_SYSTEM_PROMPT.replace("{skills_locations}", skillsLocations).replace("{skills_list}", skillsList); - const newSystemMessage = request.systemMessage.concat(skillsSection); - return handler({ - ...request, - systemMessage: newSystemMessage + email(message) { + return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil2.errToObj(message) }); } - }); -} -function resolveHeaders(headers) { - const resolved = { ...headers }; - if (!("x-auth-scheme" in resolved)) - resolved["x-auth-scheme"] = "langsmith"; - return resolved; -} -async function notifyParent(callbackGraphId, callbackThreadId, message, options) { - try { - await new Client2({ - apiUrl: options?.url ?? undefined, - apiKey: null, - defaultHeaders: resolveHeaders(options?.headers) - }).runs.create(callbackThreadId, callbackGraphId, { input: { messages: [{ - role: "user", - content: message - }] } }); - } catch (e) { - console.warn(`[CompletionCallbackMiddleware] Failed to notify callback thread ${callbackThreadId}:`, e); - } -} -function extractLastMessage(state, taskId) { - const messages = state.messages; - if (!messages || messages.length === 0) - throw new Error(`Expected at least one message in state ${JSON.stringify(state)}`); - const last = messages[messages.length - 1]; - if (!AIMessage.isInstance(last)) - throw new TypeError(`Expected an AIMessage, got ${typeof last === "object" && last !== null ? last.constructor?.name ?? typeof last : typeof last} instead`); - let textContent = last.text; - if (textContent.length > MAX_MESSAGE_LENGTH) { - textContent = textContent.slice(0, MAX_MESSAGE_LENGTH) + TRUNCATION_SUFFIX; - if (taskId) - textContent += ` Result truncated. Use \`check_async_task(task_id='${taskId}')\` to retrieve the full result if needed.`; - } - return textContent; -} -function createCompletionCallbackMiddleware(options) { - const { callbackGraphId, url: url2, headers } = options; - async function sendNotification(callbackThreadId, message) { - await notifyParent(callbackGraphId, callbackThreadId, message, { - url: url2, - headers - }); - } - function getTaskId(runtime) { - return runtime?.configurable?.thread_id; - } - function formatNotification(body, runtime) { - const taskId = getTaskId(runtime); - return `${taskId ? `[task_id=${taskId}]` : ""}${body}`; - } - return createMiddleware({ - name: "CompletionCallbackMiddleware", - stateSchema: CompletionCallbackStateSchema, - async afterAgent(state, runtime) { - const callbackThreadId = state[CALLBACK_THREAD_ID_KEY]; - if (callbackThreadId == null) - throw new Error(`Missing required state key '${CALLBACK_THREAD_ID_KEY}'`); - const taskId = getTaskId(runtime); - await sendNotification(callbackThreadId, formatNotification(`Completed. Result: ${extractLastMessage(state, typeof taskId === "string" ? taskId : undefined)}`, runtime)); - }, - async wrapModelCall(request, handler) { - try { - return await handler(request); - } catch (e) { - const callbackThreadId = request.state[CALLBACK_THREAD_ID_KEY]; - if (typeof callbackThreadId === "string") - await sendNotification(callbackThreadId, formatNotification("The agent encountered an error while calling the model.", request.runtime)); - throw e; + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil2.errToObj(options?.message) + }); } - }); -} -function computeSummarizationDefaults(resolvedModel) { - if (resolvedModel.profile && typeof resolvedModel.profile === "object" && "maxInputTokens" in resolvedModel.profile && typeof resolvedModel.profile.maxInputTokens === "number") - return { - trigger: PROFILE_TRIGGER, - keep: PROFILE_KEEP, - truncateArgsSettings: PROFILE_TRUNCATE_ARGS - }; - return { - trigger: FALLBACK_TRIGGER, - keep: FALLBACK_KEEP, - truncateArgsSettings: FALLBACK_TRUNCATE_ARGS - }; -} -function isSummaryMessage(msg) { - if (!HumanMessage.isInstance(msg)) - return false; - return msg.additional_kwargs?.lc_source === "summarization"; -} -function createSummarizationMiddleware(options) { - const { model, backend, summaryPrompt = DEFAULT_SUMMARY_PROMPT2, trimTokensToSummarize = DEFAULT_TRIM_TOKEN_LIMIT, historyPathPrefix = "/conversation_history" } = options; - let trigger = options.trigger; - let keep = options.keep ?? { - type: "messages", - value: DEFAULT_MESSAGES_TO_KEEP - }; - let truncateArgsSettings = options.truncateArgsSettings; - let defaultsComputed = trigger != null; - let truncateTrigger = truncateArgsSettings?.trigger; - let truncateKeep = truncateArgsSettings?.keep ?? { - type: "messages", - value: 20 - }; - let maxArgLength = truncateArgsSettings?.maxLength ?? 2000; - let truncationText = truncateArgsSettings?.truncationText ?? "...(argument truncated)"; - function applyModelDefaults(resolvedModel) { - if (defaultsComputed) - return; - defaultsComputed = true; - const defaults = computeSummarizationDefaults(resolvedModel); - trigger = defaults.trigger; - keep = options.keep ?? defaults.keep; - if (!options.truncateArgsSettings) { - truncateArgsSettings = defaults.truncateArgsSettings; - truncateTrigger = defaults.truncateArgsSettings.trigger; - truncateKeep = defaults.truncateArgsSettings.keep ?? { - type: "messages", - value: 20 - }; - maxArgLength = defaults.truncateArgsSettings.maxLength ?? 2000; - truncationText = defaults.truncateArgsSettings.truncationText ?? "...(argument truncated)"; + date(message) { + return this._addCheck({ kind: "date", message }); } - } - let sessionId = null; - let tokenEstimationMultiplier = 1; - function getSessionId(state) { - if (state._summarizationSessionId) - return state._summarizationSessionId; - if (!sessionId) - sessionId = `session_${crypto.randomUUID().substring(0, 8)}`; - return sessionId; - } - function getHistoryPath(state) { - return `${historyPathPrefix}/${getSessionId(state)}.md`; - } - let cachedModel = undefined; - async function getChatModel() { - if (cachedModel) - return cachedModel; - if (!model) - throw new Error("Summarization middleware could not resolve a model. Provide `options.model` or ensure `request.model` is present."); - if (typeof model === "string") - cachedModel = await initChatModel(model); - else - cachedModel = model; - return cachedModel; - } - function getMaxInputTokens(resolvedModel) { - const profile = resolvedModel.profile; - if (profile && typeof profile === "object" && "maxInputTokens" in profile && typeof profile.maxInputTokens === "number") - return profile.maxInputTokens; - } - function shouldSummarize(messages, totalTokens, maxInputTokens) { - if (!trigger) - return false; - const adjustedTokens = totalTokens * tokenEstimationMultiplier; - const triggers = Array.isArray(trigger) ? trigger : [trigger]; - for (const t of triggers) { - if (t.type === "messages" && messages.length >= t.value) - return true; - if (t.type === "tokens" && adjustedTokens >= t.value) - return true; - if (t.type === "fraction" && maxInputTokens) { - if (adjustedTokens >= Math.floor(maxInputTokens * t.value)) - return true; + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil2.errToObj(options?.message) + }); } - return false; - } - function findSafeCutoffPoint(messages, cutoffIndex) { - if (cutoffIndex >= messages.length || !ToolMessage.isInstance(messages[cutoffIndex])) - return cutoffIndex; - let forwardIdx = cutoffIndex; - while (forwardIdx < messages.length && ToolMessage.isInstance(messages[forwardIdx])) - forwardIdx++; - const toolCallIds = /* @__PURE__ */ new Set; - for (let i = cutoffIndex;i < forwardIdx; i++) { - const toolMsg = messages[i]; - if (toolMsg.tool_call_id) - toolCallIds.add(toolMsg.tool_call_id); + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); } - let backwardIdx = null; - for (let i = cutoffIndex - 1;i >= 0; i--) { - const msg = messages[i]; - if (AIMessage.isInstance(msg) && msg.tool_calls) { - const aiToolCallIds = new Set(msg.tool_calls.map((tc) => tc.id).filter((id) => id != null)); - for (const id of toolCallIds) - if (aiToolCallIds.has(id)) { - backwardIdx = i; - break; - } - if (backwardIdx !== null) - break; + regex(regex2, message) { + return this._addCheck({ + kind: "regex", + regex: regex2, + ...errorUtil2.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil2.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil2.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil2.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil2.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil2.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil2.errToObj(message) + }); + } + nonempty(message) { + return this.min(1, errorUtil2.errToObj(message)); + } + trim() { + return new ZodString4({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new ZodString4({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new ZodString4({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } + return min; } - if (backwardIdx === null) - return forwardIdx; - if (cutoffIndex - backwardIdx > cutoffIndex / 2 && cutoffIndex > 2) - return forwardIdx; - return backwardIdx; - } - function determineCutoffIndex(messages, maxInputTokens) { - let rawCutoff; - if (keep.type === "messages") { - if (messages.length <= keep.value) - return 0; - rawCutoff = messages.length - keep.value; - } else if (keep.type === "tokens" || keep.type === "fraction") { - const targetTokenCount = keep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * keep.value) : keep.value; - let tokensKept = 0; - rawCutoff = 0; - for (let i = messages.length - 1;i >= 0; i--) { - const msgTokens = countTokensApproximately([messages[i]]); - if (tokensKept + msgTokens > targetTokenCount) { - rawCutoff = i + 1; - break; + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; } - tokensKept += msgTokens; } - } else - return 0; - return findSafeCutoffPoint(messages, rawCutoff); - } - function shouldTruncateArgs(messages, totalTokens, maxInputTokens) { - if (!truncateTrigger) - return false; - const adjustedTokens = totalTokens * tokenEstimationMultiplier; - if (truncateTrigger.type === "messages") - return messages.length >= truncateTrigger.value; - if (truncateTrigger.type === "tokens") - return adjustedTokens >= truncateTrigger.value; - if (truncateTrigger.type === "fraction" && maxInputTokens) - return adjustedTokens >= Math.floor(maxInputTokens * truncateTrigger.value); - return false; - } - function determineTruncateCutoffIndex(messages, maxInputTokens) { - let rawCutoff; - if (truncateKeep.type === "messages") { - if (messages.length <= truncateKeep.value) - return messages.length; - rawCutoff = messages.length - truncateKeep.value; - } else if (truncateKeep.type === "tokens" || truncateKeep.type === "fraction") { - const targetTokenCount = truncateKeep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * truncateKeep.value) : truncateKeep.value; - let tokensKept = 0; - rawCutoff = 0; - for (let i = messages.length - 1;i >= 0; i--) { - const msgTokens = countTokensApproximately([messages[i]]); - if (tokensKept + msgTokens > targetTokenCount) { - rawCutoff = i + 1; - break; - } - tokensKept += msgTokens; + return max; + } + }; + ZodString4.create = (params) => { + return new ZodString4({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams2(params) + }); + }; + ZodNumber4 = class ZodNumber4 extends ZodType4 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); } - } else - return messages.length; - return findSafeCutoffPoint(messages, rawCutoff); - } - function countTotalTokens(messages, systemMessage, tools) { - return countTokensApproximately(systemMessage && SystemMessage.isInstance(systemMessage) ? [systemMessage, ...messages] : [...messages], tools && Array.isArray(tools) && tools.length > 0 ? tools : null); - } - function compactToolResults(messages, maxInputTokens, systemMessage, tools) { - const toolMessageIndices = []; - for (let i = 0;i < messages.length; i++) - if (ToolMessage.isInstance(messages[i])) - toolMessageIndices.push(i); - if (toolMessageIndices.length === 0) - return { - messages, - modified: false - }; - const overheadTokens = countTotalTokens(messages.filter((m) => !ToolMessage.isInstance(m)), systemMessage, tools); - const adjustedMax = maxInputTokens / tokenEstimationMultiplier; - const budgetForTools = Math.max(adjustedMax * 0.7 - overheadTokens, 1000); - const perToolBudgetChars = Math.floor(budgetForTools / toolMessageIndices.length) * 4; - let modified = false; - const result = [...messages]; - for (const idx of toolMessageIndices) { - const msg = messages[idx]; - const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content); - if (content.length > perToolBudgetChars) { - result[idx] = new ToolMessage({ - content: content.substring(0, perToolBudgetChars) + ` -...(result truncated)`, - tool_call_id: msg.tool_call_id, - name: msg.name + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.number, + received: ctx2.parsedType }); - modified = true; + return INVALID2; + } + let ctx = undefined; + const status = new ParseStatus2; + for (const check3 of this._def.checks) { + if (check3.kind === "int") { + if (!util3.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: "integer", + received: "float", + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "min") { + const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: check3.value, + type: "number", + inclusive: check3.inclusive, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: check3.value, + type: "number", + inclusive: check3.inclusive, + exact: false, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "multipleOf") { + if (floatSafeRemainder4(input.data, check3.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.not_multiple_of, + multipleOf: check3.value, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.not_finite, + message: check3.message + }); + status.dirty(); + } + } else { + util3.assertNever(check3); + } } + return { status: status.value, value: input.data }; } - return { - messages: result, - modified - }; - } - function truncateArgs(messages, maxInputTokens, systemMessage, tools) { - if (!shouldTruncateArgs(messages, countTotalTokens(messages, systemMessage, tools), maxInputTokens)) - return { - messages, - modified: false - }; - const cutoffIndex = determineTruncateCutoffIndex(messages, maxInputTokens); - if (cutoffIndex >= messages.length) - return { - messages, - modified: false - }; - const truncatedMessages = []; - let modified = false; - for (let i = 0;i < messages.length; i++) { - const msg = messages[i]; - if (i < cutoffIndex && AIMessage.isInstance(msg) && msg.tool_calls) { - const truncatedToolCalls = msg.tool_calls.map((toolCall) => { - const args = toolCall.args || {}; - const truncatedArgs = {}; - let toolModified = false; - for (const [key, value] of Object.entries(args)) - if (typeof value === "string" && value.length > maxArgLength && (toolCall.name === "write_file" || toolCall.name === "edit_file")) { - truncatedArgs[key] = value.substring(0, 20) + truncationText; - toolModified = true; - } else - truncatedArgs[key] = value; - if (toolModified) { - modified = true; - return { - ...toolCall, - args: truncatedArgs - }; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil2.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil2.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil2.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil2.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber4({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil2.toString(message) } - return toolCall; - }); - if (modified) { - const truncatedMsg = new AIMessage({ - content: msg.content, - tool_calls: truncatedToolCalls, - additional_kwargs: msg.additional_kwargs - }); - truncatedMessages.push(truncatedMsg); - } else - truncatedMessages.push(msg); - } else - truncatedMessages.push(msg); + ] + }); } - return { - messages: truncatedMessages, - modified - }; - } - function filterSummaryMessages(messages) { - return messages.filter((msg) => !isSummaryMessage(msg)); - } - async function offloadToBackend(resolvedBackend, messages, state) { - const filePath = getHistoryPath(state); - const filteredMessages = filterSummaryMessages(messages); - const newSection = `## Summarized at ${(/* @__PURE__ */ new Date()).toISOString()} - -${getBufferString(filteredMessages)} - -`; - const sectionBytes = new TextEncoder().encode(newSection); - try { - let existingBytes = null; - if (resolvedBackend.downloadFiles) - try { - const responses = await resolvedBackend.downloadFiles([filePath]); - if (responses.length > 0 && responses[0].content && !responses[0].error) - existingBytes = responses[0].content; - } catch {} - let result; - if (existingBytes && resolvedBackend.uploadFiles) { - const combined = new Uint8Array(existingBytes.byteLength + sectionBytes.byteLength); - combined.set(existingBytes, 0); - combined.set(sectionBytes, existingBytes.byteLength); - const uploadResults = await resolvedBackend.uploadFiles([[filePath, combined]]); - result = uploadResults[0].error ? { error: uploadResults[0].error } : { path: filePath }; - } else if (!existingBytes) - result = await resolvedBackend.write(filePath, newSection); - else { - const existingContent = new TextDecoder().decode(existingBytes); - result = await resolvedBackend.edit(filePath, existingContent, existingContent + newSection); + _addCheck(check3) { + return new ZodNumber4({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil2.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil2.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil2.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil2.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil2.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil2.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil2.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil2.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil2.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } - if (result.error) { - console.warn(`Failed to offload conversation history to ${filePath}: ${result.error}`); - return null; + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - return filePath; - } catch (e) { - console.warn(`Exception offloading conversation history to ${filePath}:`, e); - return null; + return max; } - } - async function createSummary(messages, chatModel) { - let messagesToSummarize = messages; - if (countTokensApproximately(messages) > trimTokensToSummarize) { - let kept = 0; - const trimmedMessages = []; - for (let i = messages.length - 1;i >= 0; i--) { - const msgTokens = countTokensApproximately([messages[i]]); - if (kept + msgTokens > trimTokensToSummarize) - break; - trimmedMessages.unshift(messages[i]); - kept += msgTokens; + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util3.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } } - messagesToSummarize = trimmedMessages; + return Number.isFinite(min) && Number.isFinite(max); } - const conversation = getBufferString(messagesToSummarize); - const prompt = summaryPrompt.replace("{conversation}", conversation); - const response = await chatModel.invoke([new HumanMessage({ content: prompt })]); - return typeof response.content === "string" ? response.content : JSON.stringify(response.content); - } - function buildSummaryMessage(summary, filePath) { - let content; - if (filePath) - content = context` - You are in the middle of a conversation that has been summarized. - - The full conversation history has been saved to ${filePath} should you need to refer back to it for details. - - A condensed summary follows: - - - ${summary} - - `; - else - content = `Here is a summary of the conversation to date: - -${summary}`; - return new HumanMessage({ - content, - additional_kwargs: { lc_source: "summarization" } + }; + ZodNumber4.create = (params) => { + return new ZodNumber4({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams2(params) }); - } - function getEffectiveMessages(messages, state) { - const event = state._summarizationEvent; - if (!event) - return messages; - const result = [event.summaryMessage]; - result.push(...messages.slice(event.cutoffIndex)); - return result; - } - async function summarizeMessages(messagesToSummarize, resolvedModel, state, previousCutoffIndex, cutoffIndex) { - const filePath = await offloadToBackend(await resolveBackend(backend, { state }), messagesToSummarize, state); - if (filePath === null) - console.warn(`[SummarizationMiddleware] Backend offload failed during summarization. Proceeding with summary generation.`); - return { - summaryMessage: buildSummaryMessage(await createSummary(messagesToSummarize, resolvedModel), filePath), - filePath, - stateCutoffIndex: previousCutoffIndex != null ? previousCutoffIndex + cutoffIndex - 1 : cutoffIndex - }; - } - function isContextOverflow(err) { - let cause = err; - for (;; ) { - if (!cause) - break; - if (ContextOverflowError.isInstance(cause)) - return true; - cause = typeof cause === "object" && "cause" in cause ? cause.cause : undefined; + }; + ZodBigInt4 = class ZodBigInt4 extends ZodType4 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; } - return false; - } - async function performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens) { - const cutoffIndex = determineCutoffIndex(truncatedMessages, maxInputTokens); - if (cutoffIndex <= 0) - return handler({ - ...request, - messages: truncatedMessages - }); - const messagesToSummarize = truncatedMessages.slice(0, cutoffIndex); - const preservedMessages = truncatedMessages.slice(cutoffIndex); - if (preservedMessages.length === 0 && maxInputTokens) { - const compact = compactToolResults(truncatedMessages, maxInputTokens, request.systemMessage, request.tools); - if (compact.modified) + _parse(input) { + if (this._def.coerce) { try { - return await handler({ - ...request, - messages: compact.messages - }); - } catch (err) { - if (!isContextOverflow(err)) - throw err; + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); } - } - const previousEvent = request.state._summarizationEvent; - const previousCutoffIndex = previousEvent != null ? previousEvent.cutoffIndex : undefined; - const { summaryMessage, filePath, stateCutoffIndex } = await summarizeMessages(messagesToSummarize, resolvedModel, request.state, previousCutoffIndex, cutoffIndex); - let modifiedMessages = [summaryMessage, ...preservedMessages]; - const modifiedTokens = countTotalTokens(modifiedMessages, request.systemMessage, request.tools); - let finalStateCutoffIndex = stateCutoffIndex; - let finalSummaryMessage = summaryMessage; - let finalFilePath = filePath; - try { - await handler({ - ...request, - messages: modifiedMessages - }); - } catch (err) { - if (!isContextOverflow(err)) - throw err; - if (maxInputTokens && modifiedTokens > 0) { - const observedRatio = maxInputTokens / modifiedTokens; - if (observedRatio > tokenEstimationMultiplier) - tokenEstimationMultiplier = observedRatio * 1.1; } - const reSumResult = await summarizeMessages([...messagesToSummarize, ...preservedMessages], resolvedModel, request.state, previousCutoffIndex, truncatedMessages.length); - finalSummaryMessage = reSumResult.summaryMessage; - finalFilePath = reSumResult.filePath; - finalStateCutoffIndex = reSumResult.stateCutoffIndex; - modifiedMessages = [reSumResult.summaryMessage]; - await handler({ - ...request, - messages: modifiedMessages + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus2; + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + type: "bigint", + minimum: check3.value, + inclusive: check3.inclusive, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "max") { + const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + type: "bigint", + maximum: check3.value, + inclusive: check3.inclusive, + message: check3.message + }); + status.dirty(); + } + } else if (check3.kind === "multipleOf") { + if (input.data % check3.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.not_multiple_of, + multipleOf: check3.value, + message: check3.message + }); + status.dirty(); + } + } else { + util3.assertNever(check3); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.bigint, + received: ctx.parsedType }); + return INVALID2; } - return new Command({ update: { - _summarizationEvent: { - cutoffIndex: finalStateCutoffIndex, - summaryMessage: finalSummaryMessage, - filePath: finalFilePath - }, - _summarizationSessionId: getSessionId(request.state) - } }); - } - return createMiddleware({ - name: "SummarizationMiddleware", - stateSchema: SummarizationStateSchema, - async wrapModelCall(request, handler) { - const effectiveMessages = getEffectiveMessages(request.messages ?? [], request.state); - if (effectiveMessages.length === 0) - return handler(request); - const resolvedModel = request.model ?? await getChatModel(); - const maxInputTokens = getMaxInputTokens(resolvedModel); - applyModelDefaults(resolvedModel); - const { messages: truncatedMessages } = truncateArgs(effectiveMessages, maxInputTokens, request.systemMessage, request.tools); - const totalTokens = countTotalTokens(truncatedMessages, request.systemMessage, request.tools); - if (!shouldSummarize(truncatedMessages, totalTokens, maxInputTokens)) - try { - return await handler({ - ...request, - messages: truncatedMessages - }); - } catch (err) { - if (!isContextOverflow(err)) - throw err; - if (maxInputTokens && totalTokens > 0) { - const observedRatio = maxInputTokens / totalTokens; - if (observedRatio > tokenEstimationMultiplier) - tokenEstimationMultiplier = observedRatio * 1.1; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil2.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil2.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil2.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil2.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt4({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil2.toString(message) } + ] + }); + } + _addCheck(check3) { + return new ZodBigInt4({ + ...this._def, + checks: [...this._def.checks, check3] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil2.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil2.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil2.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil2.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil2.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - return performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens); + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } - }); -} -function toolCallIdFromRuntime(runtime) { - return runtime.toolCall?.id ?? runtime.toolCallId ?? ""; -} -function asyncTasksReducer(existing, update) { - return { - ...existing || {}, - ...update || {} }; -} -function resolveTrackedTask(taskId, state) { - const tracked = (state.asyncTasks ?? {})[taskId.trim()]; - if (!tracked) - return `No tracked task found for taskId: '${taskId}'`; - return tracked; -} -function buildCheckResult(run2, threadId, threadValues) { - const checkResult = { - status: run2.status, - threadId + ZodBigInt4.create = (params) => { + return new ZodBigInt4({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams2(params) + }); }; - if (run2.status === "success") { - const messages = (Array.isArray(threadValues) ? {} : threadValues)?.messages ?? []; - if (messages.length > 0) { - const last = messages[messages.length - 1]; - const rawContent = typeof last === "object" && last !== null && "content" in last ? last.content : last; - checkResult.result = typeof rawContent === "string" ? rawContent : JSON.stringify(rawContent); - } else - checkResult.result = "Completed with no output messages."; - } else if (run2.status === "error") - checkResult.error = "The async subagent encountered an error."; - return checkResult; -} -function filterTasks(tasks, statusFilter) { - if (!statusFilter || statusFilter === "all") - return Object.values(tasks); - return Object.values(tasks).filter((task2) => task2.status === statusFilter); -} -async function fetchLiveTaskStatus(clients, task2) { - if (TERMINAL_STATUSES.has(task2.status)) - return task2.status; - try { - return (await clients.getClient(task2.agentName).runs.get(task2.threadId, task2.runId)).status; - } catch { - return task2.status; - } -} -function formatTaskEntry(task2, status) { - return `- taskId: ${task2.taskId} agent: ${task2.agentName} status: ${status}`; -} -function extractCallbackContext(runtime) { - const threadId = runtime.config?.configurable?.thread_id; - if (typeof threadId === "string" && threadId) - return { callbackThreadId: threadId }; - return {}; -} -function buildStartTool(agentMap, clients, toolDescription) { - return tool$1(async (input, runtime) => { - if (!(input.agentName in agentMap)) { - const allowed = Object.keys(agentMap).map((k) => `\`${k}\``).join(", "); - return `Unknown async subagent type \`${input.agentName}\`. Available types: ${allowed}`; + ZodBoolean4 = class ZodBoolean4 extends ZodType4 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.boolean, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); } - const spec = agentMap[input.agentName]; - const callbackContext = extractCallbackContext(runtime); - try { - const client2 = clients.getClient(input.agentName); - const thread = await client2.threads.create(); - const run2 = await client2.runs.create(thread.thread_id, spec.graphId, { input: { - messages: [{ - role: "user", - content: input.description - }], - ...callbackContext - } }); - const taskId = thread.thread_id; - const task2 = { - taskId, - agentName: input.agentName, - threadId: taskId, - runId: run2.run_id, - status: "running", - createdAt: (/* @__PURE__ */ new Date()).toISOString(), - description: input.description + }; + ZodBoolean4.create = (params) => { + return new ZodBoolean4({ + typeName: ZodFirstPartyTypeKind3.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams2(params) + }); + }; + ZodDate4 = class ZodDate4 extends ZodType4 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.date, + received: ctx2.parsedType + }); + return INVALID2; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode4.invalid_date + }); + return INVALID2; + } + const status = new ParseStatus2; + let ctx = undefined; + for (const check3 of this._def.checks) { + if (check3.kind === "min") { + if (input.data.getTime() < check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + message: check3.message, + inclusive: true, + exact: false, + minimum: check3.value, + type: "date" + }); + status.dirty(); + } + } else if (check3.kind === "max") { + if (input.data.getTime() > check3.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + message: check3.message, + inclusive: true, + exact: false, + maximum: check3.value, + type: "date" + }); + status.dirty(); + } + } else { + util3.assertNever(check3); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) }; - return new Command({ update: { - messages: [new ToolMessage({ - content: `Launched async subagent. taskId: ${taskId}`, - tool_call_id: toolCallIdFromRuntime(runtime) - })], - asyncTasks: { [taskId]: task2 } - } }); - } catch (e) { - return `Failed to launch async subagent '${input.agentName}': ${e}`; } - }, { - name: "start_async_task", - description: toolDescription, - schema: exports_external.object({ - description: exports_external.string().describe("A detailed description of the task for the async subagent to perform."), - agentName: exports_external.string().describe("The type of async subagent to use. Must be one of the available types listed in the tool description.") - }) - }); -} -function buildCheckTool(clients) { - return tool$1(async (input, runtime) => { - const task2 = resolveTrackedTask(input.taskId, runtime.state); - if (typeof task2 === "string") - return task2; - const client2 = clients.getClient(task2.agentName); - let run2; - try { - run2 = await client2.runs.get(task2.threadId, task2.runId); - } catch (e) { - return `Failed to get run status: ${e}`; + _addCheck(check3) { + return new ZodDate4({ + ...this._def, + checks: [...this._def.checks, check3] + }); } - let threadValues = {}; - if (run2.status === "success") - try { - threadValues = (await client2.threads.getState(task2.threadId)).values || {}; - } catch {} - const result = buildCheckResult(run2, task2.threadId, threadValues); - const updatedTask = { - taskId: task2.taskId, - agentName: task2.agentName, - threadId: task2.threadId, - runId: task2.runId, - status: result.status, - createdAt: task2.createdAt, - updatedAt: result.status !== task2.status ? (/* @__PURE__ */ new Date()).toISOString() : task2.updatedAt, - checkedAt: (/* @__PURE__ */ new Date()).toISOString() - }; - return new Command({ update: { - messages: [new ToolMessage({ - content: JSON.stringify(result), - tool_call_id: toolCallIdFromRuntime(runtime) - })], - asyncTasks: { [task2.taskId]: updatedTask } - } }); - }, { - name: "check_async_task", - description: "Check the status of an async subagent task. Returns the current status and, if complete, the result.", - schema: exports_external.object({ taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) - }); -} -function buildUpdateTool(agentMap, clients) { - return tool$1(async (input, runtime) => { - const tracked = resolveTrackedTask(input.taskId, runtime.state); - if (typeof tracked === "string") - return tracked; - const spec = agentMap[tracked.agentName]; - try { - const run2 = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, { - input: { messages: [{ - role: "user", - content: input.message - }] }, - multitaskStrategy: "interrupt" + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil2.toString(message) }); - const task2 = { - taskId: tracked.taskId, - agentName: tracked.agentName, - threadId: tracked.threadId, - runId: run2.run_id, - status: "running", - createdAt: tracked.createdAt, - description: input.message, - updatedAt: (/* @__PURE__ */ new Date()).toISOString(), - checkedAt: tracked.checkedAt - }; - return new Command({ update: { - messages: [new ToolMessage({ - content: `Updated async subagent. taskId: ${tracked.taskId}`, - tool_call_id: toolCallIdFromRuntime(runtime) - })], - asyncTasks: { [tracked.taskId]: task2 } - } }); - } catch (e) { - return `Failed to update async subagent: ${e}`; } - }, { - name: "update_async_task", - description: "send updated instructions to an async subagent. Interrupts the current run and starts a new one on the same thread so the subagent sees the full conversation history plus your new message. The taskId remains the same.", - schema: exports_external.object({ - taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."), - message: exports_external.string().describe("Follow-up instructions or context to send to the subagent") - }) - }); -} -function buildCancelTool(clients) { - return tool$1(async (input, runtime) => { - const tracked = resolveTrackedTask(input.taskId, runtime.state); - if (typeof tracked === "string") - return tracked; - const client2 = clients.getClient(tracked.agentName); - try { - await client2.runs.cancel(tracked.threadId, tracked.runId); - } catch (e) { - return `Failed to cancel run: ${e}`; + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil2.toString(message) + }); } - const updated = { - taskId: tracked.taskId, - agentName: tracked.agentName, - threadId: tracked.threadId, - runId: tracked.runId, - status: "cancelled", - createdAt: tracked.createdAt, - updatedAt: (/* @__PURE__ */ new Date()).toISOString(), - checkedAt: tracked.checkedAt - }; - return new Command({ update: { - messages: [new ToolMessage({ - content: `Cancelled async subagent task: ${tracked.taskId}`, - tool_call_id: toolCallIdFromRuntime(runtime) - })], - asyncTasks: { [tracked.taskId]: updated } - } }); - }, { - name: "cancel_async_task", - description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.", - schema: exports_external.object({ taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) - }); -} -function buildListTool(clients) { - return tool$1(async (input, runtime) => { - const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? undefined); - if (filtered.length === 0) - return "No async subagent tasks tracked"; - const statuses = await Promise.all(filtered.map((task2) => fetchLiveTaskStatus(clients, task2))); - const updatedTasks = {}; - const entries = []; - for (let idx = 0;idx < filtered.length; idx++) { - const task2 = filtered[idx]; - const status = statuses[idx]; - const taskEntry = formatTaskEntry(task2, status); - entries.push(taskEntry); - updatedTasks[task2.taskId] = { - taskId: task2.taskId, - agentName: task2.agentName, - threadId: task2.threadId, - runId: task2.runId, - status, - createdAt: task2.createdAt, - updatedAt: status !== task2.status ? (/* @__PURE__ */ new Date()).toISOString() : task2.updatedAt, - checkedAt: task2.checkedAt - }; + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; } - return new Command({ update: { - messages: [new ToolMessage({ - content: `${entries.length} tracked task(s): -${entries.join(` -`)}`, - tool_call_id: toolCallIdFromRuntime(runtime) - })], - asyncTasks: updatedTasks - } }); - }, { - name: "list_async_tasks", - description: "List tracked async subagent tasks with their current live statuses. Be default shows all tasks. Use `statusFilter` to narrow by status (e.g., 'running', 'success', 'error', 'cancelled'). Use `check_async_task` to get the full result of a specific completed task.", - schema: exports_external.object({ statusFilter: exports_external.string().nullish().describe("Filter tasks by status. One of: 'running', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") }) - }); -} -function isAsyncSubAgent(subAgent) { - return "graphId" in subAgent; -} -function createAsyncSubAgentMiddleware(options) { - const { asyncSubAgents, systemPrompt = ASYNC_TASK_SYSTEM_PROMPT } = options; - if (!asyncSubAgents || asyncSubAgents.length === 0) - throw new Error("At least one async subagent must be specified"); - const names = asyncSubAgents.map((a) => a.name); - const duplicates = names.filter((n3, i) => names.indexOf(n3) !== i); - if (duplicates.length > 0) - throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`); - const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a])); - const clients = new ClientCache(agentMap); - const agentsDescription = asyncSubAgents.map((a) => `- ${a.name}: ${a.description}`).join(` -`); - const tools = [ - buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)), - buildCheckTool(clients), - buildUpdateTool(agentMap, clients), - buildCancelTool(clients), - buildListTool(clients) - ]; - const fullSystemPrompt = systemPrompt ? `${systemPrompt} - -Available async subagent types: -${agentsDescription}` : null; - return createMiddleware({ - name: "asyncSubAgentMiddleware", - stateSchema: AsyncTaskStateSchema, - tools, - wrapModelCall: async (request, handler) => { - if (fullSystemPrompt !== null) - return handler({ - ...request, - systemMessage: request.systemMessage.concat(new SystemMessage({ content: fullSystemPrompt })) + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + ZodDate4.create = (params) => { + return new ZodDate4({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind3.ZodDate, + ...processCreateParams2(params) + }); + }; + ZodSymbol4 = class ZodSymbol4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.symbol, + received: ctx.parsedType }); - return handler(request); + return INVALID2; + } + return OK2(input.data); } - }); -} -function getObjectRecord(value) { - return value != null && typeof value === "object" ? value : undefined; -} -function getAssistantIdFromRecord(value) { - const assistantId = value?.assistant_id ?? value?.assistantId; - return typeof assistantId === "string" && assistantId.length > 0 ? assistantId : undefined; -} -function validateNamespace2(namespace) { - if (namespace.length === 0) - throw new Error("Namespace array must not be empty."); - for (let i = 0;i < namespace.length; i++) { - const component = namespace[i]; - if (typeof component !== "string") - throw new TypeError(`Namespace component at index ${i} must be a string, got ${typeof component}.`); - if (!component) - throw new Error(`Namespace component at index ${i} must not be empty.`); - if (!NAMESPACE_COMPONENT_RE.test(component)) - throw new Error(`Namespace component at index ${i} contains disallowed characters: "${component}". Only alphanumeric characters, hyphens, underscores, dots, @, +, colons, and tildes are allowed.`); - } - return namespace; -} -function getErrorMessage(error51) { - if (typeof error51 === "string") - return error51; - if (typeof error51 === "object" && error51 !== null && "message" in error51 && typeof error51.message === "string") - return error51.message; - return String(error51); -} -function splitLinesKeepEnds(content) { - const lines = []; - let lineStart = 0; - for (let index2 = 0;index2 < content.length; index2 += 1) - if (content[index2] === ` -`) { - lines.push(content.slice(lineStart, index2 + 1)); - lineStart = index2 + 1; + }; + ZodSymbol4.create = (params) => { + return new ZodSymbol4({ + typeName: ZodFirstPartyTypeKind3.ZodSymbol, + ...processCreateParams2(params) + }); + }; + ZodUndefined4 = class ZodUndefined4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.undefined, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); } - if (lineStart < content.length) - lines.push(content.slice(lineStart)); - return lines; -} -function sliceReadContent(content, offset, limit) { - if (!content || content.trim() === "") - return { content }; - const lines = splitLinesKeepEnds(content.replace(/\r\n/g, ` -`).replace(/\r/g, ` -`)); - const startIndex = offset; - const endIndex = Math.min(startIndex + limit, lines.length); - if (startIndex >= lines.length) - return { error: `Line offset ${offset} exceeds file length (${lines.length} lines)` }; - return { content: lines.slice(startIndex, endIndex).join("") }; -} -function isLangSmithNotFoundError2(error51) { - if (typeof error51 !== "object" || error51 === null) - return false; - const maybeError = error51; - return maybeError.name === "LangSmithNotFoundError" || maybeError.status === 404; -} -function isLangSmithError(error51) { - if (typeof error51 !== "object" || error51 === null) - return false; - const maybeError = error51; - return typeof maybeError.name === "string" && maybeError.name.startsWith("LangSmith") || typeof maybeError.status === "number"; -} -function getLangSmithStatus(error51) { - if (typeof error51 !== "object" || error51 === null) - return; - const maybeError = error51; - if (typeof maybeError.status === "number") - return maybeError.status; -} -function mapHubFileOperationError(error51) { - const status = getLangSmithStatus(error51); - if (status === 401 || status === 403) - return "permission_denied"; - if (status === 404) - return "file_not_found"; - return "invalid_path"; -} -function shellQuote(s) { - return "'" + s.replace(/'/g, "'\\''") + "'"; -} -function globToPathRegex(pattern) { - let regex2 = "^"; - let i = 0; - while (i < pattern.length) { - const c = pattern[i]; - if (c === "*") - if (i + 1 < pattern.length && pattern[i + 1] === "*") { - i += 2; - if (i < pattern.length && pattern[i] === "/") { - regex2 += "(.*/)?"; - i++; - } else - regex2 += ".*"; - } else { - regex2 += "[^/]*"; - i++; + }; + ZodUndefined4.create = (params) => { + return new ZodUndefined4({ + typeName: ZodFirstPartyTypeKind3.ZodUndefined, + ...processCreateParams2(params) + }); + }; + ZodNull4 = class ZodNull4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.null, + received: ctx.parsedType + }); + return INVALID2; } - else if (c === "?") { - regex2 += "[^/]"; - i++; - } else if (c === "[") { - let j = i + 1; - while (j < pattern.length && pattern[j] !== "]") - j++; - regex2 += pattern.slice(i, j + 1); - i = j + 1; - } else if (c === "." || c === "+" || c === "^" || c === "$" || c === "{" || c === "}" || c === "(" || c === ")" || c === "|" || c === "\\") { - regex2 += `\\${c}`; - i++; - } else { - regex2 += c; - i++; + return OK2(input.data); } - } - regex2 += "$"; - return new RegExp(regex2); -} -function parseStatLine(line) { - const firstTab = line.indexOf("\t"); - if (firstTab === -1) - return null; - const secondTab = line.indexOf("\t", firstTab + 1); - if (secondTab === -1) - return null; - const thirdTab = line.indexOf("\t", secondTab + 1); - if (thirdTab === -1) - return null; - const size = parseInt(line.slice(0, firstTab), 10); - const mtime = parseInt(line.slice(firstTab + 1, secondTab), 10); - const fileType = line.slice(secondTab + 1, thirdTab); - const fullPath = line.slice(thirdTab + 1); - if (isNaN(size) || isNaN(mtime)) - return null; - return { - size, - mtime, - isDir: fileType === "d" || fileType === "directory" || fileType.startsWith("d"), - fullPath }; -} -function buildLsCommand(dirPath) { - const quotedPath = shellQuote(dirPath); - const findBase = `find -L ${quotedPath} -maxdepth 1 -not -path ${quotedPath}`; - return `if find /dev/null -maxdepth 0 -printf '' 2>/dev/null; then ${findBase} -printf '%s\\t%T@\\t%y\\t%p\\n' 2>/dev/null; elif stat -c %s /dev/null >/dev/null 2>&1; then ${findBase} -exec sh -c '${STAT_C_SCRIPT}' _ {} +; else ${findBase} -exec stat -f '%z %m %Sp %N' {} + 2>/dev/null; fi || true`; -} -function buildFindCommand(searchPath) { - const quotedPath = shellQuote(searchPath); - const findBase = `find -L ${quotedPath} -not -path ${quotedPath}`; - return `if find /dev/null -maxdepth 0 -printf '' 2>/dev/null; then ${findBase} -printf '%s\\t%T@\\t%y\\t%p\\n' 2>/dev/null; elif stat -c %s /dev/null >/dev/null 2>&1; then ${findBase} -exec sh -c '${STAT_C_SCRIPT}' _ {} +; else ${findBase} -exec stat -f '%z %m %Sp %N' {} + 2>/dev/null; fi || true`; -} -function buildReadCommand(filePath, offset, limit) { - const quotedPath = shellQuote(filePath); - const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0; - const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.min(Math.floor(limit), 999999999) : 999999999; - const start = safeOffset + 1; - const end = safeOffset + safeLimit; - return [ - `if [ ! -f ${quotedPath} ]; then echo "Error: File not found"; exit 1; fi`, - `if [ ! -s ${quotedPath} ]; then echo "System reminder: File exists but has empty contents"; exit 0; fi`, - `awk 'NR >= ${start} && NR <= ${end} { printf "%6d\\t%s\\n", NR, $0 }' ${quotedPath}` - ].join("; "); -} -function buildGrepCommand(pattern, searchPath, globPattern) { - const patternEscaped = shellQuote(pattern); - const searchPathQuoted = shellQuote(searchPath); - if (globPattern) - return `find -L ${searchPathQuoted} -type f -name ${shellQuote(globPattern)} -exec grep -HnF -e ${patternEscaped} {} + 2>/dev/null || true`; - return `grep -rHnF -e ${patternEscaped} ${searchPathQuoted} 2>/dev/null || true`; -} -function createCacheBreakpointMiddleware() { - return createMiddleware({ - name: "CacheBreakpointMiddleware", - wrapModelCall(request, handler) { - const existingContent = request.systemMessage.content; - const existingBlocks = typeof existingContent === "string" ? [{ - type: "text", - text: existingContent - }] : Array.isArray(existingContent) ? [...existingContent] : []; - if (existingBlocks.length === 0) - return handler(request); - existingBlocks[existingBlocks.length - 1] = { - ...existingBlocks[existingBlocks.length - 1], - cache_control: { type: "ephemeral" } - }; - return handler({ - ...request, - systemMessage: new SystemMessage({ content: existingBlocks }) + ZodNull4.create = (params) => { + return new ZodNull4({ + typeName: ZodFirstPartyTypeKind3.ZodNull, + ...processCreateParams2(params) + }); + }; + ZodAny4 = class ZodAny4 extends ZodType4 { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK2(input.data); + } + }; + ZodAny4.create = (params) => { + return new ZodAny4({ + typeName: ZodFirstPartyTypeKind3.ZodAny, + ...processCreateParams2(params) + }); + }; + ZodUnknown4 = class ZodUnknown4 extends ZodType4 { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK2(input.data); + } + }; + ZodUnknown4.create = (params) => { + return new ZodUnknown4({ + typeName: ZodFirstPartyTypeKind3.ZodUnknown, + ...processCreateParams2(params) + }); + }; + ZodNever4 = class ZodNever4 extends ZodType4 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.never, + received: ctx.parsedType }); + return INVALID2; } - }); -} -function hasPrefix2(ns3, prefix) { - if (prefix.length > ns3.length) - return false; - for (let i = 0;i < prefix.length; i += 1) - if (ns3[i] !== prefix[i]) - return false; - return true; -} -function createSubagentTransformer(path3) { - return () => { - const subagentsLog = StreamChannel.local(); - const pendingByCallId = /* @__PURE__ */ new Map; - const pendingByNamespaceSegment = /* @__PURE__ */ new Map; - const latestValuesByNamespaceSegment = /* @__PURE__ */ new Map; - const subagentsByName = /* @__PURE__ */ new Map; - const toolsNodeToName = /* @__PURE__ */ new Map; - const childToolCalls = /* @__PURE__ */ new Map; - const activeMessages = /* @__PURE__ */ new Map; - function deletePendingSubagent(pending) { - pendingByCallId.delete(pending.callId); - for (const [segment, entry] of pendingByNamespaceSegment) - if (entry === pending) { - pendingByNamespaceSegment.delete(segment); - latestValuesByNamespaceSegment.delete(segment); + }; + ZodNever4.create = (params) => { + return new ZodNever4({ + typeName: ZodFirstPartyTypeKind3.ZodNever, + ...processCreateParams2(params) + }); + }; + ZodVoid4 = class ZodVoid4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.void, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodVoid4.create = (params) => { + return new ZodVoid4({ + typeName: ZodFirstPartyTypeKind3.ZodVoid, + ...processCreateParams2(params) + }); + }; + ZodArray4 = class ZodArray4 extends ZodType4 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType2.array) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.array, + received: ctx.parsedType + }); + return INVALID2; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext2(ctx, { + code: tooBig ? ZodIssueCode4.too_big : ZodIssueCode4.too_small, + minimum: tooSmall ? def.exactLength.value : undefined, + maximum: tooBig ? def.exactLength.value : undefined, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus2.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); + }); + return ParseStatus2.mergeArray(status, result); } - function subagentSegment(ns3) { - return ns3.length === path3.length + 1 ? ns3[path3.length] : undefined; + get element() { + return this._def.type; } - function getOrCreateSubagentLogs(name) { - let logs = subagentsByName.get(name); - if (!logs) { - logs = { - messagesLog: StreamChannel.local(), - toolCallsLog: StreamChannel.local(), - nestedSubagentsLog: StreamChannel.local() - }; - subagentsByName.set(name, logs); - } - return logs; + min(minLength, message) { + return new ZodArray4({ + ...this._def, + minLength: { value: minLength, message: errorUtil2.toString(message) } + }); } - return { - __native: true, - init: () => ({ subagents: subagentsLog }), - process(event) { - if (!hasPrefix2(event.params.namespace, path3)) - return true; - const ns3 = event.params.namespace; - const depth = ns3.length - path3.length; - if (depth <= 1 && event.method === "tools") { - const data = event.params.data; - const toolCallId = data.tool_call_id; - const toolName = data.tool_name; - if (toolName === "task" && data.event === "tool-started") { - const rawInput = data.input; - const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {}; - const subagentName = input.subagent_type ?? "unknown"; - const taskDescription = input.description ?? ""; - let resolveTaskInput; - let resolveOutput; - let rejectOutput; - const taskInput = new Promise((res) => { - resolveTaskInput = res; + max(maxLength, message) { + return new ZodArray4({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil2.toString(message) } + }); + } + length(len, message) { + return new ZodArray4({ + ...this._def, + exactLength: { value: len, message: errorUtil2.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodArray4.create = (schema, params) => { + return new ZodArray4({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind3.ZodArray, + ...processCreateParams2(params) + }); + }; + ZodObject4 = class ZodObject4 extends ZodType4 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util3.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.object, + received: ctx2.parsedType + }); + return INVALID2; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever4 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever4) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } }); - const output = new Promise((res, rej) => { - resolveOutput = res; - rejectOutput = rej; + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.unrecognized_keys, + keys: extraKeys }); - const pending2 = { - name: subagentName, - callId: toolCallId, - resolveTaskInput, - resolveOutput, - rejectOutput - }; - if (toolCallId) - pendingByCallId.set(toolCallId, pending2); - resolveTaskInput(taskDescription); - if (depth === 1) { - toolsNodeToName.set(ns3[path3.length], subagentName); - pendingByNamespaceSegment.set(ns3[path3.length], pending2); - } - if (toolCallId) { - const taskSegment = `tools:${toolCallId}`; - toolsNodeToName.set(taskSegment, subagentName); - pendingByNamespaceSegment.set(taskSegment, pending2); - } - const logs = getOrCreateSubagentLogs(subagentName); - subagentsLog.push({ - name: subagentName, - taskInput, - output, - messages: logs.messagesLog, - toolCalls: logs.toolCallsLog, - subagents: logs.nestedSubagentsLog + status.dirty(); + } + } else if (unknownKeys === "strip") {} else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet }); } - if (toolName === "task" && toolCallId) { - const pending2 = pendingByCallId.get(toolCallId); - if (pending2) { - if (data.event === "tool-finished") { - pending2.resolveOutput(data.output); - deletePendingSubagent(pending2); - } else if (data.event === "tool-error") { - const message = data.message ?? "unknown error"; - pending2.rejectOutput(new Error(message)); - deletePendingSubagent(pending2); - } - } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus2.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus2.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil2.errToObj; + return new ZodObject4({ + ...this._def, + unknownKeys: "strict", + ...message !== undefined ? { + errorMap: (issue3, ctx) => { + const defaultError = this._def.errorMap?.(issue3, ctx).message ?? ctx.defaultError; + if (issue3.code === "unrecognized_keys") + return { + message: errorUtil2.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; } + } : {} + }); + } + strip() { + return new ZodObject4({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new ZodObject4({ + ...this._def, + unknownKeys: "passthrough" + }); + } + extend(augmentation) { + return new ZodObject4({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + merge(merging) { + const merged = new ZodObject4({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind3.ZodObject + }); + return merged; + } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + catchall(index2) { + return new ZodObject4({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util3.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; } - const segment = subagentSegment(ns3); - const pending = segment ? pendingByNamespaceSegment.get(segment) : undefined; - if (pending) { - if (event.method === "values") - latestValuesByNamespaceSegment.set(segment, event.params.data); - else if (event.method === "lifecycle") { - const data = event.params.data; - if (data.event === "completed" || data.event === "interrupted") { - pending.resolveOutput(latestValuesByNamespaceSegment.get(segment)); - deletePendingSubagent(pending); - } else if (data.event === "failed") { - pending.rejectOutput(/* @__PURE__ */ new Error(`Subagent ${pending.name} failed`)); - deletePendingSubagent(pending); - } - } + } + return new ZodObject4({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util3.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; } - if (depth >= 2) { - const parentSegment = ns3[path3.length]; - const subagentName = toolsNodeToName.get(parentSegment); - const logs = subagentName ? subagentsByName.get(subagentName) : undefined; - if (logs && subagentName) { - if (event.method === "tools") { - const data = event.params.data; - const toolCallId = data.tool_call_id; - const toolName = data.tool_name; - if (data.event === "tool-started") { - let resolveOutput; - let rejectOutput; - let resolveStatus; - let resolveError; - const output = new Promise((res, rej) => { - resolveOutput = res; - rejectOutput = rej; - }); - const status = new Promise((res) => { - resolveStatus = res; - }); - const error51 = new Promise((res) => { - resolveError = res; - }); - childToolCalls.set(toolCallId, { - resolveOutput, - rejectOutput, - resolveStatus, - resolveError - }); - const rawInput = data.input; - const parsedInput = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput; - logs.toolCallsLog.push({ - name: toolName ?? "unknown", - callId: toolCallId, - input: parsedInput, - output, - status, - error: error51 - }); - } - const pending2 = toolCallId ? childToolCalls.get(toolCallId) : undefined; - if (pending2) { - if (data.event === "tool-finished") { - pending2.resolveOutput(data.output); - pending2.resolveStatus("finished"); - pending2.resolveError(undefined); - childToolCalls.delete(toolCallId); - } else if (data.event === "tool-error") { - const message = data.message ?? "unknown error"; - pending2.rejectOutput(new Error(message)); - pending2.resolveStatus("error"); - pending2.resolveError(message); - childToolCalls.delete(toolCallId); - } - } - } - if (event.method === "messages") { - const data = event.params.data; - if (data.event === "message-start") { - const eventsLog = StreamChannel.local(); - const stream2 = new ChatModelStream(eventsLog); - eventsLog.push(data); - activeMessages.set(subagentName, { - stream: stream2, - eventsLog - }); - logs.messagesLog.push(stream2); - } else if (data.event === "message-finish") { - const active = activeMessages.get(subagentName); - if (active) { - active.eventsLog.push(data); - active.eventsLog.close(); - activeMessages.delete(subagentName); - } - } else - activeMessages.get(subagentName)?.eventsLog.push(data); - } + } + return new ZodObject4({ + ...this._def, + shape: () => shape + }); + } + deepPartial() { + return deepPartialify2(this); + } + partial(mask) { + const newShape = {}; + for (const key of util3.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject4({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util3.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional4) { + newField = newField._def.innerType; } + newShape[key] = newField; } - return true; - }, - finalize() { - for (const pending of pendingByCallId.values()) - pending.resolveOutput(undefined); - pendingByCallId.clear(); - for (const pending of childToolCalls.values()) { - pending.resolveOutput(undefined); - pending.resolveStatus("finished"); - pending.resolveError(undefined); + } + return new ZodObject4({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum2(util3.objectKeys(this.shape)); + } + }; + ZodObject4.create = (shape, params) => { + return new ZodObject4({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever4.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodObject4.strictCreate = (shape, params) => { + return new ZodObject4({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever4.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodObject4.lazycreate = (shape, params) => { + return new ZodObject4({ + shape, + unknownKeys: "strip", + catchall: ZodNever4.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodUnion4 = class ZodUnion4 extends ZodType4 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } } - childToolCalls.clear(); - for (const active of activeMessages.values()) - active.eventsLog.fail(/* @__PURE__ */ new Error("run finalized before message completed")); - activeMessages.clear(); - subagentsLog.close(); - for (const logs of subagentsByName.values()) { - logs.toolCallsLog.close(); - logs.messagesLog.close(); - logs.nestedSubagentsLog.close(); + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } } - }, - fail(err) { - for (const pending of pendingByCallId.values()) - pending.rejectOutput(err); - pendingByCallId.clear(); - for (const pending of childToolCalls.values()) { - pending.rejectOutput(err); - pending.resolveStatus("error"); - pending.resolveError(err instanceof Error ? err.message : String(err)); + const unionErrors = results.map((result) => new ZodError5(result.ctx.common.issues)); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_union, + unionErrors + }); + return INVALID2; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } } - childToolCalls.clear(); - for (const active of activeMessages.values()) - active.eventsLog.fail(err); - activeMessages.clear(); - subagentsLog.fail(err); - for (const logs of subagentsByName.values()) { - logs.toolCallsLog.fail(err); - logs.messagesLog.fail(err); - logs.nestedSubagentsLog.fail(err); + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; } + const unionErrors = issues.map((issues2) => new ZodError5(issues2)); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_union, + unionErrors + }); + return INVALID2; } - }; + } + get options() { + return this._def.options; + } }; -} -function validateProfileKey(key) { - const trimmed = key.trim(); - if (!trimmed) - throw new Error("Profile key must be a non-empty string"); - if (trimmed.split(":").length > 2) - throw new Error(`Profile key "${trimmed}" has more than one ":"; expected "provider" or "provider:model"`); - if (trimmed.includes(":")) { - const [provider, model] = trimmed.split(":"); - if (!provider.trim() || !model.trim()) - throw new Error(`Profile key "${trimmed}" has an empty provider or model half; expected "provider:model"`); - } - return trimmed; -} -function isHarnessProfile(value) { - return value.excludedTools != null && typeof value.excludedTools.has === "function" && !Array.isArray(value.excludedTools); -} -function resolveMiddleware(middleware) { - if (typeof middleware === "function") - return middleware(); - return middleware; -} -function validateExcludedMiddlewareName(name) { - if (!name || !name.trim()) - throw new Error("excludedMiddleware entries must be non-empty, non-whitespace strings."); - if (name.includes(":")) - throw new Error(`excludedMiddleware entries must be plain middleware names; class-path syntax is not supported, got "${name}".`); - if (name.startsWith("_")) - throw new Error(`excludedMiddleware entry "${name}" cannot start with "_" (underscore-prefixed names refer to private middleware not part of the public exclusion surface).`); - if (REQUIRED_MIDDLEWARE_NAMES.has(name)) - throw new Error(`Cannot exclude required middleware "${name}" — it provides essential agent capabilities that the runtime depends on.`); -} -function createHarnessProfile(options = {}) { - for (const name of options.excludedMiddleware ?? []) - validateExcludedMiddlewareName(name); - const toolDescriptionOverrides = Object.freeze(Object.assign(Object.create(null), options.toolDescriptionOverrides)); - const generalPurposeSubagent = options.generalPurposeSubagent ? Object.freeze({ ...options.generalPurposeSubagent }) : undefined; - const profile = { - baseSystemPrompt: options.baseSystemPrompt, - systemPromptSuffix: options.systemPromptSuffix, - toolDescriptionOverrides, - excludedTools: new Set(options.excludedTools), - excludedMiddleware: new Set(options.excludedMiddleware), - extraMiddleware: options.extraMiddleware ?? [], - generalPurposeSubagent + ZodUnion4.create = (types3, params) => { + return new ZodUnion4({ + options: types3, + typeName: ZodFirstPartyTypeKind3.ZodUnion, + ...processCreateParams2(params) + }); }; - return Object.freeze(profile); -} -function rejectPoisonedKeys(value, path3 = "") { - if (typeof value !== "object" || value === null || Array.isArray(value)) - return; - for (const key of Object.keys(value)) { - if (POISONED_KEYS.has(key)) - throw new Error(`Rejected dangerous key "${key}" at ${path3 || "root"} in harness profile config.`); - rejectPoisonedKeys(value[key], path3 ? `${path3}.${key}` : key); - } -} -function parseHarnessProfileConfig(data) { - rejectPoisonedKeys(data); - return createHarnessProfile(harnessProfileConfigSchema.parse(data)); -} -function serializeProfile(profile) { - if (resolveMiddleware(profile.extraMiddleware).length > 0) - throw new Error("Cannot serialize a HarnessProfile with non-empty extraMiddleware — middleware instances are runtime-only and have no JSON representation."); - const result = {}; - if (profile.baseSystemPrompt !== undefined) - result.baseSystemPrompt = profile.baseSystemPrompt; - if (profile.systemPromptSuffix !== undefined) - result.systemPromptSuffix = profile.systemPromptSuffix; - if (Object.keys(profile.toolDescriptionOverrides).length > 0) - result.toolDescriptionOverrides = { ...profile.toolDescriptionOverrides }; - if (profile.excludedTools.size > 0) - result.excludedTools = [...profile.excludedTools]; - if (profile.excludedMiddleware.size > 0) - result.excludedMiddleware = [...profile.excludedMiddleware]; - if (profile.generalPurposeSubagent !== undefined) { - const gp = {}; - if (profile.generalPurposeSubagent.enabled !== undefined) - gp.enabled = profile.generalPurposeSubagent.enabled; - if (profile.generalPurposeSubagent.description !== undefined) - gp.description = profile.generalPurposeSubagent.description; - if (profile.generalPurposeSubagent.systemPrompt !== undefined) - gp.systemPrompt = profile.generalPurposeSubagent.systemPrompt; - if (Object.keys(gp).length > 0) - result.generalPurposeSubagent = gp; - } - return result; -} -function mergeMiddleware(base, override) { - const baseArr = resolveMiddleware(base); - const overrideArr = resolveMiddleware(override); - if (baseArr.length === 0) - return override; - if (overrideArr.length === 0) - return base; - return () => { - const baseSeq = resolveMiddleware(base); - const overrideSeq = resolveMiddleware(override); - const overrideByName = new Map(overrideSeq.map((m) => [m.name, m])); - const merged = []; - const replaced = /* @__PURE__ */ new Set; - for (const entry of baseSeq) { - const replacement = overrideByName.get(entry.name); - if (replacement) { - if (!replaced.has(entry.name)) { - merged.push(replacement); - replaced.add(entry.name); - } - } else - merged.push(entry); - } - for (const entry of overrideSeq) - if (!replaced.has(entry.name)) - merged.push(entry); - return merged; - }; -} -function mergeGeneralPurposeSubagentConfigs(base, override) { - if (base === undefined) - return override; - if (override === undefined) - return base; - return { - enabled: override.enabled ?? base.enabled, - description: override.description ?? base.description, - systemPrompt: override.systemPrompt ?? base.systemPrompt - }; -} -function mergeProfiles(base, override) { - return createHarnessProfile({ - baseSystemPrompt: override.baseSystemPrompt ?? base.baseSystemPrompt, - systemPromptSuffix: override.systemPromptSuffix ?? base.systemPromptSuffix, - toolDescriptionOverrides: { - ...base.toolDescriptionOverrides, - ...override.toolDescriptionOverrides - }, - excludedTools: [...base.excludedTools, ...override.excludedTools], - excludedMiddleware: [...base.excludedMiddleware, ...override.excludedMiddleware], - extraMiddleware: mergeMiddleware(base.extraMiddleware, override.extraMiddleware), - generalPurposeSubagent: mergeGeneralPurposeSubagentConfigs(base.generalPurposeSubagent, override.generalPurposeSubagent) - }); -} -function register$3() { - registerHarnessProfileImpl("anthropic:claude-opus-4-7", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$3 })); -} -function register$2() { - registerHarnessProfileImpl("anthropic:claude-sonnet-4-6", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$2 })); -} -function register$1() { - registerHarnessProfileImpl("anthropic:claude-haiku-4-5", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$1 })); -} -function register() { - const profile = createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX }); - for (const spec of CODEX_MODEL_SPECS) - registerHarnessProfileImpl(spec, profile); -} -function loadBuiltinProfiles() { - register$3(); - register$2(); - register$1(); - register(); - snapshotBuiltinKeys(); -} -function getHarnessProfileRegistry() { - const global2 = globalThis; - if (global2[PROFILE_REGISTRY_KEY] == null) - global2[PROFILE_REGISTRY_KEY] = { - profiles: /* @__PURE__ */ new Map, - builtinKeys: /* @__PURE__ */ new Set, - builtinsLoaded: false - }; - return global2[PROFILE_REGISTRY_KEY]; -} -function ensureBuiltinsLoaded() { - const registry3 = getHarnessProfileRegistry(); - if (registry3.builtinsLoaded) - return; - registry3.builtinsLoaded = true; - loadBuiltinProfiles(); -} -function snapshotBuiltinKeys() { - const registry3 = getHarnessProfileRegistry(); - registry3.builtinKeys = new Set(registry3.profiles.keys()); -} -function registerHarnessProfileImpl(key, profile) { - key = validateProfileKey(key); - const { profiles } = getHarnessProfileRegistry(); - const existing = profiles.get(key); - if (existing !== undefined) - profiles.set(key, mergeProfiles(existing, profile)); - else - profiles.set(key, profile); -} -function registerHarnessProfile(key, profile) { - ensureBuiltinsLoaded(); - registerHarnessProfileImpl(key, isHarnessProfile(profile) ? profile : createHarnessProfile(profile)); -} -function getHarnessProfile(spec) { - if (spec.split(":").length > 2) - return; - const colonIdx = spec.indexOf(":"); - const hasColon = colonIdx !== -1; - const provider = hasColon ? spec.slice(0, colonIdx) : undefined; - const model = hasColon ? spec.slice(colonIdx + 1) : undefined; - if (hasColon && (!provider || !model)) - return; - ensureBuiltinsLoaded(); - const { profiles } = getHarnessProfileRegistry(); - const exact = profiles.get(spec); - const base = provider ? profiles.get(provider) : undefined; - if (exact !== undefined && base !== undefined) - return mergeProfiles(base, exact); - return exact ?? base; -} -function resolveHarnessProfile(opts = {}) { - const { spec, providerHint, identifierHint } = opts; - if (spec !== undefined) - return getHarnessProfile(spec) ?? EMPTY_HARNESS_PROFILE; - if (providerHint && identifierHint && !identifierHint.includes(":")) { - const profile = getHarnessProfile(`${providerHint}:${identifierHint}`); - if (profile) - return profile; - } - if (identifierHint && identifierHint.includes(":")) { - const profile = getHarnessProfile(identifierHint); - if (profile) - return profile; - } - if (providerHint) { - const profile = getHarnessProfile(providerHint); - if (profile) - return profile; - } - return EMPTY_HARNESS_PROFILE; -} -function applyProfilePrompt(profile, basePrompt) { - const prompt = profile.baseSystemPrompt !== undefined ? profile.baseSystemPrompt : basePrompt; - if (profile.systemPromptSuffix !== undefined) - return `${prompt} - -${profile.systemPromptSuffix}`; - return prompt; -} -function isAnthropicModel(model) { - if (typeof model === "string") { - if (model.includes(":")) - return model.split(":")[0] === "anthropic"; - return model.startsWith("claude"); - } - if (model.getName() === "ConfigurableModel") - return model._defaultConfig?.modelProvider === "anthropic"; - return model.getName() === "ChatAnthropic"; -} -function getModelProvider(model) { - if (model.getName() === "ConfigurableModel") - return model._defaultConfig?.modelProvider; - return { - ChatAnthropic: "anthropic", - ChatOpenAI: "openai", - ChatGoogleGenerativeAI: "google" - }[model.getName()]; -} -function getModelIdentifier(model) { - return (model.getName() === "ConfigurableModel" ? model._defaultConfig : undefined)?.model ?? model.model_name ?? model.modelName ?? undefined; -} -function createDeepAgent(params = {}) { - const { model = "anthropic:claude-sonnet-4-6", tools = [], systemPrompt, middleware: customMiddleware = [], subagents = [], responseFormat, contextSchema: contextSchema7, checkpointer, store, backend = (config2) => new StateBackend(config2), interruptOn, name, memory, skills, permissions = [], streamTransformers = [] } = params; - const collidingTools = tools.map((t) => t.name).filter((n3) => typeof n3 === "string" && BUILTIN_TOOL_NAMES.has(n3)); - if (collidingTools.length > 0) - throw new ConfigurationError(`Tool name(s) [${collidingTools.join(", ")}] conflict with built-in tools. Rename your custom tools to avoid this.`, "TOOL_NAME_COLLISION"); - const harnessProfile = typeof model === "string" ? resolveHarnessProfile({ spec: model }) : resolveHarnessProfile({ - providerHint: getModelProvider(model), - identifierHint: getModelIdentifier(model) - }); - const toolOverrides = harnessProfile.toolDescriptionOverrides; - const effectiveTools = Object.keys(toolOverrides).length > 0 ? tools.map((t) => (t.name in toolOverrides) ? Object.assign(Object.create(Object.getPrototypeOf(t)), t, { description: toolOverrides[t.name] }) : t) : tools; - const anthropicModel = isAnthropicModel(model); - const cacheMiddleware = anthropicModel ? [anthropicPromptCachingMiddleware({ - unsupportedModelBehavior: "ignore", - minMessagesToCache: 1 - }), createCacheBreakpointMiddleware()] : []; - const normalizeSubagentSpec = (input) => { - const effectivePermissions = input.permissions ?? permissions; - const subagentMiddleware2 = [ - todoListMiddleware(), - createFilesystemMiddleware({ - backend, - permissions: effectivePermissions - }), - createSummarizationMiddleware({ backend }), - createPatchToolCallsMiddleware(), - ...input.skills != null && input.skills.length > 0 ? [createSkillsMiddleware({ - backend, - sources: input.skills - })] : [], - ...input.middleware ?? [], - ...cacheMiddleware - ]; - return { - ...input, - tools: input.tools ?? [], - middleware: subagentMiddleware2 - }; - }; - const allSubagents = subagents; - const asyncSubAgents = allSubagents.filter((item) => isAsyncSubAgent(item)); - const inlineSubagents = allSubagents.filter((item) => !isAsyncSubAgent(item)).map((item) => ("runnable" in item) ? item : normalizeSubagentSpec(item)); - const gpConfig = harnessProfile.generalPurposeSubagent; - if (!(gpConfig?.enabled === false) && !inlineSubagents.some((item) => item.name === GENERAL_PURPOSE_SUBAGENT["name"])) { - const gpSystemPrompt = gpConfig?.systemPrompt ?? applyProfilePrompt(harnessProfile, GENERAL_PURPOSE_SUBAGENT.systemPrompt); - const generalPurposeSpec = normalizeSubagentSpec({ - ...GENERAL_PURPOSE_SUBAGENT, - description: gpConfig?.description ?? GENERAL_PURPOSE_SUBAGENT.description, - systemPrompt: gpSystemPrompt, - model, - skills, - tools: effectiveTools - }); - inlineSubagents.unshift(generalPurposeSpec); - } - const skillsMiddleware = skills != null && skills.length > 0 ? [createSkillsMiddleware({ - backend, - sources: skills - })] : []; - const [todoMiddleware, fsMiddleware, subagentMiddleware, summarizationMiddleware2, patchToolCallsMiddleware] = [ - todoListMiddleware(), - createFilesystemMiddleware({ - backend, - permissions - }), - createSubAgentMiddleware({ - defaultModel: model, - defaultTools: effectiveTools, - defaultInterruptOn: interruptOn, - subagents: inlineSubagents, - generalPurposeAgent: false - }), - createSummarizationMiddleware({ backend }), - createPatchToolCallsMiddleware() - ]; - const middleware = [ - todoMiddleware, - ...skillsMiddleware, - fsMiddleware, - subagentMiddleware, - summarizationMiddleware2, - patchToolCallsMiddleware, - ...asyncSubAgents.length > 0 ? [createAsyncSubAgentMiddleware({ asyncSubAgents })] : [], - ...customMiddleware, - ...cacheMiddleware, - ...memory && memory.length > 0 ? [createMemoryMiddleware({ - backend, - sources: memory, - addCacheControl: anthropicModel - })] : [], - ...interruptOn ? [humanInTheLoopMiddleware({ interruptOn })] : [] - ]; - const profileMiddleware = resolveMiddleware(harnessProfile.extraMiddleware); - if (profileMiddleware.length > 0) { - const cacheIdx = middleware.findIndex((m) => m.name === "AnthropicPromptCachingMiddleware"); - if (cacheIdx !== -1) - middleware.splice(cacheIdx, 0, ...profileMiddleware); - else - middleware.push(...profileMiddleware); - } - if (harnessProfile.excludedMiddleware.size > 0) { - const excluded = harnessProfile.excludedMiddleware; - const filtered = middleware.filter((m) => !excluded.has(m.name)); - middleware.length = 0; - middleware.push(...filtered); - } - if (harnessProfile.excludedTools.size > 0) { - const excludedTools = harnessProfile.excludedTools; - middleware.push(createMiddleware({ - name: "_ToolExclusionMiddleware", - wrapModelCall: async (request, handler) => { - return handler({ - ...request, - tools: request.tools?.filter((t) => !excludedTools.has(t.name)) + ZodDiscriminatedUnion4 = class ZodDiscriminatedUnion4 extends ZodType4 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.object) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.object, + received: ctx.parsedType }); + return INVALID2; } - })); - } - const effectiveBasePrompt = applyProfilePrompt(harnessProfile, BASE_AGENT_PROMPT); - return createAgent({ - model, - systemPrompt: typeof systemPrompt === "string" ? new SystemMessage({ contentBlocks: [{ - type: "text", - text: systemPrompt - }, { - type: "text", - text: effectiveBasePrompt - }] }) : SystemMessage.isInstance(systemPrompt) ? new SystemMessage({ contentBlocks: [...systemPrompt.contentBlocks, { - type: "text", - text: effectiveBasePrompt - }] }) : new SystemMessage({ contentBlocks: [{ - type: "text", - text: effectiveBasePrompt - }] }), - tools: effectiveTools, - middleware, - ...responseFormat !== null && { responseFormat }, - contextSchema: contextSchema7, - checkpointer, - store, - name, - streamTransformers: [createSubagentTransformer([]), ...streamTransformers] - }).withConfig({ - recursionLimit: 1e4, - metadata: { - ls_integration: "deepagents", - lc_agent_name: name - } - }); -} -function findProjectRoot(startPath) { - let current = path$1.resolve(startPath || process.cwd()); - while (current !== path$1.dirname(current)) { - const gitDir = path$1.join(current, ".git"); - if (fs$1.existsSync(gitDir)) - return current; - current = path$1.dirname(current); - } - const rootGitDir = path$1.join(current, ".git"); - if (fs$1.existsSync(rootGitDir)) - return current; - return null; -} -function isValidAgentName(agentName) { - if (!agentName || !agentName.trim()) - return false; - return /^[a-zA-Z0-9_\-\s]+$/.test(agentName); -} -function createSettings(options = {}) { - const projectRoot = findProjectRoot(options.startPath); - const userDeepagentsDir = path$1.join(os.homedir(), ".deepagents"); - return { - projectRoot, - userDeepagentsDir, - hasProject: projectRoot !== null, - getAgentDir(agentName) { - if (!isValidAgentName(agentName)) - throw new Error(`Invalid agent name: ${JSON.stringify(agentName)}. Agent names can only contain letters, numbers, hyphens, underscores, and spaces.`); - return path$1.join(userDeepagentsDir, agentName); - }, - ensureAgentDir(agentName) { - const agentDir = this.getAgentDir(agentName); - fs$1.mkdirSync(agentDir, { recursive: true }); - return agentDir; - }, - getUserAgentMdPath(agentName) { - return path$1.join(this.getAgentDir(agentName), "agent.md"); - }, - getProjectAgentMdPath() { - if (!projectRoot) - return null; - return path$1.join(projectRoot, ".deepagents", "agent.md"); - }, - getUserSkillsDir(agentName) { - return path$1.join(this.getAgentDir(agentName), "skills"); - }, - ensureUserSkillsDir(agentName) { - const skillsDir = this.getUserSkillsDir(agentName); - fs$1.mkdirSync(skillsDir, { recursive: true }); - return skillsDir; - }, - getProjectSkillsDir() { - if (!projectRoot) - return null; - return path$1.join(projectRoot, ".deepagents", "skills"); - }, - ensureProjectSkillsDir() { - const skillsDir = this.getProjectSkillsDir(); - if (!skillsDir) - return null; - fs$1.mkdirSync(skillsDir, { recursive: true }); - return skillsDir; - }, - ensureProjectDeepagentsDir() { - if (!projectRoot) - return null; - const deepagentsDir = path$1.join(projectRoot, ".deepagents"); - fs$1.mkdirSync(deepagentsDir, { recursive: true }); - return deepagentsDir; - } - }; -} -function createAgentMemoryMiddleware(options) { - const { settings, assistantId, systemPromptTemplate } = options; - const agentDir = settings.getAgentDir(assistantId); - const agentDirDisplay = `~/.deepagents/${assistantId}`; - const agentDirAbsolute = agentDir; - const projectRoot = settings.projectRoot; - const projectMemoryInfo = projectRoot ? `\`${projectRoot}\` (detected)` : "None (not in a git project)"; - const projectDeepagentsDir = projectRoot ? `${projectRoot}/.deepagents` : "[project-root]/.deepagents (not in a project)"; - const template = systemPromptTemplate || DEFAULT_MEMORY_TEMPLATE; - return createMiddleware({ - name: "AgentMemoryMiddleware", - stateSchema: AgentMemoryStateSchema, - beforeAgent(state) { - const result = {}; - if (!("userMemory" in state)) { - const userPath = settings.getUserAgentMdPath(assistantId); - if (fs$1.existsSync(userPath)) - try { - result.userMemory = fs$1.readFileSync(userPath, "utf-8"); - } catch {} + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID2; } - if (!("projectMemory" in state)) { - const projectPath = settings.getProjectAgentMdPath(); - if (projectPath && fs$1.existsSync(projectPath)) - try { - result.projectMemory = fs$1.readFileSync(projectPath, "utf-8"); - } catch {} + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); } - return Object.keys(result).length > 0 ? result : undefined; - }, - wrapModelCall(request, handler) { - const userMemory = request.state?.userMemory; - const projectMemory = request.state?.projectMemory; - const baseSystemPrompt = request.systemPrompt || ""; - const memorySection = template.replace("{user_memory}", userMemory || "(No user agent.md)").replace("{project_memory}", projectMemory || "(No project agent.md)"); - const memoryDocs = LONGTERM_MEMORY_SYSTEM_PROMPT.replaceAll("{agent_dir_absolute}", agentDirAbsolute).replaceAll("{agent_dir_display}", agentDirDisplay).replaceAll("{project_memory_info}", projectMemoryInfo).replaceAll("{project_deepagents_dir}", projectDeepagentsDir); - let systemPrompt = memorySection; - if (baseSystemPrompt) - systemPrompt += ` - -` + baseSystemPrompt; - systemPrompt += ` - -` + memoryDocs; - return handler({ - ...request, - systemPrompt - }); - } - }); -} -function isSafePath(targetPath, baseDir) { - try { - const resolvedPath = fs$1.realpathSync(targetPath); - const resolvedBase = fs$1.realpathSync(baseDir); - return resolvedPath.startsWith(resolvedBase + path$1.sep) || resolvedPath === resolvedBase; - } catch { - return false; - } -} -function validateSkillName(name, directoryName) { - if (!name) - return { - valid: false, - error: "name is required" - }; - if (name.length > 64) - return { - valid: false, - error: "name exceeds 64 characters" - }; - if (!SKILL_NAME_PATTERN.test(name)) - return { - valid: false, - error: "name must be lowercase alphanumeric with single hyphens only" - }; - if (name !== directoryName) - return { - valid: false, - error: `name '${name}' must match directory name '${directoryName}'` - }; - return { valid: true }; -} -function parseFrontmatter(content) { - const match2 = content.match(FRONTMATTER_PATTERN); - if (!match2) - return null; - try { - const parsed = import_yaml.default.parse(match2[1]); - return typeof parsed === "object" && parsed !== null ? parsed : null; - } catch { - return null; - } -} -function parseSkillMetadata(skillMdPath, source) { - try { - const stats = fs$1.statSync(skillMdPath); - if (stats.size > 10485760) { - console.warn(`Skipping ${skillMdPath}: file too large (${stats.size} bytes)`); - return null; - } - const frontmatter = parseFrontmatter(fs$1.readFileSync(skillMdPath, "utf-8")); - if (!frontmatter) { - console.warn(`Skipping ${skillMdPath}: no valid YAML frontmatter found`); - return null; } - const name = frontmatter.name; - const description = frontmatter.description; - if (!name || !description) { - console.warn(`Skipping ${skillMdPath}: missing required 'name' or 'description'`); - return null; + get discriminator() { + return this._def.discriminator; } - const directoryName = path$1.basename(path$1.dirname(skillMdPath)); - const validation = validateSkillName(String(name), directoryName); - if (!validation.valid) - console.warn(`Skill '${name}' in ${skillMdPath} does not follow Agent Skills spec: ${validation.error}. Consider renaming to be spec-compliant.`); - let descriptionStr = String(description); - if (descriptionStr.length > 1024) { - console.warn(`Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH$1} chars in ${skillMdPath}, truncating`); - descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH$1); + get options() { + return this._def.options; } - return { - name: String(name), - description: descriptionStr, - path: skillMdPath, - source, - license: frontmatter.license ? String(frontmatter.license) : undefined, - compatibility: frontmatter.compatibility ? String(frontmatter.compatibility) : undefined, - metadata: frontmatter.metadata && typeof frontmatter.metadata === "object" ? frontmatter.metadata : undefined, - allowedTools: frontmatter["allowed-tools"] ? String(frontmatter["allowed-tools"]) : undefined - }; - } catch (error51) { - console.warn(`Error reading ${skillMdPath}: ${error51}`); - return null; - } -} -function listSkillsFromDir(skillsDir, source) { - const expandedDir = skillsDir.startsWith("~") ? path$1.join(process.env.HOME || process.env.USERPROFILE || "", skillsDir.slice(1)) : skillsDir; - if (!fs$1.existsSync(expandedDir)) - return []; - let resolvedBase; - try { - resolvedBase = fs$1.realpathSync(expandedDir); - } catch { - return []; - } - const skills = []; - let entries; - try { - entries = fs$1.readdirSync(resolvedBase, { withFileTypes: true }); - } catch { - return []; - } - for (const entry of entries) { - const skillDir = path$1.join(resolvedBase, entry.name); - if (!isSafePath(skillDir, resolvedBase)) - continue; - if (!entry.isDirectory()) - continue; - const skillMdPath = path$1.join(skillDir, "SKILL.md"); - if (!fs$1.existsSync(skillMdPath)) - continue; - if (!isSafePath(skillMdPath, resolvedBase)) - continue; - const metadata = parseSkillMetadata(skillMdPath, source); - if (metadata) - skills.push(metadata); - } - return skills; -} -function listSkills(options) { - const allSkills = /* @__PURE__ */ new Map; - if (options.userSkillsDir) { - const userSkills = listSkillsFromDir(options.userSkillsDir, "user"); - for (const skill of userSkills) - allSkills.set(skill.name, skill); - } - if (options.projectSkillsDir) { - const projectSkills = listSkillsFromDir(options.projectSkillsDir, "project"); - for (const skill of projectSkills) - allSkills.set(skill.name, skill); - } - return Array.from(allSkills.values()); -} -var import_micromatch, import_yaml, import_fast_glob, EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents", MAX_LINE_LENGTH = 5000, TOOL_RESULT_TOKEN_LIMIT = 20000, TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]", MIME_TYPES, SANDBOX_ERROR_SYMBOL, SandboxError, PREGEL_SEND_KEY = "__pregel_send", PREGEL_READ_KEY = "__pregel_read", StateBackend = class { - runtime; - fileFormat; - constructor(runtimeOrOptions, options) { - if (runtimeOrOptions != null && typeof runtimeOrOptions === "object" && "state" in runtimeOrOptions) { - this.runtime = runtimeOrOptions; - this.fileFormat = options?.fileFormat ?? "v2"; - } else { - this.runtime = undefined; - this.fileFormat = runtimeOrOptions?.fileFormat ?? "v2"; + get optionsMap() { + return this._def.optionsMap; } - } - get isLegacy() { - return this.runtime !== undefined; - } - get files() { - if (this.runtime) - return this.runtime.state.files ?? {}; - const read = getConfig().configurable?.[PREGEL_READ_KEY]; - return read?.("files", true) ?? {}; - } - sendFilesUpdate(update) { - if (this.isLegacy) - return; - const send = getConfig().configurable?.[PREGEL_SEND_KEY]; - if (typeof send === "function") - send([["files", update]]); - } - ls(path3) { - const files = this.files; - const infos = []; - const subdirs = /* @__PURE__ */ new Set; - const normalizedPath = path3.endsWith("/") ? path3 : path3 + "/"; - for (const [k, fd] of Object.entries(files)) { - if (!k.startsWith(normalizedPath)) - continue; - const relative2 = k.substring(normalizedPath.length); - if (relative2.includes("/")) { - const subdirName = relative2.split("/")[0]; - subdirs.add(normalizedPath + subdirName + "/"); - continue; + static create(discriminator, options, params) { + const optionsMap = new Map; + for (const type of options) { + const discriminatorValues = getDiscriminator2(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } } - const size = isFileDataV1(fd) ? fd.content.join(` -`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length; - infos.push({ - path: k, - is_dir: false, - size, - modified_at: fd.modified_at + return new ZodDiscriminatedUnion4({ + typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams2(params) }); } - for (const subdir of Array.from(subdirs).sort()) - infos.push({ - path: subdir, - is_dir: true, - size: 0, - modified_at: "" - }); - infos.sort((a, b) => a.path.localeCompare(b.path)); - return { files: infos }; - } - read(filePath, offset = 0, limit = 500) { - const fileData = this.files[filePath]; - if (!fileData) - return { error: `File '${filePath}' not found` }; - const fileDataV2 = migrateToFileDataV2(fileData, filePath); - if (!isTextMimeType(fileDataV2.mimeType)) - return { - content: fileDataV2.content, - mimeType: fileDataV2.mimeType + }; + ZodIntersection4 = class ZodIntersection4 extends ZodType4 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { + return INVALID2; + } + const merged = mergeValues4(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_intersection_types + }); + return INVALID2; + } + if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; }; - if (typeof fileDataV2.content !== "string") - return { error: `File '${filePath}' has binary content but text MIME type` }; - return { - content: fileDataV2.content.split(` -`).slice(offset, offset + limit).join(` -`), - mimeType: fileDataV2.mimeType - }; - } - readRaw(filePath) { - const fileData = this.files[filePath]; - if (!fileData) - return { error: `File '${filePath}' not found` }; - return { data: fileData }; - } - write(filePath, content) { - if (filePath in this.files) - return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; - const mimeType = getMimeType(filePath); - const newFileData = createFileData(content, undefined, this.fileFormat, mimeType); - const update = { [filePath]: newFileData }; - if (!this.isLegacy) { - this.sendFilesUpdate(update); - return { path: filePath }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } } - return { - path: filePath, - filesUpdate: { [filePath]: newFileData } - }; - } - edit(filePath, oldString, newString, replaceAll = false) { - const fileData = this.files[filePath]; - if (!fileData) - return { error: `Error: File '${filePath}' not found` }; - const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll); - if (typeof result === "string") - return { error: result }; - const [newContent, occurrences] = result; - const newFileData = updateFileData(fileData, newContent); - const update = { [filePath]: newFileData }; - if (!this.isLegacy) { - this.sendFilesUpdate(update); - return { - path: filePath, - occurrences - }; + }; + ZodIntersection4.create = (left, right, params) => { + return new ZodIntersection4({ + left, + right, + typeName: ZodFirstPartyTypeKind3.ZodIntersection, + ...processCreateParams2(params) + }); + }; + ZodTuple4 = class ZodTuple4 extends ZodType4 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.array) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.array, + received: ctx.parsedType + }); + return INVALID2; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID2; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus2.mergeArray(status, results); + }); + } else { + return ParseStatus2.mergeArray(status, items); + } } - return { - path: filePath, - filesUpdate: { [filePath]: newFileData }, - occurrences - }; - } - grep(pattern, path3 = "/", glob = null) { - const files = this.files; - return { matches: grepMatchesFromFiles(files, pattern, path3, glob) }; - } - glob(pattern, path3 = "/") { - const files = this.files; - const result = globSearchFiles(files, pattern, path3); - if (result === "No files found") - return { files: [] }; - const paths = result.split(` -`); - const infos = []; - for (const p of paths) { - const fd = files[p]; - const size = fd ? isFileDataV1(fd) ? fd.content.join(` -`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0; - infos.push({ - path: p, - is_dir: false, - size, - modified_at: fd?.modified_at || "" + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple4({ + ...this._def, + rest }); } - return { files: infos }; - } - uploadFiles(files) { - const responses = []; - const updates = {}; - for (const [path3, content] of files) - try { - const mimeType = getMimeType(path3); - if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) - updates[path3] = createFileData(content, undefined, "v2", mimeType); - else - updates[path3] = createFileData(new TextDecoder().decode(content), undefined, this.fileFormat, mimeType); - responses.push({ - path: path3, - error: null + }; + ZodTuple4.create = (schemas5, params) => { + if (!Array.isArray(schemas5)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple4({ + items: schemas5, + typeName: ZodFirstPartyTypeKind3.ZodTuple, + rest: null, + ...processCreateParams2(params) + }); + }; + ZodRecord4 = class ZodRecord4 extends ZodType4 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.object) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.object, + received: ctx.parsedType }); - } catch { - responses.push({ - path: path3, - error: "invalid_path" + return INVALID2; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data }); } - if (!this.isLegacy) { - if (Object.keys(updates).length > 0) - this.sendFilesUpdate(updates); - return responses; + if (ctx.common.async) { + return ParseStatus2.mergeObjectAsync(status, pairs); + } else { + return ParseStatus2.mergeObjectSync(status, pairs); + } } - const result = responses; - result.filesUpdate = updates; - return result; - } - downloadFiles(paths) { - const files = this.files; - const responses = []; - for (const path3 of paths) { - const fileData = files[path3]; - if (!fileData) { - responses.push({ - path: path3, - content: null, - error: "file_not_found" + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType4) { + return new ZodRecord4({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams2(third) }); - continue; } - const fileDataV2 = migrateToFileDataV2(fileData, path3); - if (typeof fileDataV2.content === "string") { - const content = new TextEncoder().encode(fileDataV2.content); - responses.push({ - path: path3, - content, - error: null - }); - } else - responses.push({ - path: path3, - content: fileDataV2.content, - error: null - }); + return new ZodRecord4({ + keyType: ZodString4.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams2(second) + }); } - return responses; - } -}, CompositeBackend = class { - default; - routes; - sortedRoutes; - constructor(defaultBackend, routes) { - this.default = isSandboxProtocol(defaultBackend) ? adaptSandboxProtocol(defaultBackend) : adaptBackendProtocol(defaultBackend); - this.routes = Object.fromEntries(Object.entries(routes).map(([k, v]) => [k, isSandboxProtocol(v) ? adaptSandboxProtocol(v) : adaptBackendProtocol(v)])); - this.sortedRoutes = Object.entries(this.routes).sort((a, b) => b[0].length - a[0].length); - } - get id() { - return isSandboxBackend(this.default) ? this.default.id : ""; - } - get routePrefixes() { - return Object.keys(this.routes); - } - static isInstance(backend) { - return typeof backend === "object" && backend !== null && Array.isArray(backend.routePrefixes); - } - getBackendAndKey(key) { - for (const [prefix, backend] of this.sortedRoutes) - if (key.startsWith(prefix)) { - const suffix = key.substring(prefix.length); - return [backend, suffix ? "/" + suffix : "/"]; - } - return [this.default, key]; - } - async ls(path3) { - for (const [routePrefix, backend] of this.sortedRoutes) - if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { - const suffix = path3.substring(routePrefix.length); - const searchPath = suffix ? "/" + suffix : "/"; - const result = await backend.ls(searchPath); - if (result.error) - return result; - const prefixed = []; - for (const fi of result.files || []) - prefixed.push({ - ...fi, - path: routePrefix.slice(0, -1) + fi.path - }); - return { files: prefixed }; + }; + ZodMap4 = class ZodMap4 extends ZodType4 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.map) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.map, + received: ctx.parsedType + }); + return INVALID2; } - if (path3 === "/") { - const results = []; - const defaultResult = await this.default.ls(path3); - if (defaultResult.error) - return defaultResult; - results.push(...defaultResult.files || []); - for (const [routePrefix] of this.sortedRoutes) - results.push({ - path: routePrefix, - is_dir: true, - size: 0, - modified_at: "" + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = new Map; + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID2; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; }); - results.sort((a, b) => a.path.localeCompare(b.path)); - return { files: results }; - } - return await this.default.ls(path3); - } - async read(filePath, offset = 0, limit = 500) { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.read(strippedKey, offset, limit); - } - async readRaw(filePath) { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.readRaw(strippedKey); - } - async grep(pattern, path3 = "/", glob = null) { - for (const [routePrefix, backend] of this.sortedRoutes) - if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { - const searchPath = path3.substring(routePrefix.length - 1); - const raw2 = await backend.grep(pattern, searchPath || "/", glob); - if (raw2.error) - return raw2; - return { matches: (raw2.matches || []).map((m) => ({ - ...m, - path: routePrefix.slice(0, -1) + m.path - })) }; + } else { + const finalMap = new Map; + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID2; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; } - const allMatches = []; - const rawDefault = await this.default.grep(pattern, path3, glob); - if (rawDefault.error) - return rawDefault; - allMatches.push(...rawDefault.matches || []); - for (const [routePrefix, backend] of Object.entries(this.routes)) { - const raw2 = await backend.grep(pattern, "/", glob); - if (raw2.error) - return raw2; - const matches = (raw2.matches || []).map((m) => ({ - ...m, - path: routePrefix.slice(0, -1) + m.path - })); - allMatches.push(...matches); } - return { matches: allMatches }; - } - async glob(pattern, path3 = "/") { - const results = []; - for (const [routePrefix, backend] of this.sortedRoutes) - if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { - const searchPath = path3.substring(routePrefix.length - 1); - const result = await backend.glob(pattern, searchPath || "/"); - if (result.error) - return result; - return { files: (result.files || []).map((fi) => ({ - ...fi, - path: routePrefix.slice(0, -1) + fi.path - })) }; + }; + ZodMap4.create = (keyType, valueType, params) => { + return new ZodMap4({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind3.ZodMap, + ...processCreateParams2(params) + }); + }; + ZodSet4 = class ZodSet4 extends ZodType4 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.set) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.set, + received: ctx.parsedType + }); + return INVALID2; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = new Set; + for (const element of elements2) { + if (element.status === "aborted") + return INVALID2; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); } - const defaultResult = await this.default.glob(pattern, path3); - if (defaultResult.error) - return defaultResult; - results.push(...defaultResult.files || []); - for (const [routePrefix, backend] of Object.entries(this.routes)) { - const result = await backend.glob(pattern, "/"); - if (result.error) - continue; - const files = (result.files || []).map((fi) => ({ - ...fi, - path: routePrefix.slice(0, -1) + fi.path - })); - results.push(...files); } - results.sort((a, b) => a.path.localeCompare(b.path)); - return { files: results }; - } - async write(filePath, content) { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.write(strippedKey, content); - } - async edit(filePath, oldString, newString, replaceAll = false) { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.edit(strippedKey, oldString, newString, replaceAll); - } - execute(command) { - if (!isSandboxBackend(this.default)) - throw new Error("Default backend doesn't support command execution (SandboxBackendProtocol). To enable execution, provide a default backend that implements SandboxBackendProtocol."); - return Promise.resolve(this.default.execute(command)); - } - async uploadFiles(files) { - const results = Array.from({ length: files.length }, () => null); - const batchesByBackend = /* @__PURE__ */ new Map; - for (let idx = 0;idx < files.length; idx++) { - const [path3, content] = files[idx]; - const [backend, strippedPath] = this.getBackendAndKey(path3); - if (!batchesByBackend.has(backend)) - batchesByBackend.set(backend, []); - batchesByBackend.get(backend).push({ - idx, - path: strippedPath, - content + min(minSize, message) { + return new ZodSet4({ + ...this._def, + minSize: { value: minSize, message: errorUtil2.toString(message) } }); } - for (const [backend, batch] of batchesByBackend) { - if (!backend.uploadFiles) - throw new Error("Backend does not support uploadFiles"); - const batchFiles = batch.map((b) => [b.path, b.content]); - const batchResponses = await backend.uploadFiles(batchFiles); - for (let i = 0;i < batch.length; i++) { - const originalIdx = batch[i].idx; - results[originalIdx] = { - path: files[originalIdx][0], - error: batchResponses[i]?.error ?? null - }; - } - } - return results; - } - async downloadFiles(paths) { - const results = Array.from({ length: paths.length }, () => null); - const batchesByBackend = /* @__PURE__ */ new Map; - for (let idx = 0;idx < paths.length; idx++) { - const path3 = paths[idx]; - const [backend, strippedPath] = this.getBackendAndKey(path3); - if (!batchesByBackend.has(backend)) - batchesByBackend.set(backend, []); - batchesByBackend.get(backend).push({ - idx, - path: strippedPath + max(maxSize, message) { + return new ZodSet4({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil2.toString(message) } }); } - for (const [backend, batch] of batchesByBackend) { - if (!backend.downloadFiles) - throw new Error("Backend does not support downloadFiles"); - const batchPaths = batch.map((b) => b.path); - const batchResponses = await backend.downloadFiles(batchPaths); - for (let i = 0;i < batch.length; i++) { - const originalIdx = batch[i].idx; - results[originalIdx] = { - path: paths[originalIdx], - content: batchResponses[i]?.content ?? null, - error: batchResponses[i]?.error ?? null - }; - } + size(size, message) { + return this.min(size, message).max(size, message); } - return results; - } -}, INT_FORMATTER, FILESYSTEM_TOOL_NAMES, TOOLS_EXCLUDED_FROM_EVICTION, MAX_BINARY_READ_SIZE_BYTES, READ_FILE_TRUNCATION_MSG = ` - -[Output was truncated due to size limits. The file content is very large. Consider reformatting the file to make it easier to navigate. For example, if this is JSON, use execute(command='jq . {file_path}') to pretty-print it with line breaks. For other formats, you can use appropriate formatting tools to split long lines.]`, TOO_LARGE_TOOL_MSG, TOO_LARGE_HUMAN_MSG = `Message content too large and was saved to the filesystem at: {file_path} - -You can read the full content using the read_file tool with pagination (offset and limit parameters). - -Here is a preview showing the head and tail of the content: - -{content_sample}`, FileDataV1Schema, FileDataV2Schema, FileDataSchema, FilesystemStateSchema, FILESYSTEM_SYSTEM_PROMPT, LS_TOOL_DESCRIPTION, READ_FILE_TOOL_DESCRIPTION, WRITE_FILE_TOOL_DESCRIPTION, EDIT_FILE_TOOL_DESCRIPTION, GLOB_TOOL_DESCRIPTION, GREP_TOOL_DESCRIPTION, EXECUTE_TOOL_DESCRIPTION, EXECUTION_SYSTEM_PROMPT, DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools.", EXCLUDED_STATE_KEYS, DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.", TASK_SYSTEM_PROMPT, GENERAL_PURPOSE_SUBAGENT, INVALID_TOOL_MESSAGE_BLOCK_TYPES, filesValue, MemoryStateSchema, MEMORY_SYSTEM_PROMPT, MAX_SKILL_FILE_SIZE, DEFAULT_SKILL_READ_LINE_LIMIT = 1000, MAX_SKILL_NAME_LENGTH = 64, MAX_SKILL_DESCRIPTION_LENGTH = 1024, SKILL_MODULE_EXTENSIONS, SkillMetadataEntrySchema, SkillsStateSchema, SKILLS_SYSTEM_PROMPT, MAX_MESSAGE_LENGTH = 500, TRUNCATION_SUFFIX = "... [full result truncated]", CALLBACK_THREAD_ID_KEY = "callbackThreadId", CompletionCallbackStateSchema, DEFAULT_MESSAGES_TO_KEEP = 20, DEFAULT_TRIM_TOKEN_LIMIT = 4000, FALLBACK_TRIGGER, FALLBACK_KEEP, FALLBACK_TRUNCATE_ARGS, PROFILE_TRIGGER, PROFILE_KEEP, PROFILE_TRUNCATE_ARGS, DEFAULT_SUMMARY_PROMPT2 = `You are a conversation summarizer. Your task is to create a concise summary of the conversation that captures: -1. The main topics discussed -2. Key decisions or conclusions reached -3. Any important context that would be needed for continuing the conversation - -Keep the summary focused and informative. Do not include unnecessary details. - -Conversation to summarize: -{conversation} - -Summary:`, SummarizationEventSchema, SummarizationStateSchema, AsyncTaskSchema, AsyncTaskStateSchema, ASYNC_TASK_TOOL_DESCRIPTION = `Launch an async subagent on a remote server. The subagent runs in the background and returns a task ID immediately. - -Available async agent types: -{available_agents} - -## Usage notes: -1. This tool launches a background task and returns immediately with a task ID. Report the task ID to the user and stop — do NOT immediately check status. -2. Use \`check_async_task\` only when the user asks for a status update or result. -3. Use \`update_async_task\` to send new instructions to a running task. -4. Multiple async subagents can run concurrently — launch several and let them run in the background. -5. The subagent runs on a remote server, so it has its own tools and capabilities.`, ASYNC_TASK_SYSTEM_PROMPT = `## Async subagents (remote servers) - -You have access to async subagent tools that launch background tasks on remote servers. - -### Tools: -- \`start_async_task\`: Start a new background task. Returns a task ID immediately. -- \`check_async_task\`: Check the status of a running task. Returns status and result if complete. -- \`update_async_task\`: Send an update or new instructions to a running task. -- \`cancel_async_task\`: Cancel a running task that is no longer needed. -- \`list_async_tasks\`: List all tracked tasks with live statuses. Use this to check all tasks at once. - -### Workflow: -1. **Launch** — Use \`start_async_task\` to start a task. Report the task ID to the user and stop. - Do NOT immediately check the status — the task runs in the background while you and the user continue other work. -2. **Check (on request)** — Only use \`check_async_task\` when the user explicitly asks for a status update or - result. If the status is "running", report that and stop — do not poll in a loop. -3. **Update** (optional) — Use \`update_async_task\` to send new instructions to a running task. This interrupts - the current run and starts a fresh one on the same thread. The task_id stays the same. -4. **Cancel** (optional) — Use \`cancel_async_task\` to stop a task that is no longer needed. -5. **Collect** — When \`check_async_task\` returns status "success", the result is included in the response. -6. **List** — Use \`list_async_tasks\` to see live statuses for all tasks at once, or to recall task IDs after context compaction. - -### Critical rules: -- After launching, ALWAYS return control to the user immediately. Never auto-check after launching. -- Never poll \`check_async_task\` in a loop. Check once per user request, then stop. -- If a check returns "running", tell the user and wait for them to ask again. -- Task statuses in conversation history are ALWAYS stale — a task that was "running" may now be done. - NEVER report a status from a previous tool result. ALWAYS call a tool to get the current status: - use \`list_async_tasks\` when the user asks about multiple tasks or "all tasks", - use \`check_async_task\` when the user asks about a specific task. -- Always show the full task_id — never truncate or abbreviate it. - -### When to use async subagents: -- Long-running tasks that would block the main agent -- Tasks that benefit from running on specialized remote deployments -- When you want to run multiple tasks concurrently and collect results later`, ASYNC_TASK_TOOL_NAMES, TERMINAL_STATUSES, ClientCache = class { - agents; - clients = /* @__PURE__ */ new Map; - constructor(agents) { - this.agents = agents; - } - resolveHeaders(spec) { - const headers = { ...spec.headers || {} }; - if (!("x-auth-scheme" in headers)) - headers["x-auth-scheme"] = "langsmith"; - return headers; - } - cacheKey(spec) { - const headers = this.resolveHeaders(spec); - const headerStr = Object.entries(headers).sort().flat().join(":"); - return `${spec.url ?? ""}|${headerStr}`; - } - getClient(name) { - const spec = this.agents[name]; - const key = this.cacheKey(spec); - const existing = this.clients.get(key); - if (existing) - return existing; - const headers = this.resolveHeaders(spec); - const client2 = new Client2({ - apiUrl: spec.url, - defaultHeaders: headers + nonempty(message) { + return this.min(1, message); + } + }; + ZodSet4.create = (valueType, params) => { + return new ZodSet4({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind3.ZodSet, + ...processCreateParams2(params) }); - this.clients.set(key, client2); - return client2; - } -}, NAMESPACE_COMPONENT_RE, StoreBackend = class { - stateAndStore; - storeOverride; - _namespace; - fileFormat; - constructor(stateAndStoreOrOptions, options) { - let opts; - if (stateAndStoreOrOptions != null && typeof stateAndStoreOrOptions === "object" && "state" in stateAndStoreOrOptions) { - this.stateAndStore = stateAndStoreOrOptions; - opts = options; - } else { - this.stateAndStore = undefined; - opts = stateAndStoreOrOptions; + }; + ZodFunction3 = class ZodFunction3 extends ZodType4 { + constructor() { + super(...arguments); + this.validate = this.implement; } - if (Array.isArray(opts?.namespace)) - this._namespace = validateNamespace2(opts.namespace); - else if (opts?.namespace) - this._namespace = opts.namespace; - this.storeOverride = opts?.store; - this.fileFormat = opts?.fileFormat ?? "v2"; - } - getStore() { - if (this.stateAndStore) { - const store2 = this.stateAndStore.store; - if (!store2) - throw new Error("Store is required but not available in runtime"); - return store2; + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.function) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.function, + received: ctx.parsedType + }); + return INVALID2; + } + function makeArgsIssue(args, error90) { + return makeIssue2({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), + issueData: { + code: ZodIssueCode4.invalid_arguments, + argumentsError: error90 + } + }); + } + function makeReturnsIssue(returns, error90) { + return makeIssue2({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), + issueData: { + code: ZodIssueCode4.invalid_return_type, + returnTypeError: error90 + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise4) { + const me = this; + return OK2(async function(...args) { + const error90 = new ZodError5([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error90.addIssue(makeArgsIssue(args, e)); + throw error90; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error90.addIssue(makeReturnsIssue(result, e)); + throw error90; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK2(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError5([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError5([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } } - if (this.storeOverride) - return this.storeOverride; - const store = getStore(); - if (!store) - throw new Error("Store is required but not available in LangGraph execution context. Ensure the graph was configured with a store."); - return store; - } - getState() { - if (this.stateAndStore) - return this.stateAndStore.state; - try { - return getCurrentTaskInput(); - } catch { - return; + parameters() { + return this._def.args; } - } - getNamespaceConfig() { - const injectedConfig = getObjectRecord(this.stateAndStore?.config); - if (injectedConfig) - return { - metadata: getObjectRecord(injectedConfig.metadata), - configurable: getObjectRecord(injectedConfig.configurable) - }; - try { - const configRecord = getObjectRecord(getConfig()); - if (!configRecord) - return; - return { - metadata: getObjectRecord(configRecord.metadata), - configurable: getObjectRecord(configRecord.configurable) - }; - } catch { - return; + returnType() { + return this._def.returns; } - } - getLegacyAssistantId() { - const config2 = this.getNamespaceConfig(); - const assistantIdFromConfig = getAssistantIdFromRecord(config2?.metadata) ?? getAssistantIdFromRecord(config2?.configurable); - if (assistantIdFromConfig) - return assistantIdFromConfig; - const assistantId = this.stateAndStore?.assistantId; - return typeof assistantId === "string" && assistantId.length > 0 ? assistantId : undefined; - } - getNamespace() { - if (Array.isArray(this._namespace)) - return this._namespace; - if (this._namespace) - return validateNamespace2(this._namespace({ - state: this.getState(), - config: this.getNamespaceConfig(), - assistantId: this.getLegacyAssistantId() - })); - const assistantId = this.getLegacyAssistantId(); - if (assistantId) - return [assistantId, "filesystem"]; - return ["filesystem"]; - } - convertStoreItemToFileData(storeItem) { - const value = storeItem.value; - if (!(value.content !== undefined && (Array.isArray(value.content) || typeof value.content === "string" || ArrayBuffer.isView(value.content))) || typeof value.created_at !== "string" || typeof value.modified_at !== "string") - throw new Error(`Store item does not contain valid FileData fields. Got keys: ${Object.keys(value).join(", ")}`); - return { - content: value.content, - ...value.mimeType ? { mimeType: value.mimeType } : {}, - created_at: value.created_at, - modified_at: value.modified_at - }; - } - convertFileDataToStoreValue(fileData) { - return { - content: fileData.content, - ..."mimeType" in fileData ? { mimeType: fileData.mimeType } : {}, - created_at: fileData.created_at, - modified_at: fileData.modified_at - }; - } - async searchStorePaginated(store, namespace, options = {}) { - const { query: query3, filter, pageSize = 100 } = options; - const allItems = []; - let offset = 0; - while (true) { - const pageItems = await store.search(namespace, { - query: query3, - filter, - limit: pageSize, - offset + args(...items) { + return new ZodFunction3({ + ...this._def, + args: ZodTuple4.create(items).rest(ZodUnknown4.create()) }); - if (!pageItems || pageItems.length === 0) - break; - allItems.push(...pageItems); - if (pageItems.length < pageSize) - break; - offset += pageSize; } - return allItems; - } - async ls(path3) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const items = await this.searchStorePaginated(store, namespace); - const infos = []; - const subdirs = /* @__PURE__ */ new Set; - const normalizedPath = path3.endsWith("/") ? path3 : path3 + "/"; - for (const item of items) { - const itemKey = String(item.key); - if (!itemKey.startsWith(normalizedPath)) - continue; - const relative2 = itemKey.substring(normalizedPath.length); - if (relative2.includes("/")) { - const subdirName = relative2.split("/")[0]; - subdirs.add(normalizedPath + subdirName + "/"); - continue; + returns(returnType) { + return new ZodFunction3({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction3({ + args: args ? args : ZodTuple4.create([]).rest(ZodUnknown4.create()), + returns: returns || ZodUnknown4.create(), + typeName: ZodFirstPartyTypeKind3.ZodFunction, + ...processCreateParams2(params) + }); + } + }; + ZodLazy4 = class ZodLazy4 extends ZodType4 { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + ZodLazy4.create = (getter, params) => { + return new ZodLazy4({ + getter, + typeName: ZodFirstPartyTypeKind3.ZodLazy, + ...processCreateParams2(params) + }); + }; + ZodLiteral4 = class ZodLiteral4 extends ZodType4 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode4.invalid_literal, + expected: this._def.value + }); + return INVALID2; } - try { - const fd = this.convertStoreItemToFileData(item); - const size = isFileDataV1(fd) ? fd.content.join(` -`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length; - infos.push({ - path: itemKey, - is_dir: false, - size, - modified_at: fd.modified_at + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + ZodLiteral4.create = (value, params) => { + return new ZodLiteral4({ + value, + typeName: ZodFirstPartyTypeKind3.ZodLiteral, + ...processCreateParams2(params) + }); + }; + ZodEnum4 = class ZodEnum4 extends ZodType4 { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext2(ctx, { + expected: util3.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode4.invalid_type }); - } catch { - continue; + return INVALID2; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode4.invalid_enum_value, + options: expectedValues + }); + return INVALID2; } + return OK2(input.data); } - for (const subdir of Array.from(subdirs).sort()) - infos.push({ - path: subdir, - is_dir: true, - size: 0, - modified_at: "" - }); - infos.sort((a, b) => a.path.localeCompare(b.path)); - return { files: infos }; - } - async read(filePath, offset = 0, limit = 500) { - try { - const readRawResult = await this.readRaw(filePath); - if (readRawResult.error || !readRawResult.data) - return { error: readRawResult.error || "File data not found" }; - const fileDataV2 = migrateToFileDataV2(readRawResult.data, filePath); - if (!isTextMimeType(fileDataV2.mimeType)) - return { - content: fileDataV2.content, - mimeType: fileDataV2.mimeType - }; - if (typeof fileDataV2.content !== "string") - return { error: `File '${filePath}' has binary content but text MIME type` }; - return { - content: fileDataV2.content.split(` -`).slice(offset, offset + limit).join(` -`), - mimeType: fileDataV2.mimeType - }; - } catch (e) { - return { error: e.message }; + get options() { + return this._def.values; } - } - async readRaw(filePath) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const item = await store.get(namespace, filePath); - if (!item) - return { error: `File '${filePath}' not found` }; - return { data: this.convertStoreItemToFileData(item) }; - } - async write(filePath, content) { - const store = this.getStore(); - const namespace = this.getNamespace(); - if (await store.get(namespace, filePath)) - return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; - const mimeType = getMimeType(filePath); - const fileData = createFileData(content, undefined, this.fileFormat, mimeType); - const storeValue = this.convertFileDataToStoreValue(fileData); - await store.put(namespace, filePath, storeValue); - return { - path: filePath, - filesUpdate: null - }; - } - async edit(filePath, oldString, newString, replaceAll = false) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const item = await store.get(namespace, filePath); - if (!item) - return { error: `Error: File '${filePath}' not found` }; - try { - const fileData = this.convertStoreItemToFileData(item); - const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll); - if (typeof result === "string") - return { error: result }; - const [newContent, occurrences] = result; - const newFileData = updateFileData(fileData, newContent); - const storeValue = this.convertFileDataToStoreValue(newFileData); - await store.put(namespace, filePath, storeValue); - return { - path: filePath, - filesUpdate: null, - occurrences - }; - } catch (e) { - return { error: `Error: ${e.message}` }; + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - } - async grep(pattern, path3 = "/", glob = null) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const items = await this.searchStorePaginated(store, namespace); - const files = {}; - for (const item of items) - try { - files[item.key] = this.convertStoreItemToFileData(item); - } catch { - continue; + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - return { matches: grepMatchesFromFiles(files, pattern, path3, glob) }; - } - async glob(pattern, path3 = "/") { - const store = this.getStore(); - const namespace = this.getNamespace(); - const items = await this.searchStorePaginated(store, namespace); - const files = {}; - for (const item of items) - try { - files[item.key] = this.convertStoreItemToFileData(item); - } catch { - continue; + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - const result = globSearchFiles(files, pattern, path3); - if (result === "No files found") - return { files: [] }; - const paths = result.split(` -`); - const infos = []; - for (const p of paths) { - const fd = files[p]; - const size = fd ? isFileDataV1(fd) ? fd.content.join(` -`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0; - infos.push({ - path: p, - is_dir: false, - size, - modified_at: fd?.modified_at || "" + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum4.create(values, { + ...this._def, + ...newDef }); } - return { files: infos }; - } - async uploadFiles(files) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const responses = []; - for (const [path3, content] of files) - try { - const mimeType = getMimeType(path3); - const isBinary = this.fileFormat === "v2" && !isTextMimeType(mimeType); - let fileData; - if (isBinary) - fileData = createFileData(content, undefined, "v2", mimeType); - else - fileData = createFileData(new TextDecoder().decode(content), undefined, this.fileFormat, mimeType); - const storeValue = this.convertFileDataToStoreValue(fileData); - await store.put(namespace, path3, storeValue); - responses.push({ - path: path3, - error: null + exclude(values, newDef = this._def) { + return ZodEnum4.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + ZodEnum4.create = createZodEnum2; + ZodNativeEnum2 = class ZodNativeEnum2 extends ZodType4 { + _parse(input) { + const nativeEnumValues = util3.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { + const expectedValues = util3.objectValues(nativeEnumValues); + addIssueToContext2(ctx, { + expected: util3.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode4.invalid_type }); - } catch { - responses.push({ - path: path3, - error: "invalid_path" + return INVALID2; + } + if (!this._cache) { + this._cache = new Set(util3.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util3.objectValues(nativeEnumValues); + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode4.invalid_enum_value, + options: expectedValues }); + return INVALID2; } - return responses; - } - async downloadFiles(paths) { - const store = this.getStore(); - const namespace = this.getNamespace(); - const responses = []; - for (const path3 of paths) - try { - const item = await store.get(namespace, path3); - if (!item) { - responses.push({ - path: path3, - content: null, - error: "file_not_found" - }); - continue; + return OK2(input.data); + } + get enum() { + return this._def.values; + } + }; + ZodNativeEnum2.create = (values, params) => { + return new ZodNativeEnum2({ + values, + typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, + ...processCreateParams2(params) + }); + }; + ZodPromise4 = class ZodPromise4 extends ZodType4 { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.promise, + received: ctx.parsedType + }); + return INVALID2; + } + const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); + return OK2(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + ZodPromise4.create = (schema, params) => { + return new ZodPromise4({ + type: schema, + typeName: ZodFirstPartyTypeKind3.ZodPromise, + ...processCreateParams2(params) + }); + }; + ZodEffects2 = class ZodEffects2 extends ZodType4 { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext2(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; } - const fileDataV2 = migrateToFileDataV2(this.convertStoreItemToFileData(item), path3); - if (typeof fileDataV2.content === "string") { - const content = new TextEncoder().encode(fileDataV2.content); - responses.push({ - path: path3, - content, - error: null + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID2; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID2; + if (result.status === "dirty") + return DIRTY2(result.value); + if (status.value === "dirty") + return DIRTY2(result.value); + return result; }); - } else - responses.push({ - path: path3, - content: fileDataV2.content, - error: null + } else { + if (status.value === "aborted") + return INVALID2; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx }); - } catch { - responses.push({ - path: path3, - content: null, - error: "file_not_found" - }); + if (result.status === "aborted") + return INVALID2; + if (result.status === "dirty") + return DIRTY2(result.value); + if (status.value === "dirty") + return DIRTY2(result.value); + return result; + } } - return responses; - } -}, SUPPORTS_NOFOLLOW, FilesystemBackend = class { - cwd; - virtualMode; - maxFileSizeBytes; - constructor(options = {}) { - const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options; - this.cwd = rootDir ? path$1.resolve(rootDir) : process.cwd(); - this.virtualMode = virtualMode; - this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024; - } - resolvePath(key) { - if (this.virtualMode) { - const vpath = key.startsWith("/") ? key : "/" + key; - if (vpath.includes("..") || vpath.startsWith("~")) - throw new Error("Path traversal not allowed"); - const full = path$1.resolve(this.cwd, vpath.substring(1)); - const relative2 = path$1.relative(this.cwd, full); - if (relative2.startsWith("..") || path$1.isAbsolute(relative2)) - throw new Error(`Path: ${full} outside root directory: ${this.cwd}`); - return full; - } - if (path$1.isAbsolute(key)) - return key; - return path$1.resolve(this.cwd, key); - } - async ls(dirPath) { - try { - const resolvedPath = this.resolvePath(dirPath); - if (!(await fs.stat(resolvedPath)).isDirectory()) - return { files: [] }; - const entries = await fs.readdir(resolvedPath, { withFileTypes: true }); - const results = []; - const cwdStr = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; - for (const entry of entries) { - const fullPath = path$1.join(resolvedPath, entry.name); - try { - const entryStat = await fs.stat(fullPath); - const isFile = entryStat.isFile(); - const isDir = entryStat.isDirectory(); - if (!this.virtualMode) { - if (isFile) - results.push({ - path: fullPath, - is_dir: false, - size: entryStat.size, - modified_at: entryStat.mtime.toISOString() - }); - else if (isDir) - results.push({ - path: fullPath + path$1.sep, - is_dir: true, - size: 0, - modified_at: entryStat.mtime.toISOString() - }); - } else { - let relativePath; - if (fullPath.startsWith(cwdStr)) - relativePath = fullPath.substring(cwdStr.length); - else if (fullPath.startsWith(this.cwd)) - relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); - else - relativePath = fullPath; - relativePath = relativePath.split(path$1.sep).join("/"); - const virtPath = "/" + relativePath; - if (isFile) - results.push({ - path: virtPath, - is_dir: false, - size: entryStat.size, - modified_at: entryStat.mtime.toISOString() - }); - else if (isDir) - results.push({ - path: virtPath + "/", - is_dir: true, - size: 0, - modified_at: entryStat.mtime.toISOString() - }); + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); } - } catch { - continue; + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID2; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID2; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); } } - results.sort((a, b) => a.path.localeCompare(b.path)); - return { files: results }; - } catch { - return { files: [] }; - } - } - async read(filePath, offset = 0, limit = 500) { - try { - const resolvedPath = this.resolvePath(filePath); - const mimeType = getMimeType(filePath); - const isBinary = !isTextMimeType(mimeType); - let content; - if (SUPPORTS_NOFOLLOW) { - if (!(await fs.stat(resolvedPath)).isFile()) - return { error: `File '${filePath}' not found` }; - const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); - try { - if (isBinary) { - const buffer = await fd.readFile(); - return { - content: new Uint8Array(buffer), - mimeType - }; + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid2(base)) + return INVALID2; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - const stat4 = await fs.lstat(resolvedPath); - if (stat4.isSymbolicLink()) - return { error: `Symlinks are not allowed: ${filePath}` }; - if (!stat4.isFile()) - return { error: `File '${filePath}' not found` }; - if (isBinary) { - const buffer = await fs.readFile(resolvedPath); - return { - content: new Uint8Array(buffer), - mimeType - }; + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid2(base)) + return INVALID2; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); } - content = await fs.readFile(resolvedPath, "utf-8"); } - const emptyMsg = checkEmptyContent(content); - if (emptyMsg) - return { - content: emptyMsg, - mimeType - }; - const lines = content.split(` -`); - const startIdx = offset; - const endIdx = Math.min(startIdx + limit, lines.length); - if (startIdx >= lines.length) - return { error: `Line offset ${offset} exceeds file length (${lines.length} lines)` }; - return { - content: lines.slice(startIdx, endIdx).join(` -`), - mimeType - }; - } catch (e) { - return { error: `Error reading file '${filePath}': ${e.message}` }; + util3.assertNever(effect); } - } - async readRaw(filePath) { - const resolvedPath = this.resolvePath(filePath); - const mimeType = getMimeType(filePath); - const isBinary = !isTextMimeType(mimeType); - let content; - let stat4; - if (SUPPORTS_NOFOLLOW) { - stat4 = await fs.stat(resolvedPath); - if (!stat4.isFile()) - return { error: `File '${filePath}' not found` }; - const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); - try { - if (isBinary) { - const buffer = await fd.readFile(); - return { data: { - content: new Uint8Array(buffer), - mimeType, - created_at: stat4.ctime.toISOString(), - modified_at: stat4.mtime.toISOString() - } }; - } - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - stat4 = await fs.lstat(resolvedPath); - if (stat4.isSymbolicLink()) - return { error: `Symlinks are not allowed: ${filePath}` }; - if (!stat4.isFile()) - return { error: `File '${filePath}' not found` }; - if (isBinary) { - const buffer = await fs.readFile(resolvedPath); - return { data: { - content: new Uint8Array(buffer), - mimeType, - created_at: stat4.ctime.toISOString(), - modified_at: stat4.mtime.toISOString() - } }; + }; + ZodEffects2.create = (schema, effect, params) => { + return new ZodEffects2({ + schema, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect, + ...processCreateParams2(params) + }); + }; + ZodEffects2.createWithPreprocess = (preprocess3, schema, params) => { + return new ZodEffects2({ + schema, + effect: { type: "preprocess", transform: preprocess3 }, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + ...processCreateParams2(params) + }); + }; + ZodOptional4 = class ZodOptional4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 === ZodParsedType2.undefined) { + return OK2(undefined); } - content = await fs.readFile(resolvedPath, "utf-8"); + return this._def.innerType._parse(input); } - return { data: { - content, - mimeType, - created_at: stat4.ctime.toISOString(), - modified_at: stat4.mtime.toISOString() - } }; - } - async write(filePath, content) { - try { - const resolvedPath = this.resolvePath(filePath); - const isBinary = !isTextMimeType(getMimeType(filePath)); - try { - if ((await fs.lstat(resolvedPath)).isSymbolicLink()) - return { error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.` }; - return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; - } catch {} - await fs.mkdir(path$1.dirname(resolvedPath), { recursive: true }); - if (SUPPORTS_NOFOLLOW) { - const flags = fs$1.constants.O_WRONLY | fs$1.constants.O_CREAT | fs$1.constants.O_TRUNC | fs$1.constants.O_NOFOLLOW; - const fd = await fs.open(resolvedPath, flags, 420); - try { - if (isBinary) { - const buffer = Buffer.from(content, "base64"); - await fd.writeFile(buffer); - } else - await fd.writeFile(content, "utf-8"); - } finally { - await fd.close(); - } - } else if (isBinary) { - const buffer = Buffer.from(content, "base64"); - await fs.writeFile(resolvedPath, buffer); - } else - await fs.writeFile(resolvedPath, content, "utf-8"); - return { - path: filePath, - filesUpdate: null - }; - } catch (e) { - return { error: `Error writing file '${filePath}': ${e.message}` }; + unwrap() { + return this._def.innerType; } - } - async edit(filePath, oldString, newString, replaceAll = false) { - try { - const resolvedPath = this.resolvePath(filePath); - let content; - if (SUPPORTS_NOFOLLOW) { - if (!(await fs.stat(resolvedPath)).isFile()) - return { error: `Error: File '${filePath}' not found` }; - const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); - try { - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - const stat4 = await fs.lstat(resolvedPath); - if (stat4.isSymbolicLink()) - return { error: `Error: Symlinks are not allowed: ${filePath}` }; - if (!stat4.isFile()) - return { error: `Error: File '${filePath}' not found` }; - content = await fs.readFile(resolvedPath, "utf-8"); + }; + ZodOptional4.create = (type, params) => { + return new ZodOptional4({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodOptional, + ...processCreateParams2(params) + }); + }; + ZodNullable4 = class ZodNullable4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 === ZodParsedType2.null) { + return OK2(null); } - const result = performStringReplacement(content, oldString, newString, replaceAll); - if (typeof result === "string") - return { error: result }; - const [newContent, occurrences] = result; - if (SUPPORTS_NOFOLLOW) { - const flags = fs$1.constants.O_WRONLY | fs$1.constants.O_TRUNC | fs$1.constants.O_NOFOLLOW; - const fd = await fs.open(resolvedPath, flags); - try { - await fd.writeFile(newContent, "utf-8"); - } finally { - await fd.close(); - } - } else - await fs.writeFile(resolvedPath, newContent, "utf-8"); - return { - path: filePath, - filesUpdate: null, - occurrences - }; - } catch (e) { - return { error: `Error editing file '${filePath}': ${e.message}` }; - } - } - async grep(pattern, dirPath = "/", glob = null) { - let baseFull; - try { - baseFull = this.resolvePath(dirPath || "."); - } catch { - return { matches: [] }; + return this._def.innerType._parse(input); } - try { - await fs.stat(baseFull); - } catch { - return { matches: [] }; + unwrap() { + return this._def.innerType; } - let results = await this.ripgrepSearch(pattern, baseFull, glob); - if (results === null) - results = await this.literalSearch(pattern, baseFull, glob); - const matches = []; - for (const [fpath, items] of Object.entries(results)) - for (const [lineNum, lineText] of items) - matches.push({ - path: fpath, - line: lineNum, - text: lineText - }); - return { matches }; - } - async ripgrepSearch(pattern, baseFull, includeGlob) { - return new Promise((resolve2) => { - const args = ["--json", "-F"]; - if (includeGlob) - args.push("--glob", includeGlob); - args.push("--", pattern, baseFull); - const proc = spawn("rg", args, { timeout: 30000 }); - const results = {}; - let output = ""; - proc.stdout.on("data", (data) => { - output += data.toString(); - }); - proc.on("close", (code) => { - if (code !== 0 && code !== 1) { - resolve2(null); - return; - } - for (const line of output.split(` -`)) { - if (!line.trim()) - continue; - try { - const data = JSON.parse(line); - if (data.type !== "match") - continue; - const pdata = data.data || {}; - const ftext = pdata.path?.text; - if (!ftext) - continue; - let virtPath; - if (this.virtualMode) - try { - const resolved = path$1.resolve(ftext); - const relative2 = path$1.relative(this.cwd, resolved); - if (relative2.startsWith("..")) - continue; - virtPath = "/" + relative2.split(path$1.sep).join("/"); - } catch { - continue; - } - else - virtPath = ftext; - const ln = pdata.line_number; - const lt = pdata.lines?.text?.replace(/\n$/, "") || ""; - if (ln === undefined) - continue; - if (!results[virtPath]) - results[virtPath] = []; - results[virtPath].push([ln, lt]); - } catch { - continue; - } - } - resolve2(results); - }); - proc.on("error", () => { - resolve2(null); - }); - }); - } - async literalSearch(pattern, baseFull, includeGlob) { - const results = {}; - const files = await import_fast_glob.default("**/*", { - cwd: (await fs.stat(baseFull)).isDirectory() ? baseFull : path$1.dirname(baseFull), - absolute: true, - onlyFiles: true, - dot: true + }; + ZodNullable4.create = (type, params) => { + return new ZodNullable4({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodNullable, + ...processCreateParams2(params) }); - for (const fp of files) - try { - if (!isTextMimeType(getMimeType(fp))) - continue; - if (includeGlob && !import_micromatch.default.isMatch(path$1.basename(fp), includeGlob)) - continue; - if ((await fs.stat(fp)).size > this.maxFileSizeBytes) - continue; - const lines = (await fs.readFile(fp, "utf-8")).split(` -`); - for (let i = 0;i < lines.length; i++) { - const line = lines[i]; - if (line.includes(pattern)) { - let virtPath; - if (this.virtualMode) - try { - const relative2 = path$1.relative(this.cwd, fp); - if (relative2.startsWith("..")) - continue; - virtPath = "/" + relative2.split(path$1.sep).join("/"); - } catch { - continue; - } - else - virtPath = fp; - if (!results[virtPath]) - results[virtPath] = []; - results[virtPath].push([i + 1, line]); - } - } - } catch { - continue; + }; + ZodDefault4 = class ZodDefault4 extends ZodType4 { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType2.undefined) { + data = this._def.defaultValue(); } - return results; - } - async glob(pattern, searchPath = "/") { - if (pattern.startsWith("/")) - pattern = pattern.substring(1); - const resolvedSearchPath = searchPath === "/" ? this.cwd : this.resolvePath(searchPath); - try { - if (!(await fs.stat(resolvedSearchPath)).isDirectory()) - return { files: [] }; - } catch { - return { files: [] }; - } - const results = []; - try { - const matches = await import_fast_glob.default(pattern, { - cwd: resolvedSearchPath, - absolute: true, - onlyFiles: true, - dot: true + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx }); - for (const matchedPath of matches) - try { - const stat4 = await fs.stat(matchedPath); - if (!stat4.isFile()) - continue; - const normalizedPath = matchedPath.split("/").join(path$1.sep); - if (!this.virtualMode) - results.push({ - path: normalizedPath, - is_dir: false, - size: stat4.size, - modified_at: stat4.mtime.toISOString() - }); - else { - const cwdStr = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; - let relativePath; - if (normalizedPath.startsWith(cwdStr)) - relativePath = normalizedPath.substring(cwdStr.length); - else if (normalizedPath.startsWith(this.cwd)) - relativePath = normalizedPath.substring(this.cwd.length).replace(/^[/\\]/, ""); - else - relativePath = normalizedPath; - relativePath = relativePath.split(path$1.sep).join("/"); - const virt = "/" + relativePath; - results.push({ - path: virt, - is_dir: false, - size: stat4.size, - modified_at: stat4.mtime.toISOString() - }); - } - } catch { - continue; + } + removeDefault() { + return this._def.innerType; + } + }; + ZodDefault4.create = (type, params) => { + return new ZodDefault4({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams2(params) + }); + }; + ZodCatch4 = class ZodCatch4 extends ZodType4 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] } - } catch {} - results.sort((a, b) => a.path.localeCompare(b.path)); - return { files: results }; - } - async uploadFiles(files) { - const responses = []; - for (const [filePath, content] of files) - try { - const resolvedPath = this.resolvePath(filePath); - await fs.mkdir(path$1.dirname(resolvedPath), { recursive: true }); - await fs.writeFile(resolvedPath, content); - responses.push({ - path: filePath, - error: null - }); - } catch (e) { - if (e.code === "ENOENT") - responses.push({ - path: filePath, - error: "file_not_found" - }); - else if (e.code === "EACCES") - responses.push({ - path: filePath, - error: "permission_denied" - }); - else if (e.code === "EISDIR") - responses.push({ - path: filePath, - error: "is_directory" - }); - else - responses.push({ - path: filePath, - error: "invalid_path" - }); - } - return responses; - } - async downloadFiles(paths) { - const responses = []; - for (const filePath of paths) - try { - const resolvedPath = this.resolvePath(filePath); - const content = await fs.readFile(resolvedPath); - responses.push({ - path: filePath, - content, - error: null + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync2(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError5(newCtx.common.issues); + }, + input: newCtx.data + }) + }; }); - } catch (e) { - if (e.code === "ENOENT") - responses.push({ - path: filePath, - content: null, - error: "file_not_found" - }); - else if (e.code === "EACCES") - responses.push({ - path: filePath, - content: null, - error: "permission_denied" - }); - else if (e.code === "EISDIR") - responses.push({ - path: filePath, - content: null, - error: "is_directory" - }); - else - responses.push({ - path: filePath, - content: null, - error: "invalid_path" - }); - } - return responses; - } -}, URL_COMMIT_SUFFIX_RE, TEXT_MIME_TYPE = "text/plain", FNMATCH_OPTIONS, ContextHubBackend = class ContextHubBackend2 { - identifier; - client; - cache = null; - linkedEntries = {}; - commitHash = null; - constructor(identifier, options = {}) { - this.identifier = identifier; - this.client = options.client ?? new Client; - } - static stripPrefix(path3) { - return path3.replace(/^\/+/, ""); - } - static toHubUnavailableError(error51) { - return `Hub unavailable: ${getErrorMessage(error51)}`; - } - async loadTree() { - let context2; - try { - context2 = await this.client.pullAgent(this.identifier); - } catch (error51) { - if (isLangSmithNotFoundError2(error51)) { - this.cache = {}; - this.linkedEntries = {}; - this.commitHash = null; - return; + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError5(newCtx.common.issues); + }, + input: newCtx.data + }) + }; } - throw error51; } - this.commitHash = context2.commit_hash; - this.cache = {}; - this.linkedEntries = {}; - for (const [path3, entry] of Object.entries(context2.files)) - if (entry.type === "file") - this.cache[path3] = entry.content; - else if ((entry.type === "agent" || entry.type === "skill") && typeof entry.repo_handle === "string") - this.linkedEntries[path3] = entry.repo_handle; - } - async ensureCache() { - if (this.cache === null) - await this.loadTree(); - if (this.cache === null) - throw new Error("Context Hub cache failed to initialize"); - return this.cache; - } - async commit(files) { - if (Object.keys(files).length === 0) - return; - const payload = {}; - for (const [path3, content] of Object.entries(files)) - payload[path3] = { - type: "file", - content - }; - const url2 = await this.client.pushAgent(this.identifier, { - files: payload, - ...this.commitHash ? { parentCommit: this.commitHash } : {} - }); - const match2 = URL_COMMIT_SUFFIX_RE.exec(url2); - if (match2) - this.commitHash = match2[1]; - if (this.cache !== null) - for (const [path3, content] of Object.entries(files)) - this.cache[path3] = content; - } - async getLinkedEntries() { - await this.ensureCache(); - return { ...this.linkedEntries }; - } - async hasPriorCommits() { - await this.ensureCache(); - return this.commitHash !== null; - } - async ls(path3 = "/") { - const hubPrefix = ContextHubBackend2.stripPrefix(path3).replace(/\/+$/, ""); - let cache2; - try { - cache2 = await this.ensureCache(); - } catch (error51) { - if (isLangSmithError(error51)) - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; - throw error51; + removeCatch() { + return this._def.innerType; } - const dirs = /* @__PURE__ */ new Set; - const entries = []; - for (const filePath of Object.keys(cache2)) { - if (hubPrefix && !filePath.startsWith(`${hubPrefix}/`)) - continue; - const relative2 = hubPrefix ? filePath.slice(hubPrefix.length + 1) : filePath; - if (!relative2) - continue; - const slashIndex = relative2.indexOf("/"); - if (slashIndex === -1) { - entries.push({ - path: `/${filePath}`, - is_dir: false - }); - continue; - } - const dirName = relative2.slice(0, slashIndex); - const dirPath = hubPrefix ? `${hubPrefix}/${dirName}` : dirName; - if (!dirs.has(dirPath)) { - dirs.add(dirPath); - entries.push({ - path: `/${dirPath}`, - is_dir: true + }; + ZodCatch4.create = (type, params) => { + return new ZodCatch4({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams2(params) + }); + }; + ZodNaN4 = class ZodNaN4 extends ZodType4 { + _parse(input) { + const parsedType5 = this._getType(input); + if (parsedType5 !== ZodParsedType2.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode4.invalid_type, + expected: ZodParsedType2.nan, + received: ctx.parsedType }); + return INVALID2; } + return { status: "valid", value: input.data }; } - return { files: entries }; - } - async read(filePath, offset = 0, limit = 2000) { - const hubPath = ContextHubBackend2.stripPrefix(filePath); - let cache2; - try { - cache2 = await this.ensureCache(); - } catch (error51) { - if (isLangSmithError(error51)) - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; - throw error51; + }; + ZodNaN4.create = (params) => { + return new ZodNaN4({ + typeName: ZodFirstPartyTypeKind3.ZodNaN, + ...processCreateParams2(params) + }); + }; + BRAND2 = Symbol("zod_brand"); + ZodBranded2 = class ZodBranded2 extends ZodType4 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); } - const content = cache2[hubPath]; - if (content === undefined) - return { error: `File '${filePath}' not found` }; - const sliced = sliceReadContent(content, offset, limit); - if (sliced.error) - return { error: sliced.error }; - return { - content: sliced.content ?? "", - mimeType: TEXT_MIME_TYPE - }; - } - async readRaw(filePath) { - const readResult = await this.read(filePath, 0, Number.MAX_SAFE_INTEGER); - if (readResult.error || typeof readResult.content !== "string") - return { error: readResult.error ?? `File '${filePath}' not found` }; - const now = (/* @__PURE__ */ new Date()).toISOString(); - return { data: { - content: readResult.content, - mimeType: TEXT_MIME_TYPE, - created_at: now, - modified_at: now - } }; - } - async grep(pattern, path3 = null, glob = null) { - let cache2; - try { - cache2 = await this.ensureCache(); - } catch (error51) { - if (isLangSmithError(error51)) - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; - throw error51; + unwrap() { + return this._def.type; } - const prefix = path3 ? ContextHubBackend2.stripPrefix(path3).replace(/\/+$/, "") : ""; - const matches = []; - for (const [filePath, content] of Object.entries(cache2)) { - if (prefix && !filePath.startsWith(prefix)) - continue; - if (glob && !import_micromatch.default.isMatch(filePath, glob, FNMATCH_OPTIONS)) - continue; - const lines = content.split(` -`); - for (let index2 = 0;index2 < lines.length; index2++) { - const line = lines[index2]; - if (line.includes(pattern)) - matches.push({ - path: `/${filePath}`, - line: index2 + 1, - text: line + }; + ZodPipeline2 = class ZodPipeline2 extends ZodType4 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx }); - } - } - return { matches }; - } - async glob(pattern, _path = "/") { - let cache2; - try { - cache2 = await this.ensureCache(); - } catch (error51) { - if (isLangSmithError(error51)) - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; - throw error51; - } - const files = []; - for (const filePath of Object.keys(cache2)) - if (import_micromatch.default.isMatch(`/${filePath}`, pattern, FNMATCH_OPTIONS) || import_micromatch.default.isMatch(filePath, pattern, FNMATCH_OPTIONS)) - files.push({ - path: `/${filePath}`, - is_dir: false + if (inResult.status === "aborted") + return INVALID2; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY2(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx }); - return { files }; - } - async write(filePath, content) { - const hubPath = ContextHubBackend2.stripPrefix(filePath); - try { - await this.ensureCache(); - await this.commit({ [hubPath]: content }); - } catch (error51) { - if (isLangSmithError(error51)) { - this.cache = null; - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; + if (inResult.status === "aborted") + return INVALID2; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } } - throw error51; } - return { - path: filePath, - filesUpdate: null - }; - } - async edit(filePath, oldString, newString, replaceAll = false) { - const hubPath = ContextHubBackend2.stripPrefix(filePath); - try { - const current = (await this.ensureCache())[hubPath]; - if (current === undefined) - return { error: `Error: File '${filePath}' not found` }; - const replacementResult = performStringReplacement(current, oldString, newString, replaceAll); - if (typeof replacementResult === "string") - return { error: replacementResult }; - const [newContent, occurrences] = replacementResult; - await this.commit({ [hubPath]: newContent }); - return { - path: filePath, - filesUpdate: null, - occurrences - }; - } catch (error51) { - if (isLangSmithError(error51)) { - this.cache = null; - return { error: ContextHubBackend2.toHubUnavailableError(error51) }; - } - throw error51; + static create(a, b) { + return new ZodPipeline2({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind3.ZodPipeline + }); } - } - async uploadFiles(files) { - const decoder = new TextDecoder("utf-8", { fatal: true }); - const decoded = []; - const validFiles = {}; - for (const [path3, content] of files) - try { - const text = decoder.decode(content); - decoded.push([path3, text]); - validFiles[ContextHubBackend2.stripPrefix(path3)] = text; - } catch { - decoded.push([path3, null]); - } - let commitError = null; - if (Object.keys(validFiles).length > 0) - try { - await this.ensureCache(); - await this.commit(validFiles); - } catch (error51) { - if (isLangSmithError(error51)) { - this.cache = null; - commitError = mapHubFileOperationError(error51); - } else - throw error51; - } - return decoded.map(([path3, text]) => { - if (text === null) - return { - path: path3, - error: "invalid_path" - }; - if (commitError !== null) - return { - path: path3, - error: commitError - }; - return { - path: path3, - error: null + }; + ZodReadonly4 = class ZodReadonly4 extends ZodType4 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid2(data)) { + data.value = Object.freeze(data.value); + } + return data; }; + return isAsync2(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } + }; + ZodReadonly4.create = (type, params) => { + return new ZodReadonly4({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodReadonly, + ...processCreateParams2(params) }); - } - async downloadFiles(paths) { - let cache2; - try { - cache2 = await this.ensureCache(); - } catch (error51) { - if (isLangSmithError(error51)) { - const mappedError = mapHubFileOperationError(error51); - return paths.map((path3) => ({ - path: path3, - content: null, - error: mappedError - })); + }; + late2 = { + object: ZodObject4.lazycreate + }; + (function(ZodFirstPartyTypeKind4) { + ZodFirstPartyTypeKind4["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind4["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind4["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind4["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind4["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind4["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind4["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind4["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind4["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind4["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind4["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind4["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind4["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind4["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind4["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind4["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind4["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind4["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind4["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind4["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind4["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind4["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind4["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind4["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind4["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind4["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind4["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind4["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind4["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind4["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind4["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind4["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind4["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind4["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind4["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind4["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); + stringType2 = ZodString4.create; + numberType2 = ZodNumber4.create; + nanType2 = ZodNaN4.create; + bigIntType2 = ZodBigInt4.create; + booleanType2 = ZodBoolean4.create; + dateType2 = ZodDate4.create; + symbolType2 = ZodSymbol4.create; + undefinedType2 = ZodUndefined4.create; + nullType2 = ZodNull4.create; + anyType2 = ZodAny4.create; + unknownType2 = ZodUnknown4.create; + neverType2 = ZodNever4.create; + voidType2 = ZodVoid4.create; + arrayType2 = ZodArray4.create; + objectType2 = ZodObject4.create; + strictObjectType2 = ZodObject4.strictCreate; + unionType2 = ZodUnion4.create; + discriminatedUnionType2 = ZodDiscriminatedUnion4.create; + intersectionType2 = ZodIntersection4.create; + tupleType2 = ZodTuple4.create; + recordType2 = ZodRecord4.create; + mapType2 = ZodMap4.create; + setType2 = ZodSet4.create; + functionType2 = ZodFunction3.create; + lazyType2 = ZodLazy4.create; + literalType2 = ZodLiteral4.create; + enumType2 = ZodEnum4.create; + nativeEnumType2 = ZodNativeEnum2.create; + promiseType2 = ZodPromise4.create; + effectsType2 = ZodEffects2.create; + optionalType2 = ZodOptional4.create; + nullableType2 = ZodNullable4.create; + preprocessType2 = ZodEffects2.createWithPreprocess; + pipelineType2 = ZodPipeline2.create; + coerce2 = { + string: (arg) => ZodString4.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber4.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean4.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt4.create({ ...arg, coerce: true }), + date: (arg) => ZodDate4.create({ ...arg, coerce: true }) + }; + NEVER4 = INVALID2; +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/external.js +var exports_external4 = {}; +__export(exports_external4, { + void: () => voidType2, + util: () => util3, + unknown: () => unknownType2, + union: () => unionType2, + undefined: () => undefinedType2, + tuple: () => tupleType2, + transformer: () => effectsType2, + symbol: () => symbolType2, + string: () => stringType2, + strictObject: () => strictObjectType2, + setErrorMap: () => setErrorMap4, + set: () => setType2, + record: () => recordType2, + quotelessJson: () => quotelessJson2, + promise: () => promiseType2, + preprocess: () => preprocessType2, + pipeline: () => pipelineType2, + ostring: () => ostring2, + optional: () => optionalType2, + onumber: () => onumber2, + oboolean: () => oboolean2, + objectUtil: () => objectUtil2, + object: () => objectType2, + number: () => numberType2, + nullable: () => nullableType2, + null: () => nullType2, + never: () => neverType2, + nativeEnum: () => nativeEnumType2, + nan: () => nanType2, + map: () => mapType2, + makeIssue: () => makeIssue2, + literal: () => literalType2, + lazy: () => lazyType2, + late: () => late2, + isValid: () => isValid2, + isDirty: () => isDirty2, + isAsync: () => isAsync2, + isAborted: () => isAborted2, + intersection: () => intersectionType2, + instanceof: () => instanceOfType2, + getParsedType: () => getParsedType4, + getErrorMap: () => getErrorMap4, + function: () => functionType2, + enum: () => enumType2, + effect: () => effectsType2, + discriminatedUnion: () => discriminatedUnionType2, + defaultErrorMap: () => en_default4, + datetimeRegex: () => datetimeRegex2, + date: () => dateType2, + custom: () => custom4, + coerce: () => coerce2, + boolean: () => booleanType2, + bigint: () => bigIntType2, + array: () => arrayType2, + any: () => anyType2, + addIssueToContext: () => addIssueToContext2, + ZodVoid: () => ZodVoid4, + ZodUnknown: () => ZodUnknown4, + ZodUnion: () => ZodUnion4, + ZodUndefined: () => ZodUndefined4, + ZodType: () => ZodType4, + ZodTuple: () => ZodTuple4, + ZodTransformer: () => ZodEffects2, + ZodSymbol: () => ZodSymbol4, + ZodString: () => ZodString4, + ZodSet: () => ZodSet4, + ZodSchema: () => ZodType4, + ZodRecord: () => ZodRecord4, + ZodReadonly: () => ZodReadonly4, + ZodPromise: () => ZodPromise4, + ZodPipeline: () => ZodPipeline2, + ZodParsedType: () => ZodParsedType2, + ZodOptional: () => ZodOptional4, + ZodObject: () => ZodObject4, + ZodNumber: () => ZodNumber4, + ZodNullable: () => ZodNullable4, + ZodNull: () => ZodNull4, + ZodNever: () => ZodNever4, + ZodNativeEnum: () => ZodNativeEnum2, + ZodNaN: () => ZodNaN4, + ZodMap: () => ZodMap4, + ZodLiteral: () => ZodLiteral4, + ZodLazy: () => ZodLazy4, + ZodIssueCode: () => ZodIssueCode4, + ZodIntersection: () => ZodIntersection4, + ZodFunction: () => ZodFunction3, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind3, + ZodError: () => ZodError5, + ZodEnum: () => ZodEnum4, + ZodEffects: () => ZodEffects2, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, + ZodDefault: () => ZodDefault4, + ZodDate: () => ZodDate4, + ZodCatch: () => ZodCatch4, + ZodBranded: () => ZodBranded2, + ZodBoolean: () => ZodBoolean4, + ZodBigInt: () => ZodBigInt4, + ZodArray: () => ZodArray4, + ZodAny: () => ZodAny4, + Schema: () => ZodType4, + ParseStatus: () => ParseStatus2, + OK: () => OK2, + NEVER: () => NEVER4, + INVALID: () => INVALID2, + EMPTY_PATH: () => EMPTY_PATH2, + DIRTY: () => DIRTY2, + BRAND: () => BRAND2 +}); +var init_external4 = __esm(() => { + init_errors10(); + init_parseUtil2(); + init_typeAliases2(); + init_util4(); + init_types15(); + init_ZodError2(); +}); + +// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/index.js +var init_v32 = __esm(() => { + init_external4(); + init_external4(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/messages_annotation.js +var MessagesAnnotation2, MessagesZodMeta2, MessagesZodState2; +var init_messages_annotation2 = __esm(() => { + init_annotation3(); + init_messages_reducer2(); + init_meta2(); + init_v32(); + MessagesAnnotation2 = Annotation2.Root({ messages: Annotation2({ + reducer: messagesStateReducer2, + default: () => [] + }) }); + MessagesZodMeta2 = { + reducer: { fn: messagesStateReducer2 }, + jsonSchemaExtra: { langgraph_type: "messages" }, + default: () => [] + }; + MessagesZodState2 = exports_external4.object({ messages: withLangGraph2(exports_external4.custom(), MessagesZodMeta2) }); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/writer.js +var init_writer2 = __esm(() => { + init_singletons(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/graph/index.js +var init_graph5 = __esm(() => { + init_constants5(); + init_annotation3(); + init_graph4(); + init_messages_reducer2(); + init_state4(); + init_message3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/web.js +var init_web2 = __esm(() => { + init_constants5(); + init_errors9(); + init_base16(); + init_binop2(); + init_annotation3(); + init_config3(); + init_stream_channel2(); + init_convert2(); + init_lifecycle2(); + init_messages5(); + init_subgraphs2(); + init_values3(); + init_types11(); + init_run_stream2(); + init_stream7(); + init_interrupt2(); + init_graph4(); + init_types13(); + init_adapter2(); + init_untracked_value2(); + init_channels2(); + init_reduced2(); + init_untracked2(); + init_schema2(); + init_messages_reducer2(); + init_messages7(); + init_state3(); + init_state4(); + init_message3(); + init_graph5(); + init_func2(); + init_messages_annotation2(); + init_writer2(); + init_dist3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph@1.3.2_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_ca6hmgycr5afcjmu3hi37bkcii/node_modules/@langchain/langgraph/dist/index.js +var init_dist6 = __esm(() => { + init_async_local_storage3(); + init_constants5(); + init_errors9(); + init_base16(); + init_binop2(); + init_annotation3(); + init_config3(); + init_stream_channel2(); + init_convert2(); + init_lifecycle2(); + init_messages5(); + init_subgraphs2(); + init_values3(); + init_types11(); + init_run_stream2(); + init_stream7(); + init_interrupt2(); + init_graph4(); + init_types13(); + init_adapter2(); + init_untracked_value2(); + init_reduced2(); + init_untracked2(); + init_schema2(); + init_messages_reducer2(); + init_messages7(); + init_state4(); + init_message3(); + init_func2(); + init_messages_annotation2(); + init_writer2(); + init_web2(); + initializeAsyncLocalStorageSingleton2(); +}); + +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/utils.js +var require_utils = __commonJS((exports) => { + exports.isInteger = (num) => { + if (typeof num === "number") { + return Number.isInteger(num); + } + if (typeof num === "string" && num.trim() !== "") { + return Number.isInteger(Number(num)); + } + return false; + }; + exports.find = (node, type) => node.nodes.find((node2) => node2.type === type); + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) + return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) + return false; + return (Number(max) - Number(min)) / Number(step) >= limit; + }; + exports.escapeNode = (block, n4 = 0, type) => { + const node = block.nodes[n4]; + if (!node) + return; + if (type && node.type === type || node.type === "open" || node.type === "close") { + if (node.escaped !== true) { + node.value = "\\" + node.value; + node.escaped = true; } - throw error51; } - const encoder2 = new TextEncoder; - return paths.map((path3) => { - const hubPath = ContextHubBackend2.stripPrefix(path3); - const content = cache2[hubPath]; - if (content !== undefined) - return { - path: path3, - content: encoder2.encode(content), - error: null - }; - return { - path: path3, - content: null, - error: "file_not_found" - }; - }); - } -}, LocalShellBackend, STAT_C_SCRIPT = 'for f; do if [ -d "$f" ]; then t=d; elif [ -L "$f" ]; then t=l; else t=f; fi; sz=$(stat -c %s "$f" 2>/dev/null) || continue; mt=$(stat -c %Y "$f" 2>/dev/null) || continue; printf "%s\\t%s\\t%s\\t%s\\n" "$sz" "$mt" "$t" "$f"; done', BaseSandbox = class { - async ls(path3) { - const command = buildLsCommand(path3); - const result = await this.execute(command); - const infos = []; - const lines = result.output.trim().split(` -`).filter(Boolean); - for (const line of lines) { - const parsed = parseStatLine(line); - if (!parsed) - continue; - infos.push({ - path: parsed.isDir ? parsed.fullPath + "/" : parsed.fullPath, - is_dir: parsed.isDir, - size: parsed.size, - modified_at: (/* @__PURE__ */ new Date(parsed.mtime * 1000)).toISOString() - }); + }; + exports.encloseBrace = (node) => { + if (node.type !== "brace") + return false; + if (node.commas >> 0 + node.ranges >> 0 === 0) { + node.invalid = true; + return true; } - return { files: infos }; - } - async read(filePath, offset = 0, limit = 500) { - const mimeType = getMimeType(filePath); - if (!isTextMimeType(mimeType)) { - const results = await this.downloadFiles([filePath]); - if (results[0].error || !results[0].content) - return { error: `File '${filePath}' not found` }; - return { - content: results[0].content, - mimeType - }; + return false; + }; + exports.isInvalidBrace = (block) => { + if (block.type !== "brace") + return false; + if (block.invalid === true || block.dollar) + return true; + if (block.commas >> 0 + block.ranges >> 0 === 0) { + block.invalid = true; + return true; } - if (limit === 0) - return { - content: "", - mimeType - }; - const command = buildReadCommand(filePath, offset, limit); - const result = await this.execute(command); - if (result.exitCode !== 0) - return { error: `File '${filePath}' not found` }; - return { - content: result.output, - mimeType + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; + }; + exports.isOpenOrClose = (node) => { + if (node.type === "open" || node.type === "close") { + return true; + } + return node.open === true || node.close === true; + }; + exports.reduce = (nodes) => nodes.reduce((acc, node) => { + if (node.type === "text") + acc.push(node.value); + if (node.type === "range") + node.type = "text"; + return acc; + }, []); + exports.flatten = (...args) => { + const result = []; + const flat = (arr3) => { + for (let i = 0;i < arr3.length; i++) { + const ele = arr3[i]; + if (Array.isArray(ele)) { + flat(ele); + continue; + } + if (ele !== undefined) { + result.push(ele); + } + } + return result; + }; + flat(args); + return result; + }; +}); + +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/stringify.js +var require_stringify2 = __commonJS((exports, module) => { + var utils = require_utils(); + module.exports = (ast, options = {}) => { + const stringify5 = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ""; + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return "\\" + node.value; + } + return node.value; + } + if (node.value) { + return node.value; + } + if (node.nodes) { + for (const child of node.nodes) { + output += stringify5(child); + } + } + return output; }; + return stringify5(ast); + }; +}); + +// ../../node_modules/.pnpm/is-number@7.0.0/node_modules/is-number/index.js +var require_is_number = __commonJS((exports, module) => { + /*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + module.exports = function(num) { + if (typeof num === "number") { + return num - num === 0; + } + if (typeof num === "string" && num.trim() !== "") { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; + }; +}); + +// ../../node_modules/.pnpm/to-regex-range@5.0.1/node_modules/to-regex-range/index.js +var require_to_regex_range = __commonJS((exports, module) => { + /*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + var isNumber = require_is_number(); + var toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError("toRegexRange: expected the first argument to be a number"); + } + if (max === undefined || min === max) { + return String(min); + } + if (isNumber(max) === false) { + throw new TypeError("toRegexRange: expected the second argument to be a number."); + } + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === "boolean") { + opts.relaxZeros = opts.strictZeros === false; + } + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap4 = String(opts.wrap); + let cacheKey2 = min + ":" + max + "=" + relax + shorthand + capture + wrap4; + if (toRegexRange.cache.hasOwnProperty(cacheKey2)) { + return toRegexRange.cache[cacheKey2].result; + } + let a = Math.min(min, max); + let b = Math.max(min, max); + if (Math.abs(a - b) === 1) { + let result = min + "|" + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && positives.length + negatives.length > 1) { + state.result = `(?:${state.result})`; + } + toRegexRange.cache[cacheKey2] = state; + return state.result; + }; + function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, "-", false, options) || []; + let onlyPositive = filterPatterns(pos, neg, "", false, options) || []; + let intersected = filterPatterns(neg, pos, "-?", true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join("|"); } - async readRaw(filePath) { - const results = await this.downloadFiles([filePath]); - if (results[0].error || !results[0].content) - return { error: `File '${filePath}' not found` }; - const now = (/* @__PURE__ */ new Date()).toISOString(); - const mimeType = getMimeType(filePath); - if (!isTextMimeType(mimeType)) - return { data: { - content: results[0].content, - mimeType, - created_at: now, - modified_at: now - } }; - return { data: { - content: new TextDecoder().decode(results[0].content), - mimeType, - created_at: now, - modified_at: now - } }; + function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + let stop = countNines(min, nines); + let stops = new Set([max]); + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + stop = countZeros(max + 1, zeros) - 1; + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + stops = [...stops]; + stops.sort(compare2); + return stops; } - async grep(pattern, path3 = "/", glob = null) { - const command = buildGrepCommand(pattern, path3, glob); - const output = (await this.execute(command)).output.trim(); - if (!output) - return { matches: [] }; - const matches = []; - for (const line of output.split(` -`)) { - const parts = line.split(":"); - if (parts.length >= 3) { - const filePath = parts[0]; - if (!isTextMimeType(getMimeType(filePath))) - continue; - const lineNum = parseInt(parts[1], 10); - if (!isNaN(lineNum)) - matches.push({ - path: filePath, - line: lineNum, - text: parts.slice(2).join(":") - }); + function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ""; + let count = 0; + for (let i = 0;i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + if (startDigit === stopDigit) { + pattern += startDigit; + } else if (startDigit !== "0" || stopDigit !== "9") { + pattern += toCharacterClass(startDigit, stopDigit, options); + } else { + count++; } } - return { matches }; + if (count) { + pattern += options.shorthand === true ? "\\d" : "[0-9]"; + } + return { pattern, count: [count], digits }; } - async glob(pattern, path3 = "/") { - const command = buildFindCommand(path3); - const result = await this.execute(command); - const regex2 = globToPathRegex(pattern); - const infos = []; - const lines = result.output.trim().split(` -`).filter(Boolean); - const basePath = path3.endsWith("/") ? path3.slice(0, -1) : path3; - for (const line of lines) { - const parsed = parseStatLine(line); - if (!parsed) + function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + for (let i = 0;i < ranges.length; i++) { + let max2 = ranges[i]; + let obj = rangeToPattern(String(start), String(max2), options); + let zeros = ""; + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max2 + 1; continue; - const relPath = parsed.fullPath.startsWith(basePath + "/") ? parsed.fullPath.slice(basePath.length + 1) : parsed.fullPath; - if (regex2.test(relPath)) - infos.push({ - path: relPath, - is_dir: parsed.isDir, - size: parsed.size, - modified_at: (/* @__PURE__ */ new Date(parsed.mtime * 1000)).toISOString() - }); + } + if (tok.isPadded) { + zeros = padZeros(max2, tok, options); + } + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max2 + 1; + prev = obj; } - return { files: infos }; + return tokens; } - async write(filePath, content) { - try { - const existCheck = await this.downloadFiles([filePath]); - if (existCheck[0].content !== null && existCheck[0].error === null) - return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; - } catch {} - const mimeType = getMimeType(filePath); - let fileContent; - if (isTextMimeType(mimeType)) - fileContent = new TextEncoder().encode(content); - else - fileContent = Buffer.from(content, "base64"); - const results = await this.uploadFiles([[filePath, fileContent]]); - if (results[0].error) - return { error: `Failed to write to ${filePath}: ${results[0].error}` }; - return { - path: filePath, - filesUpdate: null - }; + function filterPatterns(arr3, comparison, prefix, intersection3, options) { + let result = []; + for (let ele of arr3) { + let { string: string7 } = ele; + if (!intersection3 && !contains(comparison, "string", string7)) { + result.push(prefix + string7); + } + if (intersection3 && contains(comparison, "string", string7)) { + result.push(prefix + string7); + } + } + return result; } - async edit(filePath, oldString, newString, replaceAll = false) { - const results = await this.downloadFiles([filePath]); - if (results[0].error || !results[0].content) - return { error: `Error: File '${filePath}' not found` }; - const text = new TextDecoder().decode(results[0].content); - results[0].content = null; - if (oldString.length === 0) { - if (text.length !== 0) - return { error: "oldString must not be empty unless the file is empty" }; - if (newString.length === 0) - return { - path: filePath, - filesUpdate: null, - occurrences: 0 - }; - const encoded2 = new TextEncoder().encode(newString); - const uploadResults2 = await this.uploadFiles([[filePath, encoded2]]); - if (uploadResults2[0].error) - return { error: `Failed to write edited file '${filePath}': ${uploadResults2[0].error}` }; - return { - path: filePath, - filesUpdate: null, - occurrences: 1 - }; + function zip(a, b) { + let arr3 = []; + for (let i = 0;i < a.length; i++) + arr3.push([a[i], b[i]]); + return arr3; + } + function compare2(a, b) { + return a > b ? 1 : b > a ? -1 : 0; + } + function contains(arr3, key, val) { + return arr3.some((ele) => ele[key] === val); + } + function countNines(min, len) { + return Number(String(min).slice(0, -len) + "9".repeat(len)); + } + function countZeros(integer3, zeros) { + return integer3 - integer3 % Math.pow(10, zeros); + } + function toQuantifier(digits) { + let [start = 0, stop = ""] = digits; + if (stop || start > 1) { + return `{${start + (stop ? "," + stop : "")}}`; } - const firstIdx = text.indexOf(oldString); - if (firstIdx === -1) - return { error: `String not found in file '${filePath}'` }; - if (oldString === newString) - return { - path: filePath, - filesUpdate: null, - occurrences: 1 - }; - let newText; - let count; - if (replaceAll) { - newText = text.replaceAll(oldString, newString); - const lenDiff = oldString.length - newString.length; - if (lenDiff !== 0) - count = (text.length - newText.length) / lenDiff; - else { - count = 1; - let pos = firstIdx + oldString.length; - while (pos <= text.length) { - const idx = text.indexOf(oldString, pos); - if (idx === -1) - break; - count++; - pos = idx + oldString.length; - } + return ""; + } + function toCharacterClass(a, b, options) { + return `[${a}${b - a === 1 ? "" : "-"}${b}]`; + } + function hasPadding(str) { + return /^-?(0+)\d/.test(str); + } + function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + switch (diff) { + case 0: + return ""; + case 1: + return relax ? "0?" : "0"; + case 2: + return relax ? "0{0,2}" : "00"; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; } - } else { - if (text.indexOf(oldString, firstIdx + oldString.length) !== -1) - return { error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.` }; - count = 1; - newText = text.slice(0, firstIdx) + newString + text.slice(firstIdx + oldString.length); } - const encoded = new TextEncoder().encode(newText); - const uploadResults = await this.uploadFiles([[filePath, encoded]]); - if (uploadResults[0].error) - return { error: `Failed to write edited file '${filePath}': ${uploadResults[0].error}` }; - return { - path: filePath, - filesUpdate: null, - occurrences: count - }; } -}, LangSmithSandbox, CONFIGURATION_ERROR_SYMBOL, ConfigurationError, REQUIRED_MIDDLEWARE_NAMES, EMPTY_HARNESS_PROFILE, POISONED_KEYS, generalPurposeSubagentConfigSchema, harnessProfileConfigSchema, SYSTEM_PROMPT_SUFFIX$3 = ` -If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. - - - -Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. - - - -After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. - - - -When a task depends on the state of files, tests, or system output, use tools to observe that state directly rather than reasoning from memory about what it probably contains. Read files before describing them. Run tests before claiming they pass. Search the codebase before asserting a symbol does or does not exist. Active investigation with tools is the default mode of working, not a fallback. - - - -Do not spawn a subagent for work you can complete directly in a single response (e.g. refactoring a function you can already see). - -Spawn multiple subagents in the same turn when fanning out across items or reading multiple files. -`, SYSTEM_PROMPT_SUFFIX$2 = ` -If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. - - - -Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. - - - -After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. -`, SYSTEM_PROMPT_SUFFIX$1 = ` -If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. - - - -Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. - - - -After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. -`, CODEX_MODEL_SPECS, SYSTEM_PROMPT_SUFFIX = `## Codex-Specific Behavior - -- You are an autonomous senior engineer. Once given a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. -- Persist until the task is fully handled end-to-end within the current turn whenever feasible. Do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes. -- Bias to action: default to implementing with reasonable assumptions. Do not end your turn with clarifications unless truly blocked. -- Do not communicate an upfront plan or status preamble before acting. Just act. - -## Parallel Tool Use - -- Before any tool call, decide ALL files and resources you will need. -- Batch reads, searches, and other independent operations into parallel tool calls instead of issuing them one at a time. -- Only make sequential calls when you truly cannot determine the next step without seeing a prior result. - -## Plan Hygiene - -- Before finishing, reconcile every TODO or plan item created via write_todos. Mark each as done, blocked (with a one-sentence reason), or cancelled. Do not finish with pending items.`, PROFILE_REGISTRY_KEY, BASE_AGENT_PROMPT, BUILTIN_TOOL_NAMES, AgentMemoryStateSchema, DEFAULT_MEMORY_TEMPLATE = ` -{user_memory} - - - -{project_memory} -`, LONGTERM_MEMORY_SYSTEM_PROMPT = ` - -## Long-term Memory - -Your long-term memory is stored in files on the filesystem and persists across sessions. - -**User Memory Location**: \`{agent_dir_absolute}\` (displays as \`{agent_dir_display}\`) -**Project Memory Location**: {project_memory_info} - -Your system prompt is loaded from TWO sources at startup: -1. **User agent.md**: \`{agent_dir_absolute}/agent.md\` - Your personal preferences across all projects -2. **Project agent.md**: Loaded from project root if available - Project-specific instructions - -Project-specific agent.md is loaded from these locations (both combined if both exist): -- \`[project-root]/.deepagents/agent.md\` (preferred) -- \`[project-root]/agent.md\` (fallback, but also included if both exist) - -**When to CHECK/READ memories (CRITICAL - do this FIRST):** -- **At the start of ANY new session**: Check both user and project memories - - User: \`ls {agent_dir_absolute}\` - - Project: \`ls {project_deepagents_dir}\` (if in a project) -- **BEFORE answering questions**: If asked "what do you know about X?" or "how do I do Y?", check project memories FIRST, then user -- **When user asks you to do something**: Check if you have project-specific guides or examples -- **When user references past work**: Search project memory files for related context - -**Memory-first response pattern:** -1. User asks a question → Check project directory first: \`ls {project_deepagents_dir}\` -2. If relevant files exist → Read them with \`read_file '{project_deepagents_dir}/[filename]'\` -3. Check user memory if needed → \`ls {agent_dir_absolute}\` -4. Base your answer on saved knowledge supplemented by general knowledge - -**When to update memories:** -- **IMMEDIATELY when the user describes your role or how you should behave** -- **IMMEDIATELY when the user gives feedback on your work** - Update memories to capture what was wrong and how to do it better -- When the user explicitly asks you to remember something -- When patterns or preferences emerge (coding styles, conventions, workflows) -- After significant work where context would help in future sessions - -**Learning from feedback:** -- When user says something is better/worse, capture WHY and encode it as a pattern -- Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions -- When user says "you should remember X" or "be careful about Y", treat this as HIGH PRIORITY - update memories IMMEDIATELY -- Look for the underlying principle behind corrections, not just the specific mistake - -## Deciding Where to Store Memory - -When writing or updating agent memory, decide whether each fact, configuration, or behavior belongs in: - -### User Agent File: \`{agent_dir_absolute}/agent.md\` -→ Describes the agent's **personality, style, and universal behavior** across all projects. - -**Store here:** -- Your general tone and communication style -- Universal coding preferences (formatting, comment style, etc.) -- General workflows and methodologies you follow -- Tool usage patterns that apply everywhere -- Personal preferences that don't change per-project - -**Examples:** -- "Be concise and direct in responses" -- "Always use type hints in Python" -- "Prefer functional programming patterns" - -### Project Agent File: \`{project_deepagents_dir}/agent.md\` -→ Describes **how this specific project works** and **how the agent should behave here only.** - -**Store here:** -- Project-specific architecture and design patterns -- Coding conventions specific to this codebase -- Project structure and organization -- Testing strategies for this project -- Deployment processes and workflows -- Team conventions and guidelines - -**Examples:** -- "This project uses FastAPI with SQLAlchemy" -- "Tests go in tests/ directory mirroring src/ structure" -- "All API changes require updating OpenAPI spec" - -### Project Memory Files: \`{project_deepagents_dir}/*.md\` -→ Use for **project-specific reference information** and structured notes. - -**Store here:** -- API design documentation -- Architecture decisions and rationale -- Deployment procedures -- Common debugging patterns -- Onboarding information - -**Examples:** -- \`{project_deepagents_dir}/api-design.md\` - REST API patterns used -- \`{project_deepagents_dir}/architecture.md\` - System architecture overview -- \`{project_deepagents_dir}/deployment.md\` - How to deploy this project - -### File Operations: - -**User memory:** -\`\`\` -ls {agent_dir_absolute} # List user memory files -read_file '{agent_dir_absolute}/agent.md' # Read user preferences -edit_file '{agent_dir_absolute}/agent.md' ... # Update user preferences -\`\`\` - -**Project memory (preferred for project-specific information):** -\`\`\` -ls {project_deepagents_dir} # List project memory files -read_file '{project_deepagents_dir}/agent.md' # Read project instructions -edit_file '{project_deepagents_dir}/agent.md' ... # Update project instructions -write_file '{project_deepagents_dir}/agent.md' ... # Create project memory file -\`\`\` + toRegexRange.cache = {}; + toRegexRange.clearCache = () => toRegexRange.cache = {}; + module.exports = toRegexRange; +}); -**Important**: -- Project memory files are stored in \`.deepagents/\` inside the project root -- Always use absolute paths for file operations -- Check project memories BEFORE user when answering project-specific questions`, MAX_SKILL_DESCRIPTION_LENGTH$1 = 1024, SKILL_NAME_PATTERN, FRONTMATTER_PATTERN; -var init_dist8 = __esm(() => { - init_dist5(); - init_dist4(); - init_v43(); - init_messages(); - init_zod(); - init_zod(); - init_dist7(); - init_errors3(); - init_universal(); - init_langsmith(); - init_sandbox3(); - import_micromatch = __toESM(require_micromatch(), 1); - import_yaml = __toESM(require_dist3(), 1); - import_fast_glob = __toESM(require_out4(), 1); - MIME_TYPES = { - ".png": "image/png", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".gif": "image/gif", - ".webp": "image/webp", - ".svg": "image/svg+xml", - ".heic": "image/heic", - ".heif": "image/heif", - ".mp3": "audio/mpeg", - ".wav": "audio/wav", - ".aiff": "audio/aiff", - ".aac": "audio/aac", - ".ogg": "audio/ogg", - ".flac": "audio/flac", - ".mp4": "video/mp4", - ".webm": "video/webm", - ".mpeg": "video/mpeg", - ".mov": "video/quicktime", - ".avi": "video/x-msvideo", - ".flv": "video/x-flv", - ".mpg": "video/mpeg", - ".wmv": "video/x-ms-wmv", - ".3gpp": "video/3gpp", - ".pdf": "application/pdf", - ".ppt": "application/vnd.ms-powerpoint", - ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation" - }; - SANDBOX_ERROR_SYMBOL = Symbol.for("sandbox.error"); - SandboxError = class SandboxError2 extends Error { - [SANDBOX_ERROR_SYMBOL] = true; - name = "SandboxError"; - constructor(message, code, cause) { - super(message); - this.code = code; - this.cause = cause; - Object.setPrototypeOf(this, SandboxError2.prototype); - } - static isInstance(error51) { - return typeof error51 === "object" && error51 !== null && error51[SANDBOX_ERROR_SYMBOL] === true; - } - }; - INT_FORMATTER = new Intl.NumberFormat("en-US"); - FILESYSTEM_TOOL_NAMES = [ - "ls", - "read_file", - "write_file", - "edit_file", - "glob", - "grep", - "execute" - ]; - TOOLS_EXCLUDED_FROM_EVICTION = [ - "ls", - "glob", - "grep", - "read_file", - "edit_file", - "write_file" - ]; - MAX_BINARY_READ_SIZE_BYTES = 10 * 1024 * 1024; - TOO_LARGE_TOOL_MSG = context` - Tool result too large, the result of this tool call {tool_call_id} was saved in the filesystem at this path: {file_path} - You can read the result from the filesystem by using the read_file tool, but make sure to only read part of the result at a time. - You can do this by specifying an offset and limit in the read_file tool call. - For example, to read the first ${100} lines, you can use the read_file tool with offset=0 and limit=${100}. - - Here is a preview showing the head and tail of the result (lines of the form - ... [N lines truncated] ... - indicate omitted lines in the middle of the content): - - {content_sample} -`; - FileDataV1Schema = exports_external.object({ - content: exports_external.array(exports_external.string()), - created_at: exports_external.string(), - modified_at: exports_external.string() - }); - FileDataV2Schema = exports_external.object({ - content: exports_external.union([exports_external.string(), exports_external.instanceof(Uint8Array)]), - mimeType: exports_external.string(), - created_at: exports_external.string(), - modified_at: exports_external.string() - }); - FileDataSchema = exports_external.union([FileDataV1Schema, FileDataV2Schema]); - FilesystemStateSchema = new StateSchema({ files: new ReducedValue(exports_external.record(exports_external.string(), FileDataSchema).default(() => ({})), { - inputSchema: exports_external.record(exports_external.string(), FileDataSchema.nullable()).optional(), - reducer: fileDataReducer - }) }); - FILESYSTEM_SYSTEM_PROMPT = context` - ## Following Conventions - - - Read files before editing — understand existing content before making changes - - Mimic existing style, naming conventions, and patterns - - ## Filesystem Tools \`ls\`, \`read_file\`, \`write_file\`, \`edit_file\`, \`glob\`, \`grep\` - - You have access to a filesystem which you can interact with using these tools. - All file paths must start with a /. - - - ls: list files in a directory (requires absolute path) - - read_file: read a file from the filesystem - - write_file: write to a file in the filesystem - - edit_file: edit a file in the filesystem - - glob: find files matching a pattern (e.g., "**/*.py") - - grep: search for text within files -`; - LS_TOOL_DESCRIPTION = context` - Lists all files in a directory. - - This is useful for exploring the filesystem and finding the right file to read or edit. - You should almost ALWAYS use this tool before using the read_file or edit_file tools. -`; - READ_FILE_TOOL_DESCRIPTION = context` - Reads a file from the filesystem. - - Assume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned. - - Usage: - - By default, it reads up to ${100} lines starting from the beginning of the file - - **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow - - First scan: read_file(path, limit=${100}) to see file structure - - Read more sections: read_file(path, offset=${100}, limit=200) for next 200 lines - - Only omit limit (read full file) when necessary for editing - - Specify offset and limit: read_file(path, offset=0, limit=${100}) reads first ${100} lines - - Results are returned using cat -n format, with line numbers starting at 1 -- Lines longer than ${INT_FORMATTER.format(MAX_LINE_LENGTH)} characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). When you specify a limit, these continuation lines count towards the limit. - - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. - - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents. - - You should ALWAYS make sure a file has been read before editing it. -`; - WRITE_FILE_TOOL_DESCRIPTION = context` - Writes to a new file in the filesystem. - - Usage: - - The write_file tool will create a new file. - - Prefer to edit existing files (with the edit_file tool) over creating new ones when possible. -`; - EDIT_FILE_TOOL_DESCRIPTION = context` - Performs exact string replacements in files. - - Usage: - - You must read the file before editing. This tool will error if you attempt an edit without reading the file first. - - When editing, preserve the exact indentation (tabs/spaces) from the read output. Never include line number prefixes in old_string or new_string. - - ALWAYS prefer editing existing files over creating new ones. - - Only use emojis if the user explicitly requests it. -`; - GLOB_TOOL_DESCRIPTION = context` - Find files matching a glob pattern. - - Supports standard glob patterns: \`*\` (any characters), \`**\` (any directories), \`?\` (single character). - Returns a list of absolute file paths that match the pattern. - - Examples: - - \`**/*.py\` - Find all Python files - - \`*.txt\` - Find all text files in root - - \`/subdir/**/*.md\` - Find all markdown files under /subdir -`; - GREP_TOOL_DESCRIPTION = context` - Search for a text pattern across files. - - Searches for literal text (not regex) and returns matching files or content based on output_mode. - Special characters like parentheses, brackets, pipes, etc. are treated as literal characters, not regex operators. - - Examples: - - Search all files: \`grep(pattern="TODO")\` - - Search Python files only: \`grep(pattern="import", glob="*.py")\` - - Show matching lines: \`grep(pattern="error", output_mode="content")\` - - Search for code with special chars: \`grep(pattern="def __init__(self):")\` -`; - EXECUTE_TOOL_DESCRIPTION = context` - Executes a shell command in an isolated sandbox environment. - - Usage: - Executes a given command in the sandbox environment with proper handling and security measures. - Before executing the command, please follow these steps: - - 1. Directory Verification: - - If the command will create new directories or files, first use the ls tool to verify the parent directory exists and is the correct location - - For example, before running "mkdir foo/bar", first use ls to check that "foo" exists and is the intended parent directory - - 2. Command Execution: - - Always quote file paths that contain spaces with double quotes (e.g., cd "path with spaces/file.txt") - - Examples of proper quoting: - - cd "/Users/name/My Documents" (correct) - - cd /Users/name/My Documents (incorrect - will fail) - - python "/path/with spaces/script.py" (correct) - - python /path/with spaces/script.py (incorrect - will fail) - - After ensuring proper quoting, execute the command - - Capture the output of the command - - Usage notes: - - Commands run in an isolated sandbox environment - - Returns combined stdout/stderr output with exit code - - If the output is very large, it may be truncated - - VERY IMPORTANT: You MUST avoid using search commands like find and grep. Instead use the grep, glob tools to search. You MUST avoid read tools like cat, head, tail, and use read_file to read files. - - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings) - - Use '&&' when commands depend on each other (e.g., "mkdir dir && cd dir") - - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail - - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd - - Examples: - Good examples: - - execute(command="pytest /foo/bar/tests") - - execute(command="python /path/to/script.py") - - execute(command="npm install && npm test") - - Bad examples (avoid these): - - execute(command="cd /foo/bar && pytest tests") # Use absolute path instead - - execute(command="cat file.txt") # Use read_file tool instead - - execute(command="find . -name '*.py'") # Use glob tool instead - - execute(command="grep -r 'pattern' .") # Use grep tool instead - - Note: This tool is only available if the backend supports execution (SandboxBackendProtocol). - If execution is not supported, the tool will return an error message. -`; - EXECUTION_SYSTEM_PROMPT = context` - ## Execute Tool \`execute\` - - You have access to an \`execute\` tool for running shell commands in a sandboxed environment. - Use this tool to run commands, scripts, tests, builds, and other shell operations. - - - execute: run a shell command in the sandbox (returns output and exit code) -`; - EXCLUDED_STATE_KEYS = [ - "messages", - "todos", - "structuredResponse", - "skillsMetadata", - "memoryContents" - ]; - TASK_SYSTEM_PROMPT = context` - ## \`task\` (subagent spawner) - - You have access to a \`task\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result. - - When to use the task tool: - - When a task is complex and multi-step, and can be fully delegated in isolation - - When a task is independent of other tasks and can run in parallel - - When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread - - When sandboxing improves reliability (e.g. code execution, structured searches, data formatting) - - When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.) - - Subagent lifecycle: - 1. **Spawn** → Provide clear role, instructions, and expected output - 2. **Run** → The subagent completes the task autonomously - 3. **Return** → The subagent provides a single structured result - 4. **Reconcile** → Incorporate or synthesize the result into the main thread - - When NOT to use the task tool: - - If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them) - - If the task is trivial (a few tool calls or simple lookup) - - If delegating does not reduce token usage, complexity, or context switching - - If splitting would add latency without benefit - - ## Important Task Tool Usage Notes to Remember - - Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important. - - Remember to use the \`task\` tool to silo independent tasks within a multi-part objective. - - You should use the \`task\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient. -`; - GENERAL_PURPOSE_SUBAGENT = { - name: "general-purpose", - description: DEFAULT_GENERAL_PURPOSE_DESCRIPTION, - systemPrompt: DEFAULT_SUBAGENT_PROMPT +// ../../node_modules/.pnpm/fill-range@7.1.1/node_modules/fill-range/index.js +var require_fill_range = __commonJS((exports, module) => { + /*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + var util5 = __require("util"); + var toRegexRange = require_to_regex_range(); + var isObject4 = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + var transform3 = (toNumber) => { + return (value) => toNumber === true ? Number(value) : String(value); }; - INVALID_TOOL_MESSAGE_BLOCK_TYPES = [ - "tool_use", - "thinking", - "redacted_thinking" - ]; - filesValue = new ReducedValue(exports_external.record(exports_external.string(), FileDataSchema).default(() => ({})), { - inputSchema: exports_external.record(exports_external.string(), FileDataSchema.nullable()).optional(), - reducer: fileDataReducer - }); - MemoryStateSchema = new StateSchema({ - memoryContents: exports_external.record(exports_external.string(), exports_external.string()).optional(), - files: filesValue - }); - MEMORY_SYSTEM_PROMPT = context` - - {memory_contents} - - - - The above was loaded in from files in your filesystem. As you learn from your interactions with the user, you can save new knowledge by calling the \`edit_file\` tool. - - **Learning from feedback:** - - One of your MAIN PRIORITIES is to learn from your interactions with the user. These learnings can be implicit or explicit. This means that in the future, you will remember this important information. - - When you need to remember something, updating memory must be your FIRST, IMMEDIATE action - before responding to the user, before calling other tools, before doing anything else. Just update memory immediately. - - When user says something is better/worse, capture WHY and encode it as a pattern. - - Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions. - - A great opportunity to update your memories is when the user interrupts a tool call and provides feedback. You should update your memories immediately before revising the tool call. - - Look for the underlying principle behind corrections, not just the specific mistake. - - The user might not explicitly ask you to remember something, but if they provide information that is useful for future use, you should update your memories immediately. - - **Asking for information:** - - If you lack context to perform an action (e.g. send a Slack DM, requires a user ID/email) you should explicitly ask the user for this information. - - It is preferred for you to ask for information, don't assume anything that you do not know! - - When the user provides information that is useful for future use, you should update your memories immediately. - - **When to update memories:** - - When the user explicitly asks you to remember something (e.g., "remember my email", "save this preference") - - When the user describes your role or how you should behave (e.g., "you are a web researcher", "always do X") - - When the user gives feedback on your work - capture what was wrong and how to improve - - When the user provides information required for tool use (e.g., slack channel ID, email addresses) - - When the user provides context useful for future tasks, such as how to use tools, or which actions to take in a particular situation - - When you discover new patterns or preferences (coding styles, conventions, workflows) - - **When to NOT update memories:** - - When the information is temporary or transient (e.g., "I'm running late", "I'm on my phone right now") - - When the information is a one-time task request (e.g., "Find me a recipe", "What's 25 * 4?") - - When the information is a simple question that doesn't reveal lasting preferences (e.g., "What day is it?", "Can you explain X?") - - When the information is an acknowledgment or small talk (e.g., "Sounds good!", "Hello", "Thanks for that") - - When the information is stale or irrelevant in future conversations - - Never store API keys, access tokens, passwords, or any other credentials in any file, memory, or system prompt. - - If the user asks where to put API keys or provides an API key, do NOT echo or save it. - - **Examples:** - Example 1 (remembering user information): - User: Can you connect to my google account? - Agent: Sure, I'll connect to your google account, what's your google account email? - User: john@example.com - Agent: Let me save this to my memory. - Tool Call: edit_file(...) -> remembers that the user's google account email is john@example.com - - Example 2 (remembering implicit user preferences): - User: Can you write me an example for creating a deep agent in LangChain? - Agent: Sure, I'll write you an example for creating a deep agent in LangChain - User: Can you do this in JavaScript - Agent: Let me save this to my memory. - Tool Call: edit_file(...) -> remembers that the user prefers to get LangChain code examples in JavaScript - Agent: Sure, here is the JavaScript example - - Example 3 (do not remember transient information): - User: I'm going to play basketball tonight so I will be offline for a few hours. - Agent: Okay I'll add a block to your calendar. - Tool Call: create_calendar_event(...) -> just calls a tool, does not commit anything to memory, as it is transient information - -`; - MAX_SKILL_FILE_SIZE = 10 * 1024 * 1024; - SKILL_MODULE_EXTENSIONS = [ - ".js", - ".mjs", - ".cjs", - ".ts", - ".mts", - ".cts", - ".jsx", - ".tsx" - ]; - SkillMetadataEntrySchema = exports_external.object({ - name: exports_external.string(), - description: exports_external.string(), - path: exports_external.string(), - license: exports_external.string().nullable().optional(), - compatibility: exports_external.string().nullable().optional(), - metadata: exports_external.record(exports_external.string(), exports_external.string()).optional(), - allowedTools: exports_external.array(exports_external.string()).optional(), - module: exports_external.string().optional() - }); - SkillsStateSchema = new StateSchema({ - skillsMetadata: new ReducedValue(exports_external.array(SkillMetadataEntrySchema).default(() => []), { - inputSchema: exports_external.array(SkillMetadataEntrySchema).optional(), - reducer: skillsMetadataReducer - }), - files: filesValue - }); - SKILLS_SYSTEM_PROMPT = context` - ## Skills System - - You have access to a skills library that provides specialized capabilities and domain knowledge. - - {skills_locations} - - **Available Skills:** - - {skills_list} - - **How to Use Skills (Progressive Disclosure):** - - Skills follow a **progressive disclosure** pattern - you know they exist (name + description above), but you only read the full instructions when needed: - - 1. **Recognize when a skill applies**: Check if the user's task matches any skill's description - 2. **Read the skill's full instructions**: Use \`read_file\` on the path shown in the skill list above. - Pass \`limit=${DEFAULT_SKILL_READ_LINE_LIMIT}\` since the default of ${100} lines is too small for most skill files. - 3. **Follow the skill's instructions**: SKILL.md contains step-by-step workflows, best practices, and examples - 4. **Access supporting files**: Skills may include scripts, configs, or reference docs - use absolute paths - - **When to Use Skills:** - - When the user's request matches a skill's domain (e.g., "research X" → web-research skill) - - When you need specialized knowledge or structured workflows - - When a skill provides proven patterns for complex tasks - - **Skills are Self-Documenting:** - - Each SKILL.md tells you exactly what the skill does and how to use it - - The skill list above shows the full path for each skill's SKILL.md file - - **Executing Skill Scripts:** - Skills may contain scripts or other executable files. Always use absolute paths from the skill list. - - **Example Workflow:** - - User: "Can you research the latest developments in quantum computing?" - - 1. Check available skills above → See "web-research" skill with its full path - 2. Read the full skill file: \`read_file(path, limit=${DEFAULT_SKILL_READ_LINE_LIMIT})\` - 3. Follow the skill's research workflow (search → organize → synthesize) - 4. Use any helper scripts with absolute paths - - Remember: Skills are tools to make you more capable and consistent. When in doubt, check if a skill exists for the task! -`; - CompletionCallbackStateSchema = object({ - [CALLBACK_THREAD_ID_KEY]: string2().optional() - }); - FALLBACK_TRIGGER = { - type: "tokens", - value: 170000 + var isValidValue = (value) => { + return typeof value === "number" || typeof value === "string" && value !== ""; }; - FALLBACK_KEEP = { - type: "messages", - value: 6 + var isNumber = (num) => Number.isInteger(+num); + var zeros = (input) => { + let value = `${input}`; + let index2 = -1; + if (value[0] === "-") + value = value.slice(1); + if (value === "0") + return false; + while (value[++index2] === "0") + ; + return index2 > 0; }; - FALLBACK_TRUNCATE_ARGS = { - trigger: { - type: "messages", - value: 20 - }, - keep: { - type: "messages", - value: 20 + var stringify5 = (start, end, options) => { + if (typeof start === "string" || typeof end === "string") { + return true; } + return options.stringify === true; }; - PROFILE_TRIGGER = { - type: "fraction", - value: 0.85 - }; - PROFILE_KEEP = { - type: "fraction", - value: 0.1 + var pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === "-" ? "-" : ""; + if (dash) + input = input.slice(1); + input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0"); + } + if (toNumber === false) { + return String(input); + } + return input; }; - PROFILE_TRUNCATE_ARGS = { - trigger: { - type: "fraction", - value: 0.85 - }, - keep: { - type: "fraction", - value: 0.1 + var toMaxLen = (input, maxLength) => { + let negative = input[0] === "-" ? "-" : ""; + if (negative) { + input = input.slice(1); + maxLength--; } + while (input.length < maxLength) + input = "0" + input; + return negative ? "-" + input : input; }; - SummarizationEventSchema = exports_external.object({ - cutoffIndex: exports_external.number(), - summaryMessage: exports_external.instanceof(HumanMessage), - filePath: exports_external.string().nullable() - }); - SummarizationStateSchema = exports_external.object({ - _summarizationSessionId: exports_external.string().optional(), - _summarizationEvent: SummarizationEventSchema.optional() - }); - AsyncTaskSchema = exports_external.object({ - taskId: exports_external.string(), - agentName: exports_external.string(), - threadId: exports_external.string(), - runId: exports_external.string(), - status: exports_external.string(), - createdAt: exports_external.string(), - description: exports_external.string().optional(), - updatedAt: exports_external.string().optional(), - checkedAt: exports_external.string().optional() - }); - AsyncTaskStateSchema = new StateSchema({ asyncTasks: new ReducedValue(exports_external.record(exports_external.string(), AsyncTaskSchema).default(() => ({})), { - inputSchema: exports_external.record(exports_external.string(), AsyncTaskSchema).optional(), - reducer: asyncTasksReducer - }) }); - ASYNC_TASK_TOOL_NAMES = [ - "start_async_task", - "check_async_task", - "update_async_task", - "cancel_async_task", - "list_async_tasks" - ]; - TERMINAL_STATUSES = new Set([ - "cancelled", - "success", - "error", - "timeout", - "interrupted" - ]); - NAMESPACE_COMPONENT_RE = /^[A-Za-z0-9\-_.@+:~]+$/; - SUPPORTS_NOFOLLOW = fs$1.constants.O_NOFOLLOW !== undefined; - URL_COMMIT_SUFFIX_RE = /:([0-9a-f]{8,64})$/i; - FNMATCH_OPTIONS = { bash: true }; - LocalShellBackend = class LocalShellBackend2 extends FilesystemBackend { - #timeout; - #maxOutputBytes; - #env; - #sandboxId; - #initialized = false; - constructor(options = {}) { - const { rootDir, virtualMode = false, timeout = 120, maxOutputBytes = 1e5, env, inheritEnv = false } = options; - super({ - rootDir, - virtualMode, - maxFileSizeMb: 10 - }); - this.#timeout = timeout; - this.#maxOutputBytes = maxOutputBytes; - const bytes = new Uint8Array(4); - crypto.getRandomValues(bytes); - this.#sandboxId = `local-${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`; - if (inheritEnv) { - this.#env = { ...process.env }; - if (env) - Object.assign(this.#env, env); - } else - this.#env = env ?? {}; + var toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? "" : "?:"; + let positives = ""; + let negatives = ""; + let result; + if (parts.positives.length) { + positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|"); } - get id() { - return this.#sandboxId; + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`; } - get isInitialized() { - return this.#initialized; + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; } - get isRunning() { - return this.#initialized; + if (options.wrap) { + return `(${prefix}${result})`; } - async initialize() { - if (this.#initialized) - throw new SandboxError("Backend is already initialized. Each LocalShellBackend instance can only be initialized once.", "ALREADY_INITIALIZED"); - await fs.mkdir(this.cwd, { recursive: true }); - this.#initialized = true; + return result; + }; + var toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); } - async close() { - this.#initialized = false; + let start = String.fromCharCode(a); + if (a === b) + return start; + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; + }; + var toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap4 = options.wrap === true; + let prefix = options.capture ? "" : "?:"; + return wrap4 ? `(${prefix}${start.join("|")})` : start.join("|"); } - async read(filePath, offset = 0, limit = 500) { - const result = await super.read(filePath, offset, limit); - if (result.error?.includes("ENOENT")) - return { error: `File '${filePath}' not found` }; - return result; + return toRegexRange(start, end, options); + }; + var rangeError = (...args) => { + return new RangeError("Invalid range arguments: " + util5.inspect(...args)); + }; + var invalidRange = (start, end, options) => { + if (options.strictRanges === true) + throw rangeError([start, end]); + return []; + }; + var invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); } - async edit(filePath, oldString, newString, replaceAll = false) { - const result = await super.edit(filePath, oldString, newString, replaceAll); - if (result.error?.includes("ENOENT")) - return { - ...result, - error: `Error: File '${filePath}' not found` - }; - return result; + return []; + }; + var fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) + throw rangeError([start, end]); + return []; } - async ls(dirPath) { - const result = await super.ls(dirPath); - if (result.error) - return result; - if (this.virtualMode) - return result; - const cwdPrefix = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; - return { files: (result.files || []).map((info) => ({ - ...info, - path: info.path.startsWith(cwdPrefix) ? info.path.slice(cwdPrefix.length) : info.path - })) }; + if (a === 0) + a = 0; + if (b === 0) + b = 0; + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify5(start, end, options) === false; + let format3 = options.transform || transform3(toNumber); + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); } - async glob(pattern, searchPath = "/") { - if (pattern.startsWith("/")) - pattern = pattern.substring(1); - const resolvedSearchPath = searchPath === "/" || searchPath === "" ? this.cwd : this.virtualMode ? path$1.resolve(this.cwd, searchPath.replace(/^\//, "")) : path$1.resolve(this.cwd, searchPath); - try { - if (!(await fs.stat(resolvedSearchPath)).isDirectory()) - return { files: [] }; - } catch { - return { files: [] }; + let parts = { negatives: [], positives: [] }; + let push2 = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num)); + let range = []; + let index2 = 0; + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push2(a); + } else { + range.push(pad(format3(a, index2), maxLen, toNumber)); } - const formatPath = (rel) => this.virtualMode ? `/${rel}` : rel; - const globOpts = { - cwd: resolvedSearchPath, - absolute: false, - dot: true - }; - const [fileMatches, dirMatches] = await Promise.all([import_fast_glob.default(pattern, { - ...globOpts, - onlyFiles: true - }), import_fast_glob.default(pattern, { - ...globOpts, - onlyDirectories: true - })]); - const statFile = async (match2) => { - try { - const entryStat = await fs.stat(path$1.join(resolvedSearchPath, match2)); - if (entryStat.isFile()) - return { - path: formatPath(match2), - is_dir: false, - size: entryStat.size, - modified_at: entryStat.mtime.toISOString() - }; - } catch {} - return null; - }; - const statDir = async (match2) => { - try { - const entryStat = await fs.stat(path$1.join(resolvedSearchPath, match2)); - if (entryStat.isDirectory()) - return { - path: formatPath(match2), - is_dir: true, - size: 0, - modified_at: entryStat.mtime.toISOString() - }; - } catch {} - return null; - }; - const [fileInfos, dirInfos] = await Promise.all([Promise.all(fileMatches.map(statFile)), Promise.all(dirMatches.map(statDir))]); - const results = [...fileInfos, ...dirInfos].filter((info) => info !== null); - results.sort((a, b) => a.path.localeCompare(b.path)); - return { files: results }; - } - async execute(command) { - if (!command || typeof command !== "string") - return { - output: "Error: Command must be a non-empty string.", - exitCode: 1, - truncated: false - }; - return new Promise((resolve2) => { - let stdout = ""; - let stderr = ""; - let timedOut = false; - const child = cp.spawn(command, { - shell: true, - env: this.#env, - cwd: this.cwd - }); - const timer = setTimeout(() => { - timedOut = true; - child.kill("SIGTERM"); - }, this.#timeout * 1000); - child.stdout.on("data", (data) => { - stdout += data.toString(); - }); - child.stderr.on("data", (data) => { - stderr += data.toString(); - }); - child.on("error", (err) => { - clearTimeout(timer); - resolve2({ - output: `Error executing command: ${err.message}`, - exitCode: 1, - truncated: false - }); - }); - child.on("close", (code, signal) => { - clearTimeout(timer); - if (timedOut || signal === "SIGTERM") { - resolve2({ - output: `Error: Command timed out after ${this.#timeout.toFixed(1)} seconds.`, - exitCode: 124, - truncated: false - }); - return; - } - const outputParts = []; - if (stdout) - outputParts.push(stdout); - if (stderr) { - const stderrLines = stderr.trim().split(` -`); - outputParts.push(...stderrLines.map((line) => `[stderr] ${line}`)); - } - let output = outputParts.length > 0 ? outputParts.join(` -`) : ""; - let truncated = false; - if (output.length > this.#maxOutputBytes) { - output = output.slice(0, this.#maxOutputBytes); - output += ` - -... Output truncated at ${this.#maxOutputBytes} bytes.`; - truncated = true; - } - const exitCode = code ?? 1; - if (exitCode !== 0) - output = `${output.trimEnd()} - -Exit code: ${exitCode}`; - resolve2({ - output, - exitCode, - truncated - }); - }); - }); + a = descending ? a - step : a + step; + index2++; } - static async create(options = {}) { - const { initialFiles, ...backendOptions } = options; - const backend = new LocalShellBackend2(backendOptions); - await backend.initialize(); - if (initialFiles) { - const encoder2 = new TextEncoder; - const files = Object.entries(initialFiles).map(([filePath, content]) => [filePath, encoder2.encode(content)]); - await backend.uploadFiles(files); - } - return backend; + if (options.toRegex === true) { + return step > 1 ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } + return range; }; - LangSmithSandbox = class LangSmithSandbox2 extends BaseSandbox { - #sandbox; - #defaultTimeout; - #isRunning = true; - constructor(options) { - super(); - this.#sandbox = options.sandbox; - this.#defaultTimeout = options.defaultTimeout ?? 1800; - } - get isRunning() { - return this.#isRunning; - } - get id() { - return this.#sandbox.name; - } - async execute(command, options) { - const effectiveTimeout = options?.timeout !== undefined ? options.timeout : this.#defaultTimeout; - const result = await this.#sandbox.run(command, { timeout: effectiveTimeout }); - const out = result.stdout ?? ""; - return { - output: result.stderr ? out ? `${out} -${result.stderr}` : result.stderr : out, - exitCode: result.exit_code, - truncated: false - }; + var fillLetters = (start, end, step = 1, options = {}) => { + if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) { + return invalidRange(start, end, options); } - async downloadFiles(paths) { - const responses = []; - for (const path3 of paths) - try { - const content = await this.#sandbox.read(path3); - responses.push({ - path: path3, - content, - error: null - }); - } catch (err) { - if (err instanceof LangSmithResourceNotFoundError) - responses.push({ - path: path3, - content: null, - error: "file_not_found" - }); - else if (err instanceof LangSmithSandboxError) { - const error51 = String(err.message).toLowerCase().includes("is a directory") ? "is_directory" : "file_not_found"; - responses.push({ - path: path3, - content: null, - error: error51 - }); - } else - responses.push({ - path: path3, - content: null, - error: "invalid_path" - }); - } - return responses; + let format3 = options.transform || ((val) => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); } - async uploadFiles(files) { - const responses = []; - for (const [path3, content] of files) - try { - await this.#sandbox.write(path3, content); - responses.push({ - path: path3, - error: null - }); - } catch { - responses.push({ - path: path3, - error: "permission_denied" - }); - } - return responses; + let range = []; + let index2 = 0; + while (descending ? a >= b : a <= b) { + range.push(format3(a, index2)); + a = descending ? a - step : a + step; + index2++; } - async close() { - await this.#sandbox.delete(); - this.#isRunning = false; + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); } - async start(options = {}) { - await this.#sandbox.start(options); - this.#isRunning = true; + return range; + }; + var fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; } - async stop() { - await this.#sandbox.stop(); - this.#isRunning = false; + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); } - async captureSnapshot(name, options = {}) { - return this.#sandbox.captureSnapshot(name, options); + if (typeof step === "function") { + return fill(start, end, 1, { transform: step }); } - static async create(options) { - const { templateName, apiKey = process.env.LANGSMITH_API_KEY, defaultTimeout, snapshotId, ...createSandboxOptions } = options; - if (snapshotId && templateName) - throw new Error("snapshotId and templateName are mutually exclusive. Pass only one creation source."); - if (!snapshotId && !templateName) - throw new Error("Either snapshotId or templateName is required. snapshotId is recommended — template-based creation is deprecated."); - const sandboxOptions = { ...createSandboxOptions }; - if (templateName) - sandboxOptions.snapshotName = templateName; - return new LangSmithSandbox2({ - sandbox: await new SandboxClient({ apiKey }).createSandbox(snapshotId, sandboxOptions), - defaultTimeout - }); + if (isObject4(step)) { + return fill(start, end, 0, step); } - }; - CONFIGURATION_ERROR_SYMBOL = Symbol.for("deepagents.configuration_error"); - ConfigurationError = class ConfigurationError2 extends Error { - [CONFIGURATION_ERROR_SYMBOL] = true; - name = "ConfigurationError"; - constructor(message, code, cause) { - super(message); - this.code = code; - this.cause = cause; - Object.setPrototypeOf(this, ConfigurationError2.prototype); + let opts = { ...options }; + if (opts.capture === true) + opts.wrap = true; + step = step || opts.step || 1; + if (!isNumber(step)) { + if (step != null && !isObject4(step)) + return invalidStep(step, opts); + return fill(start, end, 1, step); } - static isInstance(error51) { - return typeof error51 === "object" && error51 !== null && error51[CONFIGURATION_ERROR_SYMBOL] === true; + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); } + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); }; - REQUIRED_MIDDLEWARE_NAMES = new Set(["FilesystemMiddleware", "SubAgentMiddleware"]); - EMPTY_HARNESS_PROFILE = createHarnessProfile(); - POISONED_KEYS = new Set([ - "__proto__", - "constructor", - "prototype" - ]); - generalPurposeSubagentConfigSchema = exports_external.object({ - enabled: exports_external.boolean().optional(), - description: exports_external.string().optional(), - systemPrompt: exports_external.string().optional() - }).strict(); - harnessProfileConfigSchema = exports_external.object({ - baseSystemPrompt: exports_external.string().optional(), - systemPromptSuffix: exports_external.string().optional(), - toolDescriptionOverrides: exports_external.record(exports_external.string(), exports_external.string()).optional(), - excludedTools: exports_external.array(exports_external.string()).optional(), - excludedMiddleware: exports_external.array(exports_external.string()).optional(), - generalPurposeSubagent: generalPurposeSubagentConfigSchema.optional() - }).strict(); - CODEX_MODEL_SPECS = [ - "openai:gpt-5.1-codex", - "openai:gpt-5.2-codex", - "openai:gpt-5.3-codex" - ]; - PROFILE_REGISTRY_KEY = Symbol.for("deepagents.harness-profiles.v1"); - BASE_AGENT_PROMPT = context` - You are a Deep Agent, an AI assistant that helps users accomplish tasks using tools. You respond with text and tool calls. The user can see your responses and tool outputs in real time. - - ## Core Behavior - - - Be concise and direct. Don't over-explain unless asked. - - NEVER add unnecessary preamble (\"Sure!\", \"Great question!\", \"I'll now...\"). - - Don't say \"I'll now do X\" — just do it. - - If the request is ambiguous, ask questions before acting. - - If asked how to approach something, explain first, then act. - - ## Professional Objectivity - - - Prioritize accuracy over validating the user's beliefs - - Disagree respectfully when the user is incorrect - - Avoid unnecessary superlatives, praise, or emotional validation - - ## Doing Tasks - - When the user asks you to do something: - - 1. **Understand first** — read relevant files, check existing patterns. Quick but thorough — gather enough evidence to start, then iterate. - 2. **Act** — implement the solution. Work quickly but accurately. - 3. **Verify** — check your work against what was asked, not against your own output. Your first attempt is rarely correct — iterate. - - Keep working until the task is fully complete. Don't stop partway and explain what you would do — just do it. Only yield back to the user when the task is done or you're genuinely blocked. - - **When things go wrong:** - - If something fails repeatedly, stop and analyze *why* — don't keep retrying the same approach. - - If you're blocked, tell the user what's wrong and ask for guidance. - - ## Progress Updates + module.exports = fill; +}); - For longer tasks, provide brief progress updates at reasonable intervals — a concise sentence recapping what you've done and what's next. -`; - BUILTIN_TOOL_NAMES = new Set([ - ...FILESYSTEM_TOOL_NAMES, - ...ASYNC_TASK_TOOL_NAMES, - "task", - "write_todos" - ]); - AgentMemoryStateSchema = exports_external.object({ - userMemory: exports_external.string().optional(), - projectMemory: exports_external.string().optional() - }); - SKILL_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/; - FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/; +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/compile.js +var require_compile = __commonJS((exports, module) => { + var fill = require_fill_range(); + var utils = require_utils(); + var compile = (ast, options = {}) => { + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? "\\" : ""; + let output = ""; + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + console.log("node.isClose", prefix, node.value); + return prefix + node.value; + } + if (node.type === "open") { + return invalid ? prefix + node.value : "("; + } + if (node.type === "close") { + return invalid ? prefix + node.value : ")"; + } + if (node.type === "comma") { + return node.prev.type === "comma" ? "" : invalid ? node.value : "|"; + } + if (node.value) { + return node.value; + } + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + if (node.nodes) { + for (const child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + return walk(ast); + }; + module.exports = compile; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/output_parsers.js -function extractToolCalls2(content) { - const toolCalls = []; - for (const block of content) - if (block.type === "tool_use") - toolCalls.push({ - name: block.name, - args: block.input, - id: block.id, - type: "tool_call" - }); - return toolCalls; -} -var AnthropicToolsOutputParser; -var init_output_parsers3 = __esm(() => { - init_types3(); - init_output_parsers(); - AnthropicToolsOutputParser = class extends BaseLLMOutputParser { - static lc_name() { - return "AnthropicToolsOutputParser"; - } - lc_namespace = [ - "langchain", - "anthropic", - "output_parsers" - ]; - returnId = false; - keyName; - returnSingle = false; - zodSchema; - serializableSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - this.serializableSchema = params.serializableSchema; +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/expand.js +var require_expand = __commonJS((exports, module) => { + var fill = require_fill_range(); + var stringify5 = require_stringify2(); + var utils = require_utils(); + var append = (queue2 = "", stash = "", enclose = false) => { + const result = []; + queue2 = [].concat(queue2); + stash = [].concat(stash); + if (!stash.length) + return queue2; + if (!queue2.length) { + return enclose ? utils.flatten(stash).map((ele) => `{${ele}}`) : stash; } - async _validateResult(result) { - let parsedResult = result; - if (typeof result === "string") - try { - parsedResult = JSON.parse(result); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); + for (const item of queue2) { + if (Array.isArray(item)) { + for (const value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === "string") + ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } - else - parsedResult = result; - if (this.serializableSchema !== undefined) { - const validated = await this.serializableSchema["~standard"].validate(parsedResult); - if (validated.issues) - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(parsedResult, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(parsedResult, null, 2)); - return validated.value; } - if (this.zodSchema === undefined) - return parsedResult; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); - if (zodParsedResult.success) - return zodParsedResult.data; - else - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); - } - async parseResult(generations) { - const tools = generations.flatMap((generation) => { - const { message } = generation; - if (!Array.isArray(message.content)) - return []; - return extractToolCalls2(message.content)[0]; - }); - if (tools[0] === undefined) - throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); - const [tool2] = tools; - return await this._validateResult(tool2.args); } + return utils.flatten(result); }; -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/tools.js -function handleToolChoice(toolChoice) { - if (!toolChoice) - return; - else if (toolChoice === "any" || toolChoice === "required") - return { type: "any" }; - else if (toolChoice === "auto") - return { type: "auto" }; - else if (toolChoice === "none") - return { type: "none" }; - else if (typeof toolChoice === "string") - return { - type: "tool", - name: toolChoice + var expand = (ast, options = {}) => { + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; + const walk = (node, parent = {}) => { + node.queue = []; + let p = parent; + let q = parent.queue; + while (p.type !== "brace" && p.type !== "root" && p.parent) { + p = p.parent; + q = p.queue; + } + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify5(node, options))); + return; + } + if (node.type === "brace" && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ["{}"])); + return; + } + if (node.nodes && node.ranges > 0) { + const args = utils.reduce(node.nodes); + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit."); + } + let range = fill(...args, options); + if (range.length === 0) { + range = stringify5(node, options); + } + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + const enclose = utils.encloseBrace(node); + let queue2 = node.queue; + let block = node; + while (block.type !== "brace" && block.type !== "root" && block.parent) { + block = block.parent; + queue2 = block.queue; + } + for (let i = 0;i < node.nodes.length; i++) { + const child = node.nodes[i]; + if (child.type === "comma" && node.type === "brace") { + if (i === 1) + queue2.push(""); + queue2.push(""); + continue; + } + if (child.type === "close") { + q.push(append(q.pop(), queue2, enclose)); + continue; + } + if (child.value && child.type !== "open") { + queue2.push(append(queue2.pop(), child.value)); + continue; + } + if (child.nodes) { + walk(child, node); + } + } + return queue2; }; - else - return toolChoice; -} -var AnthropicToolExtrasSchema, ANTHROPIC_TOOL_BETAS; -var init_tools5 = __esm(() => { - init_v43(); - AnthropicToolExtrasSchema = object({ - cache_control: custom().optional().nullable(), - defer_loading: boolean2().optional(), - input_examples: array(unknown()).optional(), - allowed_callers: array(unknown()).optional() - }); - ANTHROPIC_TOOL_BETAS = { - tool_search_tool_regex_20251119: "advanced-tool-use-2025-11-20", - tool_search_tool_bm25_20251119: "advanced-tool-use-2025-11-20", - memory_20250818: "context-management-2025-06-27", - web_fetch_20250910: "web-fetch-2025-09-10", - code_execution_20250825: "code-execution-2025-08-25", - computer_20251124: "computer-use-2025-11-24", - computer_20250124: "computer-use-2025-01-24", - mcp_toolset: "mcp-client-2025-11-20" + return utils.flatten(walk(ast)); }; + module.exports = expand; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/content.js -function _isAnthropicThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; -} -function _isAnthropicRedactedThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; -} -function _isAnthropicCompactionBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "compaction"; -} -function _isAnthropicSearchResultBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; -} -function _isAnthropicImageBlockParam(block) { - if (typeof block !== "object" || block == null) - return false; - if (!("type" in block) || block.type !== "image") - return false; - if (!("source" in block) || typeof block.source !== "object" || block.source == null) - return false; - if (!("type" in block.source)) - return false; - if (block.source.type === "base64") { - if (!("media_type" in block.source)) - return false; - if (typeof block.source.media_type !== "string") - return false; - if (!("data" in block.source)) - return false; - if (typeof block.source.data !== "string") - return false; - return true; - } - if (block.source.type === "url") { - if (!("url" in block.source)) - return false; - if (typeof block.source.url !== "string") - return false; - return true; - } - return false; -} -var standardContentBlockConverter; -var init_content2 = __esm(() => { - init_messages(); - standardContentBlockConverter = { - providerName: "anthropic", - fromStandardTextBlock(block) { - return { - type: "text", - text: block.text, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - }, - fromStandardImageBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ - dataUrl: block.url, - asTypedArray: false - }); - if (data) - return { - type: "image", - source: { - type: "base64", - data: data.data, - media_type: data.mime_type - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else - return { - type: "image", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - } else if (block.source_type === "base64") - return { - type: "image", - source: { - type: "base64", - data: block.data, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else - throw new Error(`Unsupported image source type: ${block.source_type}`); - }, - fromStandardFileBlock(block) { - const mime_type = (block.mime_type ?? "").split(";")[0]; - if (block.source_type === "url") { - if (mime_type === "application/pdf" || mime_type === "") - return { - type: "document", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); - } else if (block.source_type === "text") - if (mime_type === "text/plain" || mime_type === "") - return { - type: "document", - source: { - type: "text", - data: block.text, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else - throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); - else if (block.source_type === "base64") - if (mime_type === "application/pdf" || mime_type === "") - return { - type: "document", - source: { - type: "base64", - data: block.data, - media_type: "application/pdf" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else if ([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ].includes(mime_type)) - return { - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: block.data, - media_type: mime_type - } - }] - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else - throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); - else - throw new Error(`Unsupported file source type: ${block.source_type}`); - } +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/constants.js +var require_constants = __commonJS((exports, module) => { + module.exports = { + MAX_LENGTH: 1e4, + CHAR_0: "0", + CHAR_9: "9", + CHAR_UPPERCASE_A: "A", + CHAR_LOWERCASE_A: "a", + CHAR_UPPERCASE_Z: "Z", + CHAR_LOWERCASE_Z: "z", + CHAR_LEFT_PARENTHESES: "(", + CHAR_RIGHT_PARENTHESES: ")", + CHAR_ASTERISK: "*", + CHAR_AMPERSAND: "&", + CHAR_AT: "@", + CHAR_BACKSLASH: "\\", + CHAR_BACKTICK: "`", + CHAR_CARRIAGE_RETURN: "\r", + CHAR_CIRCUMFLEX_ACCENT: "^", + CHAR_COLON: ":", + CHAR_COMMA: ",", + CHAR_DOLLAR: "$", + CHAR_DOT: ".", + CHAR_DOUBLE_QUOTE: '"', + CHAR_EQUAL: "=", + CHAR_EXCLAMATION_MARK: "!", + CHAR_FORM_FEED: "\f", + CHAR_FORWARD_SLASH: "/", + CHAR_HASH: "#", + CHAR_HYPHEN_MINUS: "-", + CHAR_LEFT_ANGLE_BRACKET: "<", + CHAR_LEFT_CURLY_BRACE: "{", + CHAR_LEFT_SQUARE_BRACKET: "[", + CHAR_LINE_FEED: ` +`, + CHAR_NO_BREAK_SPACE: " ", + CHAR_PERCENT: "%", + CHAR_PLUS: "+", + CHAR_QUESTION_MARK: "?", + CHAR_RIGHT_ANGLE_BRACKET: ">", + CHAR_RIGHT_CURLY_BRACE: "}", + CHAR_RIGHT_SQUARE_BRACKET: "]", + CHAR_SEMICOLON: ";", + CHAR_SINGLE_QUOTE: "'", + CHAR_SPACE: " ", + CHAR_TAB: "\t", + CHAR_UNDERSCORE: "_", + CHAR_VERTICAL_LINE: "|", + CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF" }; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/index.js -var iife4 = (fn) => fn(); -var init_utils15 = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/standard.js -function _isStandardAnnotation(annotation) { - return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; -} -function _formatStandardCitations(annotations) { - function* iterateAnnotations() { - for (const annotation of annotations) - if (_isStandardAnnotation(annotation)) { - if (annotation.source === "char") - yield { - type: "char_location", - file_id: annotation.url ?? "", - start_char_index: annotation.startIndex ?? 0, - end_char_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "page") - yield { - type: "page_location", - file_id: annotation.url ?? "", - start_page_number: annotation.startIndex ?? 0, - end_page_number: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "block") - yield { - type: "content_block_location", - file_id: annotation.url ?? "", - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "url") - yield { - type: "web_search_result_location", - url: annotation.url ?? "", - title: annotation.title ?? null, - encrypted_index: String(annotation.startIndex ?? 0), - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "search") - yield { - type: "search_result_location", - title: annotation.title ?? null, - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - search_result_index: 0, - source: annotation.source ?? "", - cited_text: annotation.citedText ?? "" - }; +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/lib/parse.js +var require_parse2 = __commonJS((exports, module) => { + var stringify5 = require_stringify2(); + var { + MAX_LENGTH, + CHAR_BACKSLASH, + CHAR_BACKTICK, + CHAR_COMMA, + CHAR_DOT, + CHAR_LEFT_PARENTHESES, + CHAR_RIGHT_PARENTHESES, + CHAR_LEFT_CURLY_BRACE, + CHAR_RIGHT_CURLY_BRACE, + CHAR_LEFT_SQUARE_BRACKET, + CHAR_RIGHT_SQUARE_BRACKET, + CHAR_DOUBLE_QUOTE, + CHAR_SINGLE_QUOTE, + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE + } = require_constants(); + var parse16 = (input, options = {}) => { + if (typeof input !== "string") { + throw new TypeError("Expected a string"); + } + const opts = options || {}; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + const ast = { type: "root", input, nodes: [] }; + const stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + const length = input.length; + let index2 = 0; + let depth = 0; + let value; + const advance = () => input[index2++]; + const push2 = (node) => { + if (node.type === "text" && prev.type === "dot") { + prev.type = "text"; } - } - return Array.from(iterateAnnotations()); -} -function _formatBase64Data(data) { - if (typeof data === "string") - return data; - else - return _encodeUint8Array(data); -} -function _encodeUint8Array(data) { - const output = []; - for (let i = 0, { length } = data;i < length; i++) - output.push(String.fromCharCode(data[i])); - return btoa(output.join("")); -} -function _normalizeMimeType(mimeType) { - return (mimeType ?? "").split(";")[0].toLowerCase(); -} -function _extractMetadataValue(metadata, key) { - if (metadata !== undefined && metadata !== null && typeof metadata === "object" && key in metadata) - return metadata[key]; -} -function _applyDocumentMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== undefined) - block.cache_control = cacheControl; - const citations = _extractMetadataValue(metadata, "citations"); - if (citations !== undefined) - block.citations = citations; - const context2 = _extractMetadataValue(metadata, "context"); - if (context2 !== undefined) - block.context = context2; - const title = _extractMetadataValue(metadata, "title"); - if (title !== undefined) - block.title = title; - return block; -} -function _applyImageMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== undefined) - block.cache_control = cacheControl; - return block; -} -function _hasAllowedImageMimeType(mimeType) { - return new Set([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ]).has(mimeType); -} -function _formatStandardContent(message) { - const result = []; - const responseMetadata = message.response_metadata; - const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; - for (const block of message.contentBlocks) - if (block.type === "text") - if (block.annotations) - result.push({ - type: "text", - text: block.text, - citations: _formatStandardCitations(block.annotations) - }); - else - result.push({ - type: "text", - text: block.text - }); - else if (block.type === "tool_call") - result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name, - input: block.args - }); - else if (block.type === "tool_call_chunk") { - const input = iife4(() => { - if (typeof block.args !== "string") - return block.args; - try { - return JSON.parse(block.args); - } catch { - return {}; - } - }); - result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name ?? "", - input - }); - } else if (block.type === "reasoning" && isAnthropicMessage) - result.push({ - type: "thinking", - thinking: block.reasoning, - signature: String(block.signature) - }); - else if (block.type === "server_tool_call" && isAnthropicMessage) { - if (block.name === "web_search") - result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - else if (block.name === "code_execution") - result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { - if (block.name === "web_search" && Array.isArray(block.output.urls)) { - const content = block.output.urls.map((url2) => ({ - type: "web_search_result", - title: "", - encrypted_content: "", - url: url2 - })); - result.push({ - type: "web_search_tool_result", - tool_use_id: block.toolCallId ?? "", - content - }); - } else if (block.name === "code_execution") - result.push({ - type: "code_execution_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - else if (block.name === "mcp_tool_result") - result.push({ - type: "mcp_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - } else if (block.type === "audio") - throw new Error("Anthropic does not support audio content blocks."); - else if (block.type === "file") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); + if (prev && prev.type === "text" && node.type === "text") { + prev.value += node.value; + return; + } + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + push2({ type: "bos" }); + while (index2 < length) { + block = stack[stack.length - 1]; + value = advance(); + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { continue; } - if (block.url) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "application/pdf" || mimeType === "") { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "url", - url: block.url + if (value === CHAR_BACKSLASH) { + push2({ type: "text", value: (options.keepEscaping ? value : "") + advance() }); + continue; + } + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push2({ type: "text", value: "\\" + value }); + continue; + } + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let next; + while (index2 < length && (next = advance())) { + value += next; + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + if (brackets === 0) { + break; } - }, metadata)); - continue; + } } + push2({ type: "text", value }); + continue; } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "" || mimeType === "application/pdf") - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: "application/pdf" - } - }, metadata)); - else if (mimeType === "text/plain") - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" - } - }, metadata)); - else if (_hasAllowedImageMimeType(mimeType)) - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }] - } - }, metadata)); - else - throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); + if (value === CHAR_LEFT_PARENTHESES) { + block = push2({ type: "paren", nodes: [] }); + stack.push(block); + push2({ type: "text", value }); continue; } - throw new Error("File content block must include a fileId, url, or data property."); - } else if (block.type === "image") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== "paren") { + push2({ type: "text", value }); + continue; + } + block = stack.pop(); + push2({ type: "text", value }); + block = stack[stack.length - 1]; continue; } - if (block.url) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "url", - url: block.url + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + const open = value; + let next; + if (options.keepQuotes !== true) { + value = ""; + } + while (index2 < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; } - }, metadata)); + if (next === open) { + if (options.keepQuotes === true) + value += next; + break; + } + value += next; + } + push2({ type: "text", value }); continue; } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; - if (_hasAllowedImageMimeType(mimeType)) - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }, metadata)); + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + const dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true; + const brace = { + type: "brace", + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + block = push2(brace); + stack.push(block); + push2({ type: "open", value }); continue; } - throw new Error("Image content block must include a fileId, url, or data property."); - } else if (block.type === "video") {} else if (block.type === "text-plain") { - if (block.data) - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== "brace") { + push2({ type: "text", value }); + continue; + } + const type = "close"; + block = stack.pop(); + block.close = true; + push2({ type, value }); + depth--; + block = stack[stack.length - 1]; + continue; + } + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + const open = block.nodes.shift(); + block.nodes = [open, { type: "text", value: stringify5(block) }]; + } + push2({ type: "comma", value }); + block.commas++; + continue; + } + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + const siblings = block.nodes; + if (depth === 0 || siblings.length === 0) { + push2({ type: "text", value }); + continue; + } + if (prev.type === "dot") { + block.range = []; + prev.value += value; + prev.type = "range"; + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = "text"; + continue; } - }, block.metadata)); - } else if (block.type === "non_standard" && isAnthropicMessage) - result.push(block.value); - return result; -} -var init_standard = __esm(() => { - init_utils15(); + block.ranges++; + block.args = []; + continue; + } + if (prev.type === "range") { + siblings.pop(); + const before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + push2({ type: "dot", value }); + continue; + } + push2({ type: "text", value }); + } + do { + block = stack.pop(); + if (block.type !== "root") { + block.nodes.forEach((node) => { + if (!node.nodes) { + if (node.type === "open") + node.isOpen = true; + if (node.type === "close") + node.isClose = true; + if (!node.nodes) + node.type = "text"; + node.invalid = true; + } + }); + const parent = stack[stack.length - 1]; + const index3 = parent.nodes.indexOf(block); + parent.nodes.splice(index3, 1, ...block.nodes); + } + } while (stack.length > 0); + push2({ type: "eos" }); + return ast; + }; + module.exports = parse16; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/message_inputs.js -function _formatImage(imageUrl) { - const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); - if (parsed) - return { - type: "base64", - media_type: parsed.mime_type, - data: parsed.data - }; - let parsedUrl; - try { - parsedUrl = new URL(imageUrl); - } catch { - throw new Error([ - `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join(` +// ../../node_modules/.pnpm/braces@3.0.3/node_modules/braces/index.js +var require_braces = __commonJS((exports, module) => { + var stringify5 = require_stringify2(); + var compile = require_compile(); + var expand = require_expand(); + var parse16 = require_parse2(); + var braces = (input, options = {}) => { + let output = []; + if (Array.isArray(input)) { + for (const pattern of input) { + const result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; + }; + braces.parse = (input, options = {}) => parse16(input, options); + braces.stringify = (input, options = {}) => { + if (typeof input === "string") { + return stringify5(braces.parse(input, options), options); + } + return stringify5(input, options); + }; + braces.compile = (input, options = {}) => { + if (typeof input === "string") { + input = braces.parse(input, options); + } + return compile(input, options); + }; + braces.expand = (input, options = {}) => { + if (typeof input === "string") { + input = braces.parse(input, options); + } + let result = expand(input, options); + if (options.noempty === true) { + result = result.filter(Boolean); + } + if (options.nodupes === true) { + result = [...new Set(result)]; + } + return result; + }; + braces.create = (input, options = {}) => { + if (input === "" || input.length < 3) { + return [input]; + } + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); + }; + module.exports = braces; +}); -`)); - } - if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") - return { - type: "url", - url: imageUrl +// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/constants.js +var require_constants2 = __commonJS((exports, module) => { + var path2 = __require("path"); + var WIN_SLASH = "\\\\/"; + var WIN_NO_SLASH = `[^${WIN_SLASH}]`; + var DEFAULT_MAX_EXTGLOB_RECURSION = 0; + var DOT_LITERAL = "\\."; + var PLUS_LITERAL = "\\+"; + var QMARK_LITERAL = "\\?"; + var SLASH_LITERAL = "\\/"; + var ONE_CHAR = "(?=.)"; + var QMARK = "[^/]"; + var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; + var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; + var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; + var NO_DOT = `(?!${DOT_LITERAL})`; + var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; + var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; + var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; + var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; + var STAR = `${QMARK}*?`; + var POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR + }; + var WINDOWS_CHARS = { + ...POSIX_CHARS, + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` + }; + var POSIX_REGEX_SOURCE = { + __proto__: null, + alnum: "a-zA-Z0-9", + alpha: "a-zA-Z", + ascii: "\\x00-\\x7F", + blank: " \\t", + cntrl: "\\x00-\\x1F\\x7F", + digit: "0-9", + graph: "\\x21-\\x7E", + lower: "a-z", + print: "\\x20-\\x7E ", + punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", + space: " \\t\\r\\n\\v\\f", + upper: "A-Z", + word: "A-Za-z0-9_", + xdigit: "A-Fa-f0-9" + }; + module.exports = { + DEFAULT_MAX_EXTGLOB_RECURSION, + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + REPLACEMENTS: { + __proto__: null, + "***": "*", + "**/**": "**", + "**/**/**": "**" + }, + CHAR_0: 48, + CHAR_9: 57, + CHAR_UPPERCASE_A: 65, + CHAR_LOWERCASE_A: 97, + CHAR_UPPERCASE_Z: 90, + CHAR_LOWERCASE_Z: 122, + CHAR_LEFT_PARENTHESES: 40, + CHAR_RIGHT_PARENTHESES: 41, + CHAR_ASTERISK: 42, + CHAR_AMPERSAND: 38, + CHAR_AT: 64, + CHAR_BACKWARD_SLASH: 92, + CHAR_CARRIAGE_RETURN: 13, + CHAR_CIRCUMFLEX_ACCENT: 94, + CHAR_COLON: 58, + CHAR_COMMA: 44, + CHAR_DOT: 46, + CHAR_DOUBLE_QUOTE: 34, + CHAR_EQUAL: 61, + CHAR_EXCLAMATION_MARK: 33, + CHAR_FORM_FEED: 12, + CHAR_FORWARD_SLASH: 47, + CHAR_GRAVE_ACCENT: 96, + CHAR_HASH: 35, + CHAR_HYPHEN_MINUS: 45, + CHAR_LEFT_ANGLE_BRACKET: 60, + CHAR_LEFT_CURLY_BRACE: 123, + CHAR_LEFT_SQUARE_BRACKET: 91, + CHAR_LINE_FEED: 10, + CHAR_NO_BREAK_SPACE: 160, + CHAR_PERCENT: 37, + CHAR_PLUS: 43, + CHAR_QUESTION_MARK: 63, + CHAR_RIGHT_ANGLE_BRACKET: 62, + CHAR_RIGHT_CURLY_BRACE: 125, + CHAR_RIGHT_SQUARE_BRACKET: 93, + CHAR_SEMICOLON: 59, + CHAR_SINGLE_QUOTE: 39, + CHAR_SPACE: 32, + CHAR_TAB: 9, + CHAR_UNDERSCORE: 95, + CHAR_VERTICAL_LINE: 124, + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, + SEP: path2.sep, + extglobChars(chars) { + return { + "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` }, + "?": { type: "qmark", open: "(?:", close: ")?" }, + "+": { type: "plus", open: "(?:", close: ")+" }, + "*": { type: "star", open: "(?:", close: ")*" }, + "@": { type: "at", open: "(?:", close: ")" } + }; + }, + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } + }; +}); + +// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/utils.js +var require_utils2 = __commonJS((exports) => { + var path2 = __require("path"); + var win32 = process.platform === "win32"; + var { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = require_constants2(); + exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); + exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str); + exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); + exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); + exports.removeBackslashes = (str) => { + return str.replace(REGEX_REMOVE_BACKSLASH, (match2) => { + return match2 === "\\" ? "" : match2; + }); + }; + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split(".").map(Number); + if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { + return true; + } + return false; + }; + exports.isWindows = (options) => { + if (options && typeof options.windows === "boolean") { + return options.windows; + } + return win32 === true || path2.sep === "\\"; + }; + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) + return input; + if (input[idx - 1] === "\\") + return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith("./")) { + output = output.slice(2); + state.prefix = "./"; + } + return output; + }; + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? "" : "^"; + const append = options.contains ? "" : "$"; + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; + }; +}); + +// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/scan.js +var require_scan = __commonJS((exports, module) => { + var utils = require_utils2(); + var { + CHAR_ASTERISK, + CHAR_AT, + CHAR_BACKWARD_SLASH, + CHAR_COMMA, + CHAR_DOT, + CHAR_EXCLAMATION_MARK, + CHAR_FORWARD_SLASH, + CHAR_LEFT_CURLY_BRACE, + CHAR_LEFT_PARENTHESES, + CHAR_LEFT_SQUARE_BRACKET, + CHAR_PLUS, + CHAR_QUESTION_MARK, + CHAR_RIGHT_CURLY_BRACE, + CHAR_RIGHT_PARENTHESES, + CHAR_RIGHT_SQUARE_BRACKET + } = require_constants2(); + var isPathSeparator = (code) => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; + }; + var depth = (token) => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } + }; + var scan2 = (input, options) => { + const opts = options || {}; + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + let str = input; + let index2 = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: "", depth: 0, isGlob: false }; + const eos2 = () => index2 >= length; + const peek = () => str.charCodeAt(index2 + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index2); }; - throw new Error([ - `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join(` + while (index2 < length) { + code = advance(); + let next; + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + while (eos2() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index2); + tokens.push(token); + token = { value: "", depth: 0, isGlob: false }; + if (finished === true) + continue; + if (prev === CHAR_DOT && index2 === start + 1) { + start += 2; + continue; + } + lastIndex = index2 + 1; + continue; + } + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index2 === start) { + negatedExtglob = true; + } + if (scanToEnd === true) { + while (eos2() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) + isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos2() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + if (scanToEnd === true) { + continue; + } + break; + } + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index2 === start) { + negated = token.negated = true; + start++; + continue; + } + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + if (scanToEnd === true) { + while (eos2() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + if (isGlob === true) { + finished = true; + if (scanToEnd === true) { + continue; + } + break; + } + } + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + let base = str; + let prefix = ""; + let glob = ""; + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ""; + glob = str; + } else { + base = str; + } + if (base && base !== "" && base !== "/" && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + if (opts.unescape === true) { + if (glob) + glob = utils.removeBackslashes(glob); + if (base && backslashes === true) { + base = utils.removeBackslashes(base); + } + } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + for (let idx = 0;idx < slashes.length; idx++) { + const n4 = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n4, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== "") { + parts.push(value); + } + prevIndex = i; + } + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + state.slashes = slashes; + state.parts = parts; + } + return state; + }; + module.exports = scan2; +}); -`)); -} -function _ensureMessageContents(messages) { - const updatedMsgs = []; - for (const message of messages) - if (message._getType() === "tool") - if (typeof message.content === "string") { - const previousMessage = updatedMsgs[updatedMsgs.length - 1]; - if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") - previousMessage.content.push({ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }); - else - updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }] })); - } else - updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - ...message.content != null ? { content: _formatContent(message) } : {}, - tool_use_id: message.tool_call_id - }] })); - else - updatedMsgs.push(message); - return updatedMsgs; -} -function _convertLangChainToolCallToAnthropic(toolCall) { - if (toolCall.id === undefined) - throw new Error(`Anthropic requires all tool calls to have an "id".`); - return { - type: "tool_use", - id: toolCall.id, - name: toolCall.name, - input: toolCall.args +// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/parse.js +var require_parse3 = __commonJS((exports, module) => { + var constants = require_constants2(); + var utils = require_utils2(); + var { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS + } = constants; + var expandRange = (args, options) => { + if (typeof options.expandRange === "function") { + return options.expandRange(...args, options); + } + args.sort(); + const value = `[${args.join("-")}]`; + try { + new RegExp(value); + } catch (ex) { + return args.map((v) => utils.escapeRegex(v)).join(".."); + } + return value; }; -} -function* _formatContentBlocks(content, toolCalls) { - const toolTypes = [ - "bash_code_execution_tool_result", - "input_json_delta", - "server_tool_use", - "text_editor_code_execution_tool_result", - "tool_result", - "tool_use", - "web_search_result", - "web_search_tool_result" - ]; - const textTypes = ["text", "text_delta"]; - for (const contentPart of content) { - if (isDataContentBlock(contentPart)) - yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); - const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : undefined; - if (contentPart.type === "image_url") { - let source; - if (typeof contentPart.image_url === "string") - source = _formatImage(contentPart.image_url); - else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") - source = _formatImage(contentPart.image_url.url); - if (source) - yield { - type: "image", - source, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (_isAnthropicImageBlockParam(contentPart)) - yield contentPart; - else if (contentPart.type === "image") { - let source; - if ("url" in contentPart && typeof contentPart.url === "string") - source = _formatImage(contentPart.url); - else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) - source = { - type: "base64", - media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "image/jpeg", - data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") - }; - else if ("fileId" in contentPart && typeof contentPart.fileId === "string") - source = { - type: "file", - file_id: contentPart.fileId - }; - if (source) - yield { - type: "image", - source, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (contentPart.type === "file") { - let source; - if ("url" in contentPart && typeof contentPart.url === "string") - source = { - type: "url", - url: contentPart.url - }; - else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) - source = { - type: "base64", - media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "application/pdf", - data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") - }; - else if ("fileId" in contentPart && typeof contentPart.fileId === "string") - source = { - type: "file", - file_id: contentPart.fileId - }; - if (source) - yield { - type: "document", - source, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (contentPart.type === "document") - yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicThinkingBlock(contentPart)) - yield { - type: "thinking", - thinking: contentPart.thinking, - signature: contentPart.signature, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicRedactedThinkingBlock(contentPart)) - yield { - type: "redacted_thinking", - data: contentPart.data, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicCompactionBlock(contentPart)) - yield { - type: "compaction", - content: contentPart.content, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicSearchResultBlock(contentPart)) - yield { - type: "search_result", - title: contentPart.title, - source: contentPart.source, - ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, - content: contentPart.content - }; - else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) - yield { - type: "text", - text: contentPart.text, - ...cacheControl ? { cache_control: cacheControl } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} - }; - else if (toolTypes.find((t) => t === contentPart.type)) { - const contentPartCopy = { ...contentPart }; - if (contentPartCopy.type === "input_json_delta") + var syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; + }; + var splitTopLevel = (input) => { + const parts = []; + let bracket = 0; + let paren = 0; + let quote = 0; + let value = ""; + let escaped = false; + for (const ch of input) { + if (escaped === true) { + value += ch; + escaped = false; continue; - if (contentPartCopy.type === "tool_use" && typeof contentPartCopy.input === "string") { - const matchingToolCall = toolCalls?.find((tc) => tc.id === contentPartCopy.id); - if (matchingToolCall) - contentPartCopy.input = matchingToolCall.args; - else - contentPartCopy.input = content.filter((nestedContentPart) => nestedContentPart.index === contentPartCopy.index && nestedContentPart.type === "input_json_delta" && typeof nestedContentPart.input === "string").reduce((accumulator, nestedContentPart) => accumulator + nestedContentPart.input, contentPartCopy.input); } - if ("index" in contentPartCopy) - delete contentPartCopy.index; - if ("input" in contentPartCopy) { - if (typeof contentPartCopy.input === "string") - try { - contentPartCopy.input = JSON.parse(contentPartCopy.input); - } catch { - contentPartCopy.input = {}; + if (ch === "\\") { + value += ch; + escaped = true; + continue; + } + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + value += ch; + continue; + } + if (quote === 0) { + if (ch === "[") { + bracket++; + } else if (ch === "]" && bracket > 0) { + bracket--; + } else if (bracket === 0) { + if (ch === "(") { + paren++; + } else if (ch === ")" && paren > 0) { + paren--; + } else if (ch === "|" && paren === 0) { + parts.push(value); + value = ""; + continue; } + } } - yield { - ...contentPartCopy, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (contentPart.type === "container_upload") - yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } -} -function _formatContent(message, toolCalls) { - const { content } = message; - if (typeof content === "string") - return content; - else - return Array.from(_formatContentBlocks(content, toolCalls)); -} -function _convertMessagesToAnthropicPayload(messages) { - const mergedMessages = _ensureMessageContents(messages); - let system; - if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") - system = messages[0].content; - return { - messages: mergeMessages((system !== undefined ? mergedMessages.slice(1) : mergedMessages).map((message) => { - let role; - if (message._getType() === "human") - role = "user"; - else if (message._getType() === "ai") - role = "assistant"; - else if (message._getType() === "tool") - role = "user"; - else if (message._getType() === "system") - throw new Error("System messages are only permitted as the first passed message."); - else - throw new Error(`Message type "${message.type}" is not supported.`); - if (AIMessage.isInstance(message) && message.response_metadata?.output_version === "v1") - return { - role, - content: _formatStandardContent(message) - }; - if (AIMessage.isInstance(message) && !!message.tool_calls?.length) - if (typeof message.content === "string") - if (message.content === "") - return { - role, - content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) - }; - else - return { - role, - content: [{ - type: "text", - text: message.content - }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] - }; - else { - const { content } = message; - const formattedContent = _formatContent(message, message.tool_calls); - const formattedContentArr = Array.isArray(formattedContent) ? formattedContent : [{ - type: "text", - text: formattedContent - }]; - const missingToolCalls = message.tool_calls.filter((toolCall) => !content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); + value += ch; + } + parts.push(value); + return parts; + }; + var isPlainBranch = (branch) => { + let escaped = false; + for (const ch of branch) { + if (escaped === true) { + escaped = false; + continue; + } + if (ch === "\\") { + escaped = true; + continue; + } + if (/[?*+@!()[\]{}]/.test(ch)) { + return false; + } + } + return true; + }; + var normalizeSimpleBranch = (branch) => { + let value = branch.trim(); + let changed = true; + while (changed === true) { + changed = false; + if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { + value = value.slice(2, -1); + changed = true; + } + } + if (!isPlainBranch(value)) { + return; + } + return value.replace(/\\(.)/g, "$1"); + }; + var hasRepeatedCharPrefixOverlap = (branches) => { + const values = branches.map(normalizeSimpleBranch).filter(Boolean); + for (let i = 0;i < values.length; i++) { + for (let j = i + 1;j < values.length; j++) { + const a = values[i]; + const b = values[j]; + const char = a[0]; + if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { + continue; + } + if (a === b || a.startsWith(b) || b.startsWith(a)) { + return true; + } + } + } + return false; + }; + var parseRepeatedExtglob = (pattern, requireEnd = true) => { + if (pattern[0] !== "+" && pattern[0] !== "*" || pattern[1] !== "(") { + return; + } + let bracket = 0; + let paren = 0; + let quote = 0; + let escaped = false; + for (let i = 1;i < pattern.length; i++) { + const ch = pattern[i]; + if (escaped === true) { + escaped = false; + continue; + } + if (ch === "\\") { + escaped = true; + continue; + } + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + continue; + } + if (quote === 1) { + continue; + } + if (ch === "[") { + bracket++; + continue; + } + if (ch === "]" && bracket > 0) { + bracket--; + continue; + } + if (bracket > 0) { + continue; + } + if (ch === "(") { + paren++; + continue; + } + if (ch === ")") { + paren--; + if (paren === 0) { + if (requireEnd === true && i !== pattern.length - 1) { + return; + } return { - role, - content: [...formattedContentArr, ...missingToolCalls.map(_convertLangChainToolCallToAnthropic)] + type: pattern[0], + body: pattern.slice(2, i), + end: i }; } - else - return { - role, - content: _formatContent(message, AIMessage.isInstance(message) ? message.tool_calls : undefined) - }; - })), - system + } + } }; -} -function mergeMessages(messages) { - if (!messages || messages.length <= 1) - return messages; - const result = []; - let currentMessage = messages[0]; - const normalizeContent = (content) => { - if (typeof content === "string") - return [{ - type: "text", - text: content - }]; - return content; + var getStarExtglobSequenceOutput = (pattern) => { + let index2 = 0; + const chars = []; + while (index2 < pattern.length) { + const match2 = parseRepeatedExtglob(pattern.slice(index2), false); + if (!match2 || match2.type !== "*") { + return; + } + const branches = splitTopLevel(match2.body).map((branch2) => branch2.trim()); + if (branches.length !== 1) { + return; + } + const branch = normalizeSimpleBranch(branches[0]); + if (!branch || branch.length !== 1) { + return; + } + chars.push(branch); + index2 += match2.end + 1; + } + if (chars.length < 1) { + return; + } + const source = chars.length === 1 ? utils.escapeRegex(chars[0]) : `[${chars.map((ch) => utils.escapeRegex(ch)).join("")}]`; + return `${source}*`; }; - const isToolResultMessage = (msg) => { - if (msg.role !== "user") - return false; - if (typeof msg.content === "string") - return false; - return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); + var repeatedExtglobRecursion = (pattern) => { + let depth = 0; + let value = pattern.trim(); + let match2 = parseRepeatedExtglob(value); + while (match2) { + depth++; + value = match2.body.trim(); + match2 = parseRepeatedExtglob(value); + } + return depth; }; - for (let i = 1;i < messages.length; i += 1) { - const nextMessage = messages[i]; - if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) - currentMessage = { - ...currentMessage, - content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] - }; - else { - result.push(currentMessage); - currentMessage = nextMessage; + var analyzeRepeatedExtglob = (body, options) => { + if (options.maxExtglobRecursion === false) { + return { risky: false }; } - } - result.push(currentMessage); - return result; -} -var init_message_inputs = __esm(() => { - init_content2(); - init_standard(); - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/params.js -function isThinkingEnabled(thinking) { - return thinking.type === "enabled" || thinking.type === "adaptive"; -} -function isOpus47Model(model) { - return model?.startsWith("claude-opus-4-7") ?? false; -} -function getTaskBudgetBetas(model, outputConfig) { - const hasTaskBudget = outputConfig && typeof outputConfig === "object" && "task_budget" in outputConfig && outputConfig.task_budget != null; - return isOpus47Model(model) && hasTaskBudget ? ["task-budgets-2026-03-13"] : []; -} -function validateInvocationParamCompatibility(fields) { - const { model, thinking, topK, topP, temperature } = fields; - const opus47 = isOpus47Model(model); - if (opus47 && thinking.type === "enabled") - throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead'); - if (opus47 && typeof thinking === "object" && thinking != null && "budget_tokens" in thinking) - throw new Error("thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead"); - if (opus47) { - if (topK !== undefined) - throw new Error("topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead"); - if (topP !== undefined && topP !== 1) - throw new Error("topP is not supported for claude-opus-4-7 when set to non-default values"); - if (temperature !== undefined && temperature !== 1) - throw new Error("temperature is not supported for claude-opus-4-7 when set to non-default values"); - } - if (isThinkingEnabled(thinking)) { - if (topK !== undefined) - throw new Error("topK is not supported when thinking is enabled"); - if (topP !== undefined) - throw new Error("topP is not supported when thinking is enabled"); - if (temperature !== undefined && temperature !== 1) - throw new Error("temperature is not supported when thinking is enabled"); - } -} -function getSamplingParams(fields) { - const { model, thinking, topK, topP, temperature } = fields; - const output = {}; - if (isThinkingEnabled(thinking) || isOpus47Model(model)) - return output; - if (temperature !== undefined) - output.temperature = temperature; - if (topK !== undefined) - output.top_k = topK; - if (topP !== undefined) - output.top_p = topP; - return output; -} -var init_params = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/message_outputs.js -function _makeMessageChunkFromAnthropicEvent(data, fields) { - const response_metadata = { model_provider: "anthropic" }; - if (data.type === "message_start") { - const { content, usage, ...additionalKwargs } = data.message; - const filteredAdditionalKwargs = {}; - for (const [key, value] of Object.entries(additionalKwargs)) - if (value !== undefined && value !== null) - filteredAdditionalKwargs[key] = value; - const { input_tokens, output_tokens, ...rest } = usage ?? {}; - const usageMetadata = buildUsageMetadata(usage); - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - additional_kwargs: filteredAdditionalKwargs, - usage_metadata: fields.streamUsage ? usageMetadata : undefined, - response_metadata: { - ...response_metadata, - usage: { ...rest } - }, - id: data.message.id - }) }; - } else if (data.type === "message_delta") { - const usageMetadata = { - input_tokens: 0, - output_tokens: data.usage.output_tokens, - total_tokens: data.usage.output_tokens - }; - const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : undefined; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - response_metadata: responseMetadata, - additional_kwargs: { ...data.delta }, - usage_metadata: fields.streamUsage ? usageMetadata : undefined - }) }; - } else if (data.type === "content_block_start" && [ - "tool_use", - "document", - "server_tool_use", - "web_search_tool_result" - ].includes(data.content_block.type)) { - const contentBlock = data.content_block; - let toolCallChunks; - if (contentBlock.type === "tool_use") - toolCallChunks = [{ - id: contentBlock.id, - index: data.index, - name: contentBlock.name, - args: "" - }]; - else - toolCallChunks = []; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block, - input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : undefined - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: toolCallChunks - }) }; - } else if (data.type === "content_block_delta" && [ - "text_delta", - "citations_delta", - "thinking_delta", - "signature_delta" - ].includes(data.delta.type)) - if (fields.coerceContentToString && "text" in data.delta) - return { chunk: new AIMessageChunk({ content: data.delta.text }) }; - else { - const contentBlock = data.delta; - if ("citation" in contentBlock) { - contentBlock.citations = [contentBlock.citation]; - delete contentBlock.citation; + const max = typeof options.maxExtglobRecursion === "number" ? options.maxExtglobRecursion : constants.DEFAULT_MAX_EXTGLOB_RECURSION; + const branches = splitTopLevel(body).map((branch) => branch.trim()); + if (branches.length > 1) { + if (branches.some((branch) => branch === "") || branches.some((branch) => /^[*?]+$/.test(branch)) || hasRepeatedCharPrefixOverlap(branches)) { + return { risky: true }; } - if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") - return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "thinking" - }], - response_metadata - }) }; - return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "text" - }], - response_metadata - }) }; } - else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - input: data.delta.partial_json, - type: data.delta.type - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: [{ - index: data.index, - args: data.delta.partial_json - }] - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "text") { - const content = data.content_block?.text; - if (content !== undefined) - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata, - additional_kwargs: {} - }) }; - } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "thinking") { - const content = data.content_block.thinking; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - } else if (data.type === "content_block_start" && _isAnthropicCompactionBlock(data.content_block)) - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - else if (data.type === "content_block_delta" && data.delta.type === "compaction_delta") - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.delta, - type: "compaction" - }], - response_metadata - }) }; - return null; -} -function anthropicResponseToChatMessages(messages, additionalKwargs) { - const response_metadata = { - ...additionalKwargs, - model_provider: "anthropic" - }; - const usage = additionalKwargs.usage; - const usageMetadata = usage != null ? buildUsageMetadata(usage) : undefined; - if (messages.length === 1 && messages[0].type === "text") - return [{ - text: messages[0].text, - message: new AIMessage({ - content: messages[0].text, - additional_kwargs: additionalKwargs, - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; - else - return [{ - text: "", - message: new AIMessage({ - content: messages, - additional_kwargs: additionalKwargs, - tool_calls: extractToolCalls2(messages), - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; -} -function buildUsageMetadata(usage) { - const cacheCreationInputTokens = usage.cache_creation_input_tokens ?? 0; - const cacheReadInputTokens = usage.cache_read_input_tokens ?? 0; - const totalInputTokens = usage.input_tokens + cacheCreationInputTokens + cacheReadInputTokens; - return { - input_tokens: totalInputTokens, - output_tokens: usage.output_tokens, - total_tokens: totalInputTokens + usage.output_tokens, - input_token_details: { - cache_creation: cacheCreationInputTokens, - cache_read: cacheReadInputTokens + for (const branch of branches) { + const safeOutput = getStarExtglobSequenceOutput(branch); + if (safeOutput) { + return { risky: true, safeOutput }; + } + if (repeatedExtglobRecursion(branch) > max) { + return { risky: true }; + } } + return { risky: false }; }; -} -var init_message_outputs = __esm(() => { - init_output_parsers3(); - init_content2(); - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/errors.js -function addLangChainErrorFields2(error51, lc_error_code) { - error51.lc_error_code = lc_error_code; - error51.message = `${error51.message} - -Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/ -`; - return error51; -} -function wrapAnthropicClientError(e) { - let error51; - if (e.status === 400 && typeof e.message === "string" && e.message.includes("prompt is too long")) - error51 = addLangChainErrorFields2(ContextOverflowError.fromError(e), "CONTEXT_OVERFLOW"); - else if (e.status === 400 && e.message.includes("tool")) - error51 = addLangChainErrorFields2(e, "INVALID_TOOL_RESULTS"); - else if (e.status === 401) - error51 = addLangChainErrorFields2(e, "MODEL_AUTHENTICATION"); - else if (e.status === 404) - error51 = addLangChainErrorFields2(e, "MODEL_NOT_FOUND"); - else if (e.status === 429) - error51 = addLangChainErrorFields2(e, "MODEL_RATE_LIMIT"); - else - error51 = e; - return error51; -} -var init_errors9 = __esm(() => { - init_errors3(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/profiles.js -var PROFILES; -var init_profiles2 = __esm(() => { - PROFILES = { - "claude-3-sonnet-20240229": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-haiku-4-5": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-5-20251101": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-opus-20240229": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-haiku-20241022": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-sonnet-20241022": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-6": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-0": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-7": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-haiku-20240307": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-5-20250929": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-haiku-latest": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-1": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-0": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-sonnet-20240620": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-5": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-1-20250805": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-haiku-4-5-20251001": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-20250514": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-6": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-7-sonnet-20250219": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-5": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-20250514": { - maxInputTokens: 200000, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32000, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true + var parse16 = (input, options) => { + if (typeof input !== "string") { + throw new TypeError("Expected a string"); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/stream_events.js -async function* convertAnthropicStream(source, options = {}) { - const shouldStreamUsage = options.streamUsage ?? true; - const blockAccumulators = /* @__PURE__ */ new Map; - let usageSnapshot; - let stopReason = null; - for await (const data of source) - switch (data.type) { - case "message_start": { - const { usage, id, model } = data.message; - if (usage && shouldStreamUsage) - usageSnapshot = buildUsageSnapshot(usage); - yield { - event: "message-start", - id, - ...usageSnapshot ? { usage: usageSnapshot } : {} - }; - yield { - event: "provider", - provider: "anthropic", - name: "message_start", - payload: { - model, - id - } - }; - break; + input = REPLACEMENTS[input] || input; + const opts = { ...options }; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + const bos = { type: "bos", value: "", output: opts.prepend || "" }; + const tokens = [bos]; + const capture = opts.capture ? "" : "?:"; + const win32 = utils.isWindows(options); + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + const globstar = (opts2) => { + return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const nodot = opts.dot ? "" : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + if (opts.capture) { + star = `(${star})`; + } + if (typeof opts.noext === "boolean") { + opts.noextglob = opts.noext; + } + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: "", + output: "", + prefix: "", + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils.removePrefix(input, state); + len = input.length; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + const eos2 = () => state.index === len - 1; + const peek = state.peek = (n4 = 1) => input[state.index + n4]; + const advance = state.advance = () => input[++state.index] || ""; + const remaining = () => input.slice(state.index + 1); + const consume = (value2 = "", num = 0) => { + state.consumed += value2; + state.index += num; + }; + const append = (token) => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + const negate = () => { + let count = 1; + while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { + advance(); + state.start++; + count++; } - case "message_delta": - stopReason = data.delta.stop_reason; - if (shouldStreamUsage && data.usage) { - if (!usageSnapshot) - usageSnapshot = { - input_tokens: 0, - output_tokens: data.usage.output_tokens, - total_tokens: data.usage.output_tokens - }; - else - usageSnapshot = { - ...usageSnapshot, - output_tokens: usageSnapshot.output_tokens + data.usage.output_tokens, - total_tokens: usageSnapshot.input_tokens + usageSnapshot.output_tokens + data.usage.output_tokens - }; - yield { - event: "usage", - usage: usageSnapshot - }; + if (count % 2 === 0) { + return false; + } + state.negated = true; + state.start++; + return true; + }; + const increment3 = (type) => { + state[type]++; + stack.push(type); + }; + const decrement = (type) => { + state[type]--; + stack.pop(); + }; + const push2 = (tok) => { + if (prev.type === "globstar") { + const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); + const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); + if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = "star"; + prev.value = "*"; + prev.output = star; + state.output += prev.output; } - if ("context_management" in data.delta && data.delta.context_management) - yield { - event: "provider", - provider: "anthropic", - name: "context_management", - payload: data.delta.context_management - }; - break; - case "message_stop": - yield { - event: "message-finish", - reason: mapStopReason(stopReason), - ...usageSnapshot ? { usage: usageSnapshot } : {}, - metadata: { model_provider: "anthropic" } - }; - break; - case "content_block_start": { - const { index: index2, content_block } = data; - const mapped = mapBlockToContentBlock(content_block, index2); - blockAccumulators.set(index2, { ...mapped }); - yield { - event: "content-block-start", - index: index2, - content: mapped - }; - break; } - case "content_block_delta": { - const { index: index2, delta } = data; - const acc = blockAccumulators.get(index2); - if (!acc) - break; - const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta); - blockAccumulators.set(index2, accumulated); - yield { - event: "content-block-delta", - index: index2, - delta: contentDelta - }; - break; + if (extglobs.length && tok.type !== "paren") { + extglobs[extglobs.length - 1].inner += tok.value; } - case "content_block_stop": { - const { index: index2 } = data; - const acc = blockAccumulators.get(index2); - if (!acc) - break; - yield { - event: "content-block-finish", - index: index2, - content: finalizeBlock(acc) - }; - blockAccumulators.delete(index2); - break; + if (tok.value || tok.output) + append(tok); + if (prev && prev.type === "text" && tok.type === "text") { + prev.value += tok.value; + prev.output = (prev.output || "") + tok.value; + return; } - default: - yield { - event: "provider", - provider: "anthropic", - name: data.type, - payload: data - }; - break; - } -} -function mapStopReason(stopReason) { - switch (stopReason) { - case "end_turn": - case "stop_sequence": - return "stop"; - case "tool_use": - return "tool_use"; - case "max_tokens": - return "length"; - default: - return "stop"; - } -} -function buildUsageSnapshot(usage) { - const cacheCreation = usage.cache_creation_input_tokens ?? 0; - const cacheRead = usage.cache_read_input_tokens ?? 0; - const totalInput = usage.input_tokens + cacheCreation + cacheRead; - return { - input_tokens: totalInput, - output_tokens: usage.output_tokens, - total_tokens: totalInput + usage.output_tokens, - input_token_details: { - cache_creation: cacheCreation, - cache_read: cacheRead - } - }; -} -function mapBlockToContentBlock(block, index2) { - switch (block.type) { - case "text": - return { - type: "text", - text: block.text ?? "", - index: index2 - }; - case "thinking": - return { - type: "reasoning", - reasoning: block.thinking ?? "", - index: index2 - }; - case "redacted_thinking": - return { - type: "non_standard", - value: { ...block }, - index: index2 - }; - case "tool_use": - return { - type: "tool_call_chunk", - id: block.id, - name: block.name, - args: "", - index: index2 - }; - case "server_tool_use": - return { - type: "server_tool_call_chunk", - id: block.id, - name: block.name, - args: "", - index: index2 - }; - default: - return { - type: "non_standard", - value: { ...block }, - index: index2 - }; - } -} -function applyAnthropicDelta(accumulated, delta) { - switch (delta.type) { - case "text_delta": - return { - contentDelta: { - type: "text-delta", - text: delta.text - }, - accumulated: { - ...accumulated, - text: (accumulated.text ?? "") + delta.text + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + const extglobOpen = (type, value2) => { + const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" }; + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + token.startIndex = state.index; + token.tokensIndex = tokens.length; + const output = (opts.capture ? "(" : "") + token.open; + increment3("parens"); + push2({ type, value: value2, output: state.output ? "" : ONE_CHAR }); + push2({ type: "paren", extglob: true, value: advance(), output }); + extglobs.push(token); + }; + const extglobClose = (token) => { + const literal3 = input.slice(token.startIndex, state.index + 1); + const body = input.slice(token.startIndex + 2, state.index); + const analysis = analyzeRepeatedExtglob(body, opts); + if ((token.type === "plus" || token.type === "star") && analysis.risky) { + const safeOutput = analysis.safeOutput ? (token.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : undefined; + const open = tokens[token.tokensIndex]; + open.type = "text"; + open.value = literal3; + open.output = safeOutput || utils.escapeRegex(literal3); + for (let i = token.tokensIndex + 1;i < tokens.length; i++) { + tokens[i].value = ""; + tokens[i].output = ""; + delete tokens[i].suffix; } - }; - case "thinking_delta": - return { - contentDelta: { - type: "reasoning-delta", - reasoning: delta.thinking - }, - accumulated: { - ...accumulated, - reasoning: (accumulated.reasoning ?? "") + delta.thinking + state.output = token.output + open.output; + state.backtrack = true; + push2({ type: "paren", extglob: true, value, output: "" }); + decrement("parens"); + return; + } + let output = token.close + (opts.capture ? ")" : ""); + let rest; + if (token.type === "negate") { + let extglobStar = star; + if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { + extglobStar = globstar(opts); } - }; - case "input_json_delta": { - const newArgs = (accumulated.args ?? "") + delta.partial_json; - return { - contentDelta: { - type: "block-delta", - fields: { - type: accumulated.type, - args: newArgs + if (extglobStar !== star || eos2() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + const expression = parse16(rest, { ...options, fastpaths: false }).output; + output = token.close = `)${expression})${extglobStar})`; + } + if (token.prev.type === "bos") { + state.negatedExtglob = true; + } + } + push2({ type: "paren", extglob: true, value, output }); + decrement("parens"); + }; + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc3, chars, first, rest, index2) => { + if (first === "\\") { + backslashes = true; + return m; + } + if (first === "?") { + if (esc3) { + return esc3 + first + (rest ? QMARK.repeat(rest.length) : ""); } - }, - accumulated: { - ...accumulated, - args: newArgs + if (index2 === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ""); + } + return QMARK.repeat(chars.length); } - }; - } - case "citations_delta": { - const annotations = [...accumulated.annotations ?? [], delta.citation]; - return { - contentDelta: { - type: "block-delta", - fields: { - type: accumulated.type, - annotations + if (first === ".") { + return DOT_LITERAL.repeat(chars.length); + } + if (first === "*") { + if (esc3) { + return esc3 + first + (rest ? star : ""); } - }, - accumulated: { - ...accumulated, - annotations + return star; } - }; + return esc3 ? m : `\\${m}`; + }); + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ""); + } else { + output = output.replace(/\\+/g, (m) => { + return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; + }); + } + } + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + state.output = utils.wrapOutput(output, state, options); + return state; } - case "signature_delta": - return { - contentDelta: { - type: "block-delta", - fields: { - type: accumulated.type, - signature: delta.signature + while (!eos2()) { + value = advance(); + if (value === "\x00") { + continue; + } + if (value === "\\") { + const next = peek(); + if (next === "/" && opts.bash !== true) { + continue; + } + if (next === "." || next === ";") { + continue; + } + if (!next) { + value += "\\"; + push2({ type: "text", value }); + continue; + } + const match2 = /^\\+/.exec(remaining()); + let slashes = 0; + if (match2 && match2[0].length > 2) { + slashes = match2[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += "\\"; } - }, - accumulated: { - ...accumulated, - signature: delta.signature } - }; - case "compaction_delta": - return { - contentDelta: { - type: "block-delta", - fields: { - type: "non_standard", - value: { - ...accumulated.value ?? {}, - compaction: delta + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + if (state.brackets === 0) { + push2({ type: "text", value }); + continue; + } + } + if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) { + if (opts.posix !== false && value === ":") { + const inner = prev.value.slice(1); + if (inner.includes("[")) { + prev.posix = true; + if (inner.includes(":")) { + const idx = prev.value.lastIndexOf("["); + const pre = prev.value.slice(0, idx); + const rest2 = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest2]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } } } - }, - accumulated: { - ...accumulated, - value: { - ...accumulated.value ?? {}, - compaction: delta + } + if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") { + value = `\\${value}`; + } + if (value === "]" && (prev.value === "[" || prev.value === "[^")) { + value = `\\${value}`; + } + if (opts.posix === true && value === "!" && prev.value === "[") { + value = "^"; + } + prev.value += value; + append({ value }); + continue; + } + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push2({ type: "text", value }); + } + continue; + } + if (value === "(") { + increment3("parens"); + push2({ type: "paren", value }); + continue; + } + if (value === ")") { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("opening", "(")); + } + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + push2({ type: "paren", value, output: state.parens ? ")" : "\\)" }); + decrement("parens"); + continue; + } + if (value === "[") { + if (opts.nobracket === true || !remaining().includes("]")) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("closing", "]")); } + value = `\\${value}`; + } else { + increment3("brackets"); } - }; - default: - return { - contentDelta: { - type: "block-delta", - fields: { - type: accumulated.type, - ...delta + push2({ type: "bracket", value }); + continue; + } + if (value === "]") { + if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { + push2({ type: "text", value, output: `\\${value}` }); + continue; + } + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError("opening", "[")); } - }, - accumulated - }; - } -} -function finalizeBlock(accumulated) { - if (accumulated.type === "tool_call_chunk" || accumulated.type === "server_tool_call_chunk") { - const finalType = accumulated.type === "tool_call_chunk" ? "tool_call" : "server_tool_call"; - let parsedArgs; - try { - parsedArgs = JSON.parse(accumulated.args || "{}"); - } catch { - return { - type: "invalid_tool_call", - id: accumulated.id, - name: accumulated.name, - args: accumulated.args, - error: "Failed to parse tool call arguments as JSON" - }; + push2({ type: "text", value, output: `\\${value}` }); + continue; + } + decrement("brackets"); + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { + value = `/${value}`; + } + prev.value += value; + append({ value }); + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + if (value === "{" && opts.nobrace !== true) { + increment3("braces"); + const open = { + type: "brace", + value, + output: "(", + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + braces.push(open); + push2(open); + continue; + } + if (value === "}") { + const brace = braces[braces.length - 1]; + if (opts.nobrace === true || !brace) { + push2({ type: "text", value, output: value }); + continue; + } + let output = ")"; + if (brace.dots === true) { + const arr3 = tokens.slice(); + const range = []; + for (let i = arr3.length - 1;i >= 0; i--) { + tokens.pop(); + if (arr3[i].type === "brace") { + break; + } + if (arr3[i].type !== "dots") { + range.unshift(arr3[i].value); + } + } + output = expandRange(range, opts); + state.backtrack = true; + } + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = "\\{"; + value = output = "\\}"; + state.output = out; + for (const t of toks) { + state.output += t.output || t.value; + } + } + push2({ type: "brace", value, output }); + decrement("braces"); + braces.pop(); + continue; + } + if (value === "|") { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push2({ type: "text", value }); + continue; + } + if (value === ",") { + let output = value; + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === "braces") { + brace.comma = true; + output = "|"; + } + push2({ type: "comma", value, output }); + continue; + } + if (value === "/") { + if (prev.type === "dot" && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ""; + state.output = ""; + tokens.pop(); + prev = bos; + continue; + } + push2({ type: "slash", value, output: SLASH_LITERAL }); + continue; + } + if (value === ".") { + if (state.braces > 0 && prev.type === "dot") { + if (prev.value === ".") + prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = "dots"; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { + push2({ type: "text", value, output: DOT_LITERAL }); + continue; + } + push2({ type: "dot", value, output: DOT_LITERAL }); + continue; + } + if (value === "?") { + const isGroup = prev && prev.value === "("; + if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("qmark", value); + continue; + } + if (prev && prev.type === "paren") { + const next = peek(); + let output = value; + if (next === "<" && !utils.supportsLookbehinds()) { + throw new Error("Node.js v10 or higher is required for regex lookbehinds"); + } + if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { + output = `\\${value}`; + } + push2({ type: "text", value, output }); + continue; + } + if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { + push2({ type: "qmark", value, output: QMARK_NO_DOT }); + continue; + } + push2({ type: "qmark", value, output: QMARK }); + continue; + } + if (value === "!") { + if (opts.noextglob !== true && peek() === "(") { + if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { + extglobOpen("negate", value); + continue; + } + } + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + if (value === "+") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + extglobOpen("plus", value); + continue; + } + if (prev && prev.value === "(" || opts.regex === false) { + push2({ type: "plus", value, output: PLUS_LITERAL }); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { + push2({ type: "plus", value }); + continue; + } + push2({ type: "plus", value: PLUS_LITERAL }); + continue; + } + if (value === "@") { + if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { + push2({ type: "at", extglob: true, value, output: "" }); + continue; + } + push2({ type: "text", value }); + continue; + } + if (value !== "*") { + if (value === "$" || value === "^") { + value = `\\${value}`; + } + const match2 = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match2) { + value += match2[0]; + state.index += match2[0].length; + } + push2({ type: "text", value }); + continue; + } + if (prev && (prev.type === "globstar" || prev.star === true)) { + prev.type = "star"; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen("star", value); + continue; + } + if (prev.type === "star") { + if (opts.noglobstar === true) { + consume(value); + continue; + } + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === "slash" || prior.type === "bos"; + const afterStar = before && (before.type === "star" || before.type === "globstar"); + if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { + push2({ type: "star", value, output: "" }); + continue; + } + const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); + const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); + if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) { + push2({ type: "star", value, output: "" }); + continue; + } + while (rest.slice(0, 3) === "/**") { + const after = input[state.index + 4]; + if (after && after !== "/") { + break; + } + rest = rest.slice(3); + consume("/**", 3); + } + if (prior.type === "bos" && eos2()) { + prev.type = "globstar"; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos2()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { + const end = rest[1] !== undefined ? "|$" : ""; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = "globstar"; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + state.output += prior.output + prev.output; + state.globstar = true; + consume(value + advance()); + push2({ type: "slash", value: "/", output: "" }); + continue; + } + if (prior.type === "bos" && rest[0] === "/") { + prev.type = "globstar"; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push2({ type: "slash", value: "/", output: "" }); + continue; + } + state.output = state.output.slice(0, -prev.output.length); + prev.type = "globstar"; + prev.output = globstar(opts); + prev.value += value; + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + const token = { type: "star", value, output: star }; + if (opts.bash === true) { + token.output = ".*?"; + if (prev.type === "bos" || prev.type === "slash") { + token.output = nodot + token.output; + } + push2(token); + continue; + } + if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { + token.output = value; + push2(token); + continue; + } + if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { + if (prev.type === "dot") { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + } else { + state.output += nodot; + prev.output += nodot; + } + if (peek() !== "*") { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + push2(token); } - return { - type: finalType, - id: accumulated.id, - name: accumulated.name, - args: parsedArgs - }; - } - const { index: _index, ...rest } = accumulated; - return rest; -} -var init_stream_events = () => {}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/tslib.mjs -function __classPrivateFieldSet(receiver, state, value, kind, f3) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f3) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value; -} -function __classPrivateFieldGet(receiver, state, kind, f3) { - if (kind === "a" && !f3) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver); -} -var init_tslib = () => {}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs -var uuid42 = function() { - const { crypto: crypto3 } = globalThis; - if (crypto3?.randomUUID) { - uuid42 = crypto3.randomUUID.bind(crypto3); - return crypto3.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto3 ? () => crypto3.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; - return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); -}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/errors.mjs -function isAbortError(err) { - return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException")); -} -var castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === "object" && err !== null) { - try { - if (Object.prototype.toString.call(err) === "[object Error]") { - const error51 = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error51.stack = err.stack; - if (err.cause && !error51.cause) - error51.cause = err.cause; - if (err.name) - error51.name = err.name; - return error51; + while (state.brackets > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", "]")); + state.output = utils.escapeLast(state.output, "["); + decrement("brackets"); + } + while (state.parens > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", ")")); + state.output = utils.escapeLast(state.output, "("); + decrement("parens"); + } + while (state.braces > 0) { + if (opts.strictBrackets === true) + throw new SyntaxError(syntaxError("closing", "}")); + state.output = utils.escapeLast(state.output, "{"); + decrement("braces"); + } + if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { + push2({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` }); + } + if (state.backtrack === true) { + state.output = ""; + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + if (token.suffix) { + state.output += token.suffix; + } } - } catch {} - try { - return new Error(JSON.stringify(err)); - } catch {} - } - return new Error(err); -}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/error.mjs -var AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError; -var init_error5 = __esm(() => { - AnthropicError = class AnthropicError extends Error { + } + return state; }; - APIError = class APIError extends AnthropicError { - constructor(status, error51, message, headers, type) { - super(`${APIError.makeMessage(status, error51, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get("request-id"); - this.error = error51; - this.type = type ?? null; + parse16.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } - static makeMessage(status, error51, message) { - const msg = error51?.message ? typeof error51.message === "string" ? error51.message : JSON.stringify(error51.message) : error51 ? JSON.stringify(error51) : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? "" : "?:"; + const state = { negated: false, prefix: "" }; + let star = opts.bash === true ? ".*?" : STAR; + if (opts.capture) { + star = `(${star})`; + } + const globstar = (opts2) => { + if (opts2.noglobstar === true) + return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + const create = (str) => { + switch (str) { + case "*": + return `${nodot}${ONE_CHAR}${star}`; + case ".*": + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*.*": + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "*/*": + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + case "**": + return nodot + globstar(opts); + case "**/*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + case "**/*.*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + case "**/.*": + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + default: { + const match2 = /^(.*?)\.(\w+)$/.exec(str); + if (!match2) + return; + const source2 = create(match2[1]); + if (!source2) + return; + return source2 + DOT_LITERAL + match2[2]; + } } - return "(no status code or body)"; + }; + const output = utils.removePrefix(input, state); + let source = create(output); + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError({ message, cause: castToError(errorResponse) }); + return source; + }; + module.exports = parse16; +}); + +// ../../node_modules/.pnpm/picomatch@2.3.2/node_modules/picomatch/lib/picomatch.js +var require_picomatch = __commonJS((exports, module) => { + var path2 = __require("path"); + var scan2 = require_scan(); + var parse16 = require_parse3(); + var utils = require_utils2(); + var constants = require_constants2(); + var isObject4 = (val) => val && typeof val === "object" && !Array.isArray(val); + var picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map((input) => picomatch(input, options, returnState)); + const arrayMatcher = (str) => { + for (const isMatch of fns) { + const state2 = isMatch(str); + if (state2) + return state2; + } + return false; + }; + return arrayMatcher; + } + const isState = isObject4(glob) && glob.tokens && glob.input; + if (glob === "" || typeof glob !== "string" && !isState) { + throw new TypeError("Expected pattern to be a non-empty string"); + } + const opts = options || {}; + const posix = utils.isWindows(options); + const regex2 = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); + const state = regex2.state; + delete regex2.state; + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + const matcher = (input, returnObject = false) => { + const { isMatch, match: match2, output } = picomatch.test(input, regex2, options, { glob, posix }); + const result = { glob, state, regex: regex2, posix, input, output, match: match2, isMatch }; + if (typeof opts.onResult === "function") { + opts.onResult(result); } - const error51 = errorResponse; - const type = error51?.["error"]?.["type"]; - if (status === 400) { - return new BadRequestError(status, error51, message, headers, type); + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; } - if (status === 401) { - return new AuthenticationError(status, error51, message, headers, type); + if (isIgnored(input)) { + if (typeof opts.onIgnore === "function") { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; } - if (status === 403) { - return new PermissionDeniedError(status, error51, message, headers, type); + if (typeof opts.onMatch === "function") { + opts.onMatch(result); } - if (status === 404) { - return new NotFoundError(status, error51, message, headers, type); + return returnObject ? result : true; + }; + if (returnState) { + matcher.state = state; + } + return matcher; + }; + picomatch.test = (input, regex2, options, { glob, posix } = {}) => { + if (typeof input !== "string") { + throw new TypeError("Expected input to be a string"); + } + if (input === "") { + return { isMatch: false, output: "" }; + } + const opts = options || {}; + const format3 = opts.format || (posix ? utils.toPosixSlashes : null); + let match2 = input === glob; + let output = match2 && format3 ? format3(input) : input; + if (match2 === false) { + output = format3 ? format3(input) : input; + match2 = output === glob; + } + if (match2 === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match2 = picomatch.matchBase(input, regex2, options, posix); + } else { + match2 = regex2.exec(output); } - if (status === 409) { - return new ConflictError(status, error51, message, headers, type); + } + return { isMatch: Boolean(match2), match: match2, output }; + }; + picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex2 = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex2.test(path2.basename(input)); + }; + picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) + return pattern.map((p) => picomatch.parse(p, options)); + return parse16(pattern, { ...options, fastpaths: false }); + }; + picomatch.scan = (input, options) => scan2(input, options); + picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + const opts = options || {}; + const prepend = opts.contains ? "" : "^"; + const append = opts.contains ? "" : "$"; + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + const regex2 = picomatch.toRegex(source, options); + if (returnState === true) { + regex2.state = state; + } + return regex2; + }; + picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== "string") { + throw new TypeError("Expected a non-empty string"); + } + let parsed = { negated: false, fastpaths: true }; + if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) { + parsed.output = parse16.fastpaths(input, options); + } + if (!parsed.output) { + parsed = parse16(input, options); + } + return picomatch.compileRe(parsed, options, returnOutput, returnState); + }; + picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); + } catch (err) { + if (options && options.debug === true) + throw err; + return /$^/; + } + }; + picomatch.constants = constants; + module.exports = picomatch; +}); + +// ../../node_modules/.pnpm/micromatch@4.0.8/node_modules/micromatch/index.js +var require_micromatch = __commonJS((exports, module) => { + var util5 = __require("util"); + var braces = require_braces(); + var picomatch = require_picomatch(); + var utils = require_utils2(); + var isEmptyString = (v) => v === "" || v === "./"; + var hasBraces = (v) => { + const index2 = v.indexOf("{"); + return index2 > -1 && v.indexOf("}", index2) > -1; + }; + var micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + let omit3 = new Set; + let keep = new Set; + let items = new Set; + let negatives = 0; + let onResult = (state) => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); } - if (status === 422) { - return new UnprocessableEntityError(status, error51, message, headers, type); + }; + for (let i = 0;i < patterns.length; i++) { + let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) + negatives++; + for (let item of list) { + let matched = isMatch(item, true); + let match2 = negated ? !matched.isMatch : matched.isMatch; + if (!match2) + continue; + if (negated) { + omit3.add(matched.output); + } else { + omit3.delete(matched.output); + keep.add(matched.output); + } } - if (status === 429) { - return new RateLimitError(status, error51, message, headers, type); + } + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter((item) => !omit3.has(item)); + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(", ")}"`); } - if (status >= 500) { - return new InternalServerError(status, error51, message, headers, type); + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map((p) => p.replace(/\\/g, "")) : patterns; } - return new APIError(status, error51, message, headers, type); } + return matches; }; - APIUserAbortError = class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || "Request was aborted.", undefined); + micromatch.match = micromatch; + micromatch.matcher = (pattern, options) => picomatch(pattern, options); + micromatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); + micromatch.any = micromatch.isMatch; + micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set; + let items = []; + let onResult = (state) => { + if (options.onResult) + options.onResult(state); + items.push(state.output); + }; + let matches = new Set(micromatch(list, patterns, { ...options, onResult })); + for (let item of items) { + if (!matches.has(item)) { + result.add(item); + } } + return [...result]; }; - APIConnectionError = class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || "Connection error.", undefined); - if (cause) - this.cause = cause; + micromatch.contains = (str, pattern, options) => { + if (typeof str !== "string") { + throw new TypeError(`Expected a string: "${util5.inspect(str)}"`); } - }; - APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? "Request timed out." }); + if (Array.isArray(pattern)) { + return pattern.some((p) => micromatch.contains(str, p, options)); } + if (typeof pattern === "string") { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + if (str.includes(pattern) || str.startsWith("./") && str.slice(2).includes(pattern)) { + return true; + } + } + return micromatch.isMatch(str, pattern, { ...options, contains: true }); }; - BadRequestError = class BadRequestError extends APIError { + micromatch.matchKeys = (obj, patterns, options) => { + if (!utils.isObject(obj)) { + throw new TypeError("Expected the first argument to be an object"); + } + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) + res[key] = obj[key]; + return res; }; - AuthenticationError = class AuthenticationError extends APIError { + micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (items.some((item) => isMatch(item))) { + return true; + } + } + return false; }; - PermissionDeniedError = class PermissionDeniedError extends APIError { + micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch(String(pattern), options); + if (!items.every((item) => isMatch(item))) { + return false; + } + } + return true; }; - NotFoundError = class NotFoundError extends APIError { + micromatch.all = (str, patterns, options) => { + if (typeof str !== "string") { + throw new TypeError(`Expected a string: "${util5.inspect(str)}"`); + } + return [].concat(patterns).every((p) => picomatch(p, options)(str)); }; - ConflictError = class ConflictError extends APIError { + micromatch.capture = (glob, input, options) => { + let posix = utils.isWindows(options); + let regex2 = picomatch.makeRe(String(glob), { ...options, capture: true }); + let match2 = regex2.exec(posix ? utils.toPosixSlashes(input) : input); + if (match2) { + return match2.slice(1).map((v) => v === undefined ? "" : v); + } }; - UnprocessableEntityError = class UnprocessableEntityError extends APIError { + micromatch.makeRe = (...args) => picomatch.makeRe(...args); + micromatch.scan = (...args) => picomatch.scan(...args); + micromatch.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces(String(pattern), options)) { + res.push(picomatch.parse(str, options)); + } + } + return res; }; - RateLimitError = class RateLimitError extends APIError { + micromatch.braces = (pattern, options) => { + if (typeof pattern !== "string") + throw new TypeError("Expected a string"); + if (options && options.nobrace === true || !hasBraces(pattern)) { + return [pattern]; + } + return braces(pattern, options); }; - InternalServerError = class InternalServerError extends APIError { + micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== "string") + throw new TypeError("Expected a string"); + return micromatch.braces(pattern, { ...options, expand: true }); }; + micromatch.hasBraces = hasBraces; + module.exports = micromatch; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs -function maybeObj(x) { - if (typeof x !== "object") { - return {}; - } - return x ?? {}; -} -function isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/identity.js +var require_identity = __commonJS((exports) => { + var ALIAS = Symbol.for("yaml.alias"); + var DOC = Symbol.for("yaml.document"); + var MAP = Symbol.for("yaml.map"); + var PAIR = Symbol.for("yaml.pair"); + var SCALAR = Symbol.for("yaml.scalar"); + var SEQ = Symbol.for("yaml.seq"); + var NODE_TYPE = Symbol.for("yaml.node.type"); + var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } return false; - return true; -} -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -var startsWithSchemeRegexp, isAbsoluteURL = (url2) => { - return startsWithSchemeRegexp.test(url2); -}, isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)), isReadonlyArray, validatePositiveInteger = (name, n3) => { - if (typeof n3 !== "number" || !Number.isInteger(n3)) { - throw new AnthropicError(`${name} must be an integer`); - } - if (n3 < 0) { - throw new AnthropicError(`${name} must be a positive integer`); } - return n3; -}, safeJSON = (text) => { - try { - return JSON.parse(text); - } catch (err) { - return; + function isNode3(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; } -}, pop = (obj, key) => { - const value = obj[key]; - delete obj[key]; - return value; -}; -var init_values4 = __esm(() => { - init_error5(); - startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; - isReadonlyArray = isArray2; + var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + exports.ALIAS = ALIAS; + exports.DOC = DOC; + exports.MAP = MAP; + exports.NODE_TYPE = NODE_TYPE; + exports.PAIR = PAIR; + exports.SCALAR = SCALAR; + exports.SEQ = SEQ; + exports.hasAnchor = hasAnchor; + exports.isAlias = isAlias; + exports.isCollection = isCollection; + exports.isDocument = isDocument; + exports.isMap = isMap; + exports.isNode = isNode3; + exports.isPair = isPair; + exports.isScalar = isScalar; + exports.isSeq = isSeq; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs -var sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/version.mjs -var VERSION = "0.91.1"; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs -function getDetectedPlatform() { - if (typeof Deno !== "undefined" && Deno.build != null) { - return "deno"; - } - if (typeof EdgeRuntime !== "undefined") { - return "edge"; - } - if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { - return "node"; - } - return "unknown"; -} -function getBrowserInfo() { - if (typeof navigator === "undefined" || !navigator) { - return null; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/visit.js +var require_visit = __commonJS((exports) => { + var identity = require_identity(); + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove node"); + function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); } - const browserPatterns = [ - { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } - ]; - for (const { key, pattern } of browserPatterns) { - const match2 = pattern.exec(navigator.userAgent); - if (match2) { - const major = match2[1] || 0; - const minor = match2[2] || 0; - const patch = match2[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + function visit_(key, node, visitor, path2) { + const ctrl = callVisitor(key, node, visitor, path2); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visit_(key, ctrl, visitor, path2); } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0;i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = visit_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; } - return null; -} -var isRunningInBrowser = () => { - return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined"; -}, getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === "deno") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(Deno.build.os), - "X-Stainless-Arch": normalizeArch(Deno.build.arch), - "X-Stainless-Runtime": "deno", - "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" - }; - } - if (typeof EdgeRuntime !== "undefined") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": `other:${EdgeRuntime}`, - "X-Stainless-Runtime": "edge", - "X-Stainless-Runtime-Version": globalThis.process.version - }; - } - if (detectedPlatform === "node") { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), - "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), - "X-Stainless-Runtime": "node", - "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": `browser:${browserInfo.browser}`, - "X-Stainless-Runtime-Version": browserInfo.version - }; - } - return { - "X-Stainless-Lang": "js", - "X-Stainless-Package-Version": VERSION, - "X-Stainless-OS": "Unknown", - "X-Stainless-Arch": "unknown", - "X-Stainless-Runtime": "unknown", - "X-Stainless-Runtime-Version": "unknown" - }; -}, normalizeArch = (arch) => { - if (arch === "x32") - return "x32"; - if (arch === "x86_64" || arch === "x64") - return "x64"; - if (arch === "arm") - return "arm"; - if (arch === "aarch64" || arch === "arm64") - return "arm64"; - if (arch) - return `other:${arch}`; - return "unknown"; -}, normalizePlatform = (platform) => { - platform = platform.toLowerCase(); - if (platform.includes("ios")) - return "iOS"; - if (platform === "android") - return "Android"; - if (platform === "darwin") - return "MacOS"; - if (platform === "win32") - return "Windows"; - if (platform === "freebsd") - return "FreeBSD"; - if (platform === "openbsd") - return "OpenBSD"; - if (platform === "linux") - return "Linux"; - if (platform) - return `Other:${platform}`; - return "Unknown"; -}, _platformHeaders, getPlatformHeaders = () => { - return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); -}; -var init_detect_platform = () => {}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/shims.mjs -function getDefaultFetch() { - if (typeof fetch !== "undefined") { - return fetch; - } - throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); -} -function makeReadableStream(...args) { - const ReadableStream2 = globalThis.ReadableStream; - if (typeof ReadableStream2 === "undefined") { - throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); } - return new ReadableStream2(...args); -} -function ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() {}, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); + visitAsync.BREAK = BREAK; + visitAsync.SKIP = SKIP; + visitAsync.REMOVE = REMOVE; + async function visitAsync_(key, node, visitor, path2) { + const ctrl = await callVisitor(key, node, visitor, path2); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path2, ctrl); + return visitAsync_(key, ctrl, visitor, path2); } - }); -} -function ReadableStreamToAsyncIterable(stream2) { - if (stream2[Symbol.asyncIterator]) - return stream2; - const reader = stream2.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); - return result; - } catch (e) { - reader.releaseLock(); - throw e; + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path2 = Object.freeze(path2.concat(node)); + for (let i = 0;i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path2); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path2 = Object.freeze(path2.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path2); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path2); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; } - }; -} -async function CancelReadableStream(stream2) { - if (stream2 === null || typeof stream2 !== "object") - return; - if (stream2[Symbol.asyncIterator]) { - await stream2[Symbol.asyncIterator]().return?.(); + return ctrl; + } + function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; + } + function callVisitor(key, node, visitor, path2) { + if (typeof visitor === "function") + return visitor(key, node, path2); + if (identity.isMap(node)) + return visitor.Map?.(key, node, path2); + if (identity.isSeq(node)) + return visitor.Seq?.(key, node, path2); + if (identity.isPair(node)) + return visitor.Pair?.(key, node, path2); + if (identity.isScalar(node)) + return visitor.Scalar?.(key, node, path2); + if (identity.isAlias(node)) + return visitor.Alias?.(key, node, path2); return; } - const reader = stream2.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} + function replaceNode(key, path2, node) { + const parent = path2[path2.length - 1]; + if (identity.isCollection(parent)) { + parent.items[key] = node; + } else if (identity.isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (identity.isDocument(parent)) { + parent.contents = node; + } else { + const pt = identity.isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } + } + exports.visit = visit; + exports.visitAsync = visitAsync; +}); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/request-options.mjs -var FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - "content-type": "application/json" - }, - body: JSON.stringify(body) +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/directives.js +var require_directives = __commonJS((exports) => { + var identity = require_identity(); + var visit = require_visit(); + var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" }; -}; + var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs -function stringifyQuery(query3) { - return Object.entries(query3).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + class Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); } - if (value === null) { - return `${encodeURIComponent(key)}=`; + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; } - throw new AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); - }).join("&"); -} -var init_query = __esm(() => { - init_error5(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs -function concatBytes2(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; - } - const output = new Uint8Array(length); - let index2 = 0; - for (const buffer of buffers) { - output.set(buffer, index2); - index2 += buffer.length; - } - return output; -} -function encodeUTF8(str) { - let encoder2; - return (encodeUTF8_ ?? (encoder2 = new globalThis.TextEncoder, encodeUTF8_ = encoder2.encode.bind(encoder2)))(str); -} -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder, decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); -} -var encodeUTF8_, decodeUTF8_; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -class LineDecoder { - constructor() { - _LineDecoder_buffer.set(this, undefined); - _LineDecoder_carriageReturnIndex.set(this, undefined); - __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array, "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; - __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes2([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; + add(line, onError2) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; } - if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - continue; + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError2(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError2(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version6] = parts; + if (version6 === "1.1" || version6 === "1.2") { + this.yaml.version = version6; + return true; + } else { + const isValid3 = /^\d+\.\d+$/.test(version6); + onError2(6, `Unsupported YAML version ${version6}`, isValid3); + return false; + } + } + default: + onError2(0, `Unknown directive ${name}`, true); + return false; } - const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - flush() { - if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { - return []; - } - return this.decode(` -`); - } -} -function findNewlineIndex(buffer, startIndex) { - const newline = 10; - const carriage = 13; - for (let i = startIndex ?? 0;i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function findDoubleNewlineIndex(buffer) { - const newline = 10; - const carriage = 13; - for (let i = 0;i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - return i + 2; + tagName(source, onError2) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError2(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError2(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError2("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError2(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error90) { + onError2(String(error90)); + return null; + } + } + if (handle === "!") + return source; + onError2(`Could not resolve tag: ${source}`); + return null; } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - return i + 2; + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; } - if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) { - return i + 4; + toString(doc3) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc3 && tagEntries.length > 0 && identity.isNode(doc3.contents)) { + const tags = {}; + visit.visit(doc3.contents, (_key, node) => { + if (identity.isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc3 || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join(` +`); } } - return -1; -} -var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; -var init_line = __esm(() => { - init_tslib(); - _LineDecoder_buffer = new WeakMap, _LineDecoder_carriageReturnIndex = new WeakMap; - LineDecoder.NEWLINE_CHARS = new Set([` -`, "\r"]); - LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; + Directives.defaultYaml = { explicit: false, version: "1.2" }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + exports.Directives = Directives; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs -function noop() {} -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } else { - return logger[fnLevel].bind(logger); - } -} -function loggerFor(client2) { - const logger = client2.logger; - const logLevel = client2.logLevel ?? "off"; - if (!logger) { - return noopLogger; - } - const cachedLogger = cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn("error", logger, logLevel), - warn: makeLogFn("warn", logger, logLevel), - info: makeLogFn("info", logger, logLevel), - debug: makeLogFn("debug", logger, logLevel) - }; - cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client2) => { - if (!maybeLevel) { - return; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/anchors.js +var require_anchors = __commonJS((exports) => { + var identity = require_identity(); + var visit = require_visit(); + function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; + function anchorNames(root) { + const anchors = new Set; + visit.visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; } - loggerFor(client2).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return; -}, noopLogger, cachedLoggers, formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options["headers"]; + function findNewAnchor(prefix, exclude) { + for (let i = 1;; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value - ])); + function createNodeAnchors(doc3, prefix) { + const aliasObjects = []; + const sourceObjects = new Map; + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc3)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error90 = new Error("Failed to resolve repeated object (this should not happen)"); + error90.source = source; + throw error90; + } + } + }, + sourceObjects + }; } - if ("retryOfRequestLogID" in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; + exports.anchorIsValid = anchorIsValid; + exports.anchorNames = anchorNames; + exports.createNodeAnchors = createNodeAnchors; + exports.findNewAnchor = findNewAnchor; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/applyReviver.js +var require_applyReviver = __commonJS((exports) => { + function applyReviver(reviver2, obj, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length;i < len; ++i) { + const v0 = val[i]; + const v14 = applyReviver(reviver2, val, String(i), v0); + if (v14 === undefined) + delete val[i]; + else if (v14 !== v0) + val[i] = v14; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v14 = applyReviver(reviver2, val, k, v0); + if (v14 === undefined) + val.delete(k); + else if (v14 !== v0) + val.set(k, v14); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v14 = applyReviver(reviver2, val, v0, v0); + if (v14 === undefined) + val.delete(v0); + else if (v14 !== v0) { + val.delete(v0); + val.add(v14); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v14 = applyReviver(reviver2, val, k, v0); + if (v14 === undefined) + delete val[k]; + else if (v14 !== v0) + val[k] = v14; + } + } } - delete details.retryOfRequestLogID; + return reviver2.call(obj, key, val); } - return details; -}; -var init_log = __esm(() => { - init_values4(); - levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500 - }; - noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop - }; - cachedLoggers = /* @__PURE__ */ new WeakMap; + exports.applyReviver = applyReviver; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/streaming.mjs -async function* _iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { - throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/toJS.js +var require_toJS = __commonJS((exports) => { + var identity = require_identity(); + function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !identity.hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: undefined }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; } - throw new AnthropicError(`Attempted to iterate over a response with no body`); + if (typeof value === "bigint" && !ctx?.keep) + return Number(value); + return value; } - const sseDecoder = new SSEDecoder3; - const lineDecoder = new LineDecoder; - const iter = ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; + exports.toJS = toJS; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Node.js +var require_Node = __commonJS((exports) => { + var applyReviver = require_applyReviver(); + var identity = require_identity(); + var toJS = require_toJS(); + + class NodeBase { + constructor(type) { + Object.defineProperty(this, identity.NODE_TYPE, { value: type }); } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -async function* iterSSEChunks(iterator) { - let data = new Uint8Array; - for await (const chunk of iterator) { - if (chunk == null) { - continue; + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); + toJS(doc3, { mapAsMap, maxAliasCount, onAnchor, reviver: reviver2 } = {}) { + if (!identity.isDocument(doc3)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: new Map, + doc: doc3, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver2 === "function" ? applyReviver.applyReviver(reviver2, { "": res }, "", res) : res; } } - if (data.length > 0) { - yield data; - } -} + exports.NodeBase = NodeBase; +}); -class SSEDecoder3 { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith("\r")) { - line = line.substring(0, line.length - 1); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Alias.js +var require_Alias = __commonJS((exports) => { + var anchors = require_anchors(); + var visit = require_visit(); + var identity = require_identity(); + var Node3 = require_Node(); + var toJS = require_toJS(); + + class Alias extends Node3.NodeBase { + constructor(source) { + super(identity.ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); } - if (!line) { - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join(` -`), - raw: this.chunks - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; + resolve(doc3, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit.visit(doc3, { + Node: (_key, node) => { + if (identity.isAlias(node) || identity.hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = undefined; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + return found; } - this.chunks.push(line); - if (line.startsWith(":")) { - return null; + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors: anchors2, doc: doc3, maxAliasCount } = ctx; + const source = this.resolve(doc3, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors2.get(source); + if (!data) { + toJS.toJS(source, null, ctx); + data = anchors2.get(source); + } + if (data?.res === undefined) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc3, source, anchors2); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + return data.res; } - let [fieldname, _, value] = partition(line, ":"); - if (value.startsWith(" ")) { - value = value.substring(1); + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; } - if (fieldname === "event") { - this.event = value; - } else if (fieldname === "data") { - this.data.push(value); + } + function getAliasCount(doc3, node, anchors2) { + if (identity.isAlias(node)) { + const source = node.resolve(doc3); + const anchor = anchors2 && source && anchors2.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (identity.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc3, item, anchors2); + if (c > count) + count = c; + } + return count; + } else if (identity.isPair(node)) { + const kc = getAliasCount(doc3, node.key, anchors2); + const vc = getAliasCount(doc3, node.value, anchors2); + return Math.max(kc, vc); } - return null; + return 1; } -} -function partition(str, delimiter) { - const index2 = str.indexOf(delimiter); - if (index2 !== -1) { - return [str.substring(0, index2), delimiter, str.substring(index2 + delimiter.length)]; + exports.Alias = Alias; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Scalar.js +var require_Scalar = __commonJS((exports) => { + var identity = require_identity(); + var Node3 = require_Node(); + var toJS = require_toJS(); + var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; + + class Scalar extends Node3.NodeBase { + constructor(value) { + super(identity.SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } } - return [str, "", ""]; -} -var _Stream_client, Stream; -var init_streaming = __esm(() => { - init_tslib(); - init_error5(); - init_line(); - init_values4(); - init_log(); - init_error5(); - Stream = class Stream { - constructor(iterator, controller, client2) { - this.iterator = iterator; - _Stream_client.set(this, undefined); - this.controller = controller; - __classPrivateFieldSet(this, _Stream_client, client2, "f"); + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + exports.Scalar = Scalar; + exports.isScalarValue = isScalarValue; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/createNode.js +var require_createNode = __commonJS((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var defaultTagPrefix = "tag:yaml.org,2002:"; + function findTagObject(value, tagName, tags) { + if (tagName) { + const match2 = tags.filter((t) => t.tag === tagName); + const tagObj = match2.find((t) => !t.format) ?? match2[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; } - static fromSSEResponse(response, controller, client2) { - let consumed = false; - const logger = client2 ? loggerFor(client2) : console; - async function* iterator() { - if (consumed) { - throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); - } - consumed = true; - let done = false; - try { - for await (const sse of _iterSSEMessages(response, controller)) { - if (sse.event === "completion") { - try { - yield JSON.parse(sse.data); - } catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end") { - try { - yield JSON.parse(sse.data); - } catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === "ping") { - continue; - } - if (sse.event === "error") { - const body = safeJSON(sse.data) ?? sse.data; - const type = body?.error?.type; - throw new APIError(undefined, body, undefined, response.headers, type); - } - } - done = true; - } catch (e) { - if (isAbortError(e)) - return; - throw e; - } finally { - if (!done) - controller.abort(); - } + return tags.find((t) => t.identify?.(value) && !t.format); + } + function createNode(value, tagName, ctx) { + if (identity.isDocument(value)) + value = value.contents; + if (identity.isNode(value)) + return value; + if (identity.isPair(value)) { + const map3 = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); + map3.items.push(value); + return map3; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + let ref = undefined; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias.Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); } - return new Stream(iterator, controller, client2); } - static fromReadableStream(readableStream, controller, client2) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new LineDecoder; - const iter = ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); } - async function* iterator() { - if (consumed) { - throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } catch (e) { - if (isAbortError(e)) - return; - throw e; - } finally { - if (!done) - controller.abort(); - } + if (!value || typeof value !== "object") { + const node2 = new Scalar.Scalar(value); + if (ref) + ref.node = node2; + return node2; } - return new Stream(iterator, controller, client2); - } - [(_Stream_client = new WeakMap, Symbol.asyncIterator)]() { - return this.iterator(); - } - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue2) => { - return { - next: () => { - if (queue2.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue2.shift(); - } - }; - }; - return [ - new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), - new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")) - ]; + tagObj = value instanceof Map ? schema[identity.MAP] : (Symbol.iterator in Object(value)) ? schema[identity.SEQ] : schema[identity.MAP]; } - toReadableStream() { - const self2 = this; - let iter; - return makeReadableStream({ - async start() { - iter = self2[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = encodeUTF8(JSON.stringify(value) + ` -`); - ctrl.enqueue(bytes); - } catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - } - }); + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; } - }; + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; + } + exports.createNode = createNode; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/parse.mjs -async function defaultParseResponse(client2, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - loggerFor(client2).debug("response", response.status, response.url, response.headers, response.body); - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller); - } - return Stream.fromSSEResponse(response, props.controller); - } - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get("content-type"); - const mediaType = contentType?.split(";")[0]?.trim(); - const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); - if (isJSON) { - const contentLength = response.headers.get("content-length"); - if (contentLength === "0") { - return; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Collection.js +var require_Collection = __commonJS((exports) => { + var createNode = require_createNode(); + var identity = require_identity(); + var Node3 = require_Node(); + function collectionFromPath(schema, path2, value) { + let v = value; + for (let i = path2.length - 1;i >= 0; --i) { + const k = path2[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = new Map([[k, v]]); } - const json2 = await response.json(); - return addRequestID(json2, response); } - const text = await response.text(); - return text; - })(); - loggerFor(client2).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime - })); - return body; -} -function addRequestID(value, response) { - if (!value || typeof value !== "object" || Array.isArray(value)) { - return value; + return createNode.createNode(v, undefined, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema, + sourceObjects: new Map + }); } - return Object.defineProperty(value, "_request_id", { - value: response.headers.get("request-id"), - enumerable: false - }); -} -var init_parse5 = __esm(() => { - init_streaming(); - init_log(); -}); + var isEmptyPath = (path2) => path2 == null || typeof path2 === "object" && !!path2[Symbol.iterator]().next().done; -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/api-promise.mjs -var _APIPromise_client, APIPromise; -var init_api_promise = __esm(() => { - init_tslib(); - init_parse5(); - APIPromise = class APIPromise extends Promise { - constructor(client2, responsePromise, parseResponse = defaultParseResponse) { - super((resolve2) => { - resolve2(null); + class Collection extends Node3.NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, "schema", { + value: schema, + configurable: true, + enumerable: false, + writable: true }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, undefined); - __classPrivateFieldSet(this, _APIPromise_client, client2, "f"); } - _thenUnwrap(transform2) { - return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client2, props) => addRequestID(transform2(await this.parseResponse(client2, props), props), props.response)); + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) + copy.schema = schema; + copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; } - asResponse() { - return this.responsePromise.then((p) => p.response); + addIn(path2, value) { + if (isEmptyPath(path2)) + this.add(value); + else { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (identity.isCollection(node)) + node.addIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } } - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get("request-id") }; + deleteIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (identity.isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); - } - return this.parsedPromise; + getIn(path2, keepScalar) { + const [key, ...rest] = path2; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && identity.isScalar(node) ? node.value : node; + else + return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined; } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!identity.isPair(node)) + return false; + const n4 = node.value; + return n4 == null || allowScalar && identity.isScalar(n4) && n4.value == null && !n4.commentBefore && !n4.comment && !n4.tag; + }); } - catch(onrejected) { - return this.parse().catch(onrejected); + hasIn(path2) { + const [key, ...rest] = path2; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return identity.isCollection(node) ? node.hasIn(rest) : false; } - finally(onfinally) { - return this.parse().finally(onfinally); + setIn(path2, value) { + const [key, ...rest] = path2; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (identity.isCollection(node)) + node.setIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } } - }; - _APIPromise_client = new WeakMap; + } + exports.Collection = Collection; + exports.collectionFromPath = collectionFromPath; + exports.isEmptyPath = isEmptyPath; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/pagination.mjs -var _AbstractPage_client, AbstractPage, PagePromise, Page, PageCursor; -var init_pagination = __esm(() => { - init_tslib(); - init_error5(); - init_parse5(); - init_api_promise(); - init_values4(); - AbstractPage = class AbstractPage { - constructor(client2, response, body, options) { - _AbstractPage_client.set(this, undefined); - __classPrivateFieldSet(this, _AbstractPage_client, client2, "f"); - this.options = options; - this.response = response; - this.body = body; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyComment.js +var require_stringifyComment = __commonJS((exports) => { + var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); + function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; + } + var lineComment = (str, indent, comment) => str.endsWith(` +`) ? indentComment(comment, indent) : comment.includes(` +`) ? ` +` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; + exports.indentComment = indentComment; + exports.lineComment = lineComment; + exports.stringifyComment = stringifyComment; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/foldFlowLines.js +var require_foldFlowLines = __commonJS((exports) => { + var FOLD_FLOW = "flow"; + var FOLD_BLOCK = "block"; + var FOLD_QUOTED = "quoted"; + function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + for (let ch;ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; } - return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + if (ch === ` +`) { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = undefined; + } else { + if (ch === " " && prev && prev !== " " && prev !== ` +` && prev !== "\t") { + const next = text[i + 1]; + if (next && next !== " " && next !== ` +` && next !== "\t") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === "\t") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } else { + overflow = true; + } + } + } + prev = ch; } - async* iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0;i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; } } - async* [(_AbstractPage_client = new WeakMap, Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } + return res; + } + function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === "\t") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== ` +`); + end = i; + start = i + 1; + ch = text[start]; } } - }; - PagePromise = class PagePromise extends APIPromise { - constructor(client2, request, Page) { - super(client2, request, async (client3, props) => new Page(client3, props.response, await defaultParseResponse(client3, props), props.options)); + return end; + } + exports.FOLD_BLOCK = FOLD_BLOCK; + exports.FOLD_FLOW = FOLD_FLOW; + exports.FOLD_QUOTED = FOLD_QUOTED; + exports.foldFlowLines = foldFlowLines; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyString.js +var require_stringifyString = __commonJS((exports) => { + var Scalar = require_Scalar(); + var foldFlowLines = require_foldFlowLines(); + var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0;i < strLen; ++i) { + if (str[i] === ` +`) { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } } - async* [Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; + return true; + } + function doubleQuotedString(value, ctx) { + const json3 = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json3; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json3[i];ch; ch = json3[++i]) { + if (ch === " " && json3[i + 1] === "\\" && json3[i + 2] === "n") { + str += json3.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; } + if (ch === "\\") + switch (json3[i + 1]) { + case "u": + { + str += json3.slice(start, i); + const code = json3.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json3.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json3[i + 2] === '"' || json3.length < minMultiLineLength) { + i += 1; + } else { + str += json3.slice(start, i) + ` + +`; + while (json3[i + 2] === "\\" && json3[i + 3] === "n" && json3[i + 4] !== '"') { + str += ` +`; + i += 2; + } + str += indent; + if (json3[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } } - }; - Page = class Page extends AbstractPage { - constructor(client2, response, body, options) { - super(client2, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.first_id = body.first_id || null; - this.last_id = body.last_id || null; + str = start ? str + json3.slice(start) : json3; + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); + } + function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(` +`) || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; } - getPaginatedItems() { - return this.data ?? []; + return qs(value, ctx); + } + var blockEndNewlines; + try { + blockEndNewlines = new RegExp(`(^|(? +`; + let chomp; + let endStart; + for (endStart = value.length;endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== ` +` && ch !== "\t" && ch !== " ") + break; } - nextPageRequestOptions() { - if (this.options.query?.["before_id"]) { - const first_id = this.first_id; - if (!first_id) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - before_id: first_id - } - }; - } - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - after_id: cursor - } - }; + let end = value.substring(endStart); + const endNlPos = end.indexOf(` +`); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; } - }; - PageCursor = class PageCursor extends AbstractPage { - constructor(client2, response, body, options) { - super(client2, response, body, options); - this.data = body.data || []; - this.next_page = body.next_page || null; + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === ` +`) + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); } - getPaginatedItems() { - return this.data ?? []; + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0;startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === ` +`) + startNlPos = startEnd; + else + break; } - nextPageRequestOptions() { - const cursor = this.next_page; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: cursor - } - }; + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/uploads.mjs -function makeFile(fileBits, fileName, options) { - checkFileSupport(); - return new File(fileBits, fileName ?? "unknown_file", options); -} -function getName(value, stripPath) { - const val = typeof value === "object" && value !== null && (("name" in value) && value.name && String(value.name) || ("url" in value) && value.url && String(value.url) || ("filename" in value) && value.filename && String(value.filename) || ("path" in value) && value.path && String(value.path)) || ""; - return stripPath ? val.split(/[\\/]/).pop() || undefined : val; -} -function supportsFormData(fetchObject) { - const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; - const cached2 = supportsFormDataMap.get(fetch2); - if (cached2) - return cached2; - const promise2 = (async () => { - try { - const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; - const data = new FormData; - if (data.toString() === await new FetchResponse(data).text()) { - return false; + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal3) { + const foldedValue = value.replace(/\n+/g, ` +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; } - return true; - } catch { - return true; + const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; } - })(); - supportsFormDataMap.set(fetch2, promise2); - return promise2; -} -var checkFileSupport = () => { - if (typeof File === "undefined") { - const { process: process3 } = globalThis; - const isOldNode = typeof process3?.versions?.node === "string" && parseInt(process3.versions.node.split(".")) < 20; - throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); - } -}, isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", multipartFormRequestOptions = async (opts, fetch2, stripFilenames = true) => { - return { ...opts, body: await createForm(opts.body, fetch2, stripFilenames) }; -}, supportsFormDataMap, createForm = async (body, fetch2, stripFilenames = true) => { - if (!await supportsFormData(fetch2)) { - throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); - } - const form = new FormData; - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames))); - return form; -}, isNamedBlob = (value) => value instanceof Blob && ("name" in value), addFormValue = async (form, key, value, stripFilenames) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value}${end}`; } - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - form.append(key, String(value)); - } else if (value instanceof Response) { - let options = {}; - const contentType = value.headers.get("Content-Type"); - if (contentType) { - options = { type: contentType }; + function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes(` +`) || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); } - form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); - } else if (isAsyncIterable2(value)) { - form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); - } else if (isNamedBlob(value)) { - form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); - } else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames))); - } else if (typeof value === "object") { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); - } else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -var init_uploads = __esm(() => { - supportsFormDataMap = /* @__PURE__ */ new WeakMap; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/to-file.mjs -async function toFile(value, name, options) { - checkFileSupport(); - value = await value; - name || (name = getName(value, true)); - if (isFileLike(value)) { - if (value instanceof File && name == null && options == null) { - return value; + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes(` +`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); } - return makeFile([await value.arrayBuffer()], name ?? value.name, { - type: value.type, - lastModified: value.lastModified, - ...options - }); - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await getBytes2(blob), name, options); - } - const parts = await getBytes2(value); - if (!options?.type) { - const type = parts.find((part) => typeof part === "object" && ("type" in part) && part.type); - if (typeof type === "string") { - options = { ...options, type }; + if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(` +`)) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat: compat3, tags } = ctx.doc.schema; + if (tags.some(test) || compat3?.some(test)) + return quotedString(value, ctx); } + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); } - return makeFile(parts, name, options); -} -async function getBytes2(value) { - let parts = []; - if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) { - parts.push(value); - } else if (isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } else if (isAsyncIterable2(value)) { - for await (const chunk of value) { - parts.push(...await getBytes2(chunk)); + function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.Scalar.QUOTE_DOUBLE; } - } else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + const _stringify3 = (_type) => { + switch (_type) { + case Scalar.Scalar.BLOCK_FOLDED: + case Scalar.Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify3(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify3(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; } - return parts; -} -function propsForError(value) { - if (typeof value !== "object" || value === null) - return ""; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; -} -var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; -var init_to_file = __esm(() => { - init_uploads(); - init_uploads(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/uploads.mjs -var init_uploads2 = __esm(() => { - init_to_file(); + exports.stringifyString = stringifyString; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/shared.mjs -var init_shared = () => {}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/core/resource.mjs -class APIResource { - constructor(client2) { - this._client = client2; - } -} - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/headers.mjs -function* iterateHeaders2(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringify.js +var require_stringify3 = __commonJS((exports) => { + var anchors = require_anchors(); + var identity = require_identity(); + var stringifyComment = require_stringifyComment(); + var stringifyString = require_stringifyString(); + function createStringifyContext(doc3, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment.stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc3.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; } - return; + return { + anchors: new Set, + doc: doc3, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } else if (isReadonlyArray(headers)) { - iter = headers; - } else { - shouldClear = true; - iter = Object.entries(headers ?? {}); + function getTagObject(tags, item) { + if (item.tag) { + const match2 = tags.filter((t) => t.tag === item.tag); + if (match2.length > 0) + return match2.find((t) => t.format === item.format) ?? match2[0]; + } + let tagObj = undefined; + let obj; + if (identity.isScalar(item)) { + obj = item.value; + let match2 = tags.filter((t) => t.identify?.(obj)); + if (match2.length > 1) { + const testMatch = match2.filter((t) => t.test); + if (testMatch.length > 0) + match2 = testMatch; + } + tagObj = match2.find((t) => t.format === item.format) ?? match2.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; } - for (let row of iter) { - const name = row[0]; - if (typeof name !== "string") - throw new TypeError("expected header name to be a string"); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; + function stringifyProps(node, tagObj, { anchors: anchors$1, doc: doc3 }) { + if (!doc3.directives) + return ""; + const props = []; + const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; + if (anchor && anchors.anchorIsValid(anchor)) { + anchors$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc3.directives.tagString(tag)); + return props.join(" "); + } + function stringify5(item, ctx, onComment, onChompKeep) { + if (identity.isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (identity.isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = new Set([item]); + item = item.resolve(ctx.doc); } - yield [name, value]; } + let tagObj = undefined; + const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; } -} -var brand_privateNullableHeaders, buildHeaders = (newHeaders) => { - const targetHeaders = new Headers; - const nullHeaders = new Set; - for (const headers of newHeaders) { - const seenHeaders = new Set; - for (const [name, value] of iterateHeaders2(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); + exports.createStringifyContext = createStringifyContext; + exports.stringify = stringify5; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyPair.js +var require_stringifyPair = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var stringify5 = require_stringify3(); + var stringifyComment = require_stringifyComment(); + function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc: doc3, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = identity.isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); + if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify5.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc3.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity.isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify5.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? ` +` : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${stringifyComment.indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === ` +` && valueComment) + ws = ` + +`; } else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && identity.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf(` +`); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; } + } else if (valueStr === "" || valueStr[0] === ` +`) { + ws = ""; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); } + return str; } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -var init_headers = __esm(() => { - init_values4(); - brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders"); + exports.stringifyPair = stringifyPair; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -var EMPTY, createPathTagFunction = (pathEncoder = encodeURIPath) => function path3(statics, ...params) { - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path4 = statics.reduce((previousValue, currentValue, index2) => { - if (/[?#]/.test(currentValue)) { - postPath = true; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/log.js +var require_log = __commonJS((exports) => { + var node_process = __require("process"); + function debug(logLevel, ...messages) { + if (logLevel === "debug") + console.log(...messages); + } + function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + if (typeof node_process.emitWarning === "function") + node_process.emitWarning(warning); + else + console.warn(warning); } - const value = params[index2]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); - if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { - encoded = value + ""; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` - }); + } + exports.debug = debug; + exports.warn = warn; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/merge.js +var require_merge = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var MERGE_KEY = "<<"; + var merge3 = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY + }; + var isMergeKey = (ctx, key) => (merge3.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge3.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge3.tag && tag.default); + function addMergeToJSMap(ctx, map3, value) { + const source = resolveAliasValue(ctx, value); + if (identity.isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map3, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map3, it); + else + mergeValue(ctx, map3, source); + } + function mergeValue(ctx, map3, value) { + const source = resolveAliasValue(ctx, value); + if (!identity.isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map3 instanceof Map) { + if (!map3.has(key)) + map3.set(key, value2); + } else if (map3 instanceof Set) { + map3.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map3, key)) { + Object.defineProperty(map3, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } } - return previousValue + currentValue + (index2 === params.length ? "" : encoded); - }, ""); - const pathOnly = path4.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match2; - while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match2.index, - length: match2[0].length, - error: `Value "${match2[0]}" can't be safely passed as a path parameter` - }); + return map3; } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = " ".repeat(segment.start - lastEnd); - const arrows = "^".repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ""); - throw new AnthropicError(`Path parameters result in path with invalid segments: -${invalidSegments.map((e) => e.error).join(` -`)} -${path4} -${underline}`); + function resolveAliasValue(ctx, value) { + return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; } - return path4; -}, path3; -var init_path = __esm(() => { - init_error5(); - EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); - path3 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + exports.addMergeToJSMap = addMergeToJSMap; + exports.isMergeKey = isMergeKey; + exports.merge = merge3; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/environments.mjs -var Environments; -var init_environments = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Environments = class Environments extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/environments?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/addPairToJSMap.js +var require_addPairToJSMap = __commonJS((exports) => { + var log = require_log(); + var merge3 = require_merge(); + var stringify5 = require_stringify3(); + var identity = require_identity(); + var toJS = require_toJS(); + function addPairToJSMap(ctx, map3, { key, value }) { + if (identity.isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map3, value); + else if (merge3.isMergeKey(ctx, key)) + merge3.addMergeToJSMap(ctx, map3, value); + else { + const jsKey = toJS.toJS(key, "", ctx); + if (map3 instanceof Map) { + map3.set(jsKey, toJS.toJS(value, jsKey, ctx)); + } else if (map3 instanceof Set) { + map3.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS.toJS(value, stringKey, ctx); + if (stringKey in map3) + Object.defineProperty(map3, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map3[stringKey] = jsValue; + } } - retrieve(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/environments/${environmentID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + return map3; + } + function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (identity.isNode(key) && ctx?.doc) { + const strCtx = stringify5.createStringifyContext(ctx.doc, {}); + strCtx.anchors = new Set; + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; } - update(environmentID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/environments/${environmentID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + return JSON.stringify(jsKey); + } + exports.addPairToJSMap = addPairToJSMap; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/Pair.js +var require_Pair = __commonJS((exports) => { + var createNode = require_createNode(); + var stringifyPair = require_stringifyPair(); + var addPairToJSMap = require_addPairToJSMap(); + var identity = require_identity(); + function createPair(key, value, ctx) { + const k = createNode.createNode(key, undefined, ctx); + const v = createNode.createNode(value, undefined, ctx); + return new Pair(k, v); + } + + class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); + this.key = key; + this.value = value; } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/environments?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + clone(schema) { + let { key, value } = this; + if (identity.isNode(key)) + key = key.clone(schema); + if (identity.isNode(value)) + value = value.clone(schema); + return new Pair(key, value); } - delete(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/environments/${environmentID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? new Map : {}; + return addPairToJSMap.addPairToJSMap(ctx, pair, this); } - archive(environmentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/environments/${environmentID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); } - }; + } + exports.Pair = Pair; + exports.createPair = createPair; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs -function wasCreatedByStainlessHelper(value) { - return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value; -} -function collectStainlessHelpers(tools, messages) { - const helpers = new Set; - if (tools) { - for (const tool2 of tools) { - if (wasCreatedByStainlessHelper(tool2)) { - helpers.add(tool2[SDK_HELPER_SYMBOL]); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyCollection.js +var require_stringifyCollection = __commonJS((exports) => { + var identity = require_identity(); + var stringify5 = require_stringify3(); + var stringifyComment = require_stringifyComment(); + function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify6 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify6(collection, ctx, options); + } + function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0;i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (identity.isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify5.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i = 1;i < lines.length; ++i) { + const line = lines[i]; + str += line ? ` +${indent}${line}` : ` +`; } } + if (comment) { + str += ` +` + stringifyComment.indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; } - if (messages) { - for (const message of messages) { - if (wasCreatedByStainlessHelper(message)) { - helpers.add(message[SDK_HELPER_SYMBOL]); + function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0;i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = identity.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } } - if (Array.isArray(message.content)) { - for (const block of message.content) { - if (wasCreatedByStainlessHelper(block)) { - helpers.add(block[SDK_HELPER_SYMBOL]); - } + if (comment) + reqNewline = true; + let str = stringify5.stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str.includes(` +`)); + if (i < items.length - 1) { + str += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str += ","; } } + if (comment) + str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : ` +`; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } } } - return Array.from(helpers); -} -function stainlessHelperHeader(tools, messages) { - const helpers = collectStainlessHelpers(tools, messages); - if (helpers.length === 0) - return {}; - return { "x-stainless-helper": helpers.join(", ") }; -} -function stainlessHelperHeaderFromFile(file2) { - if (wasCreatedByStainlessHelper(file2)) { - return { "x-stainless-helper": file2[SDK_HELPER_SYMBOL] }; + function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = stringifyComment.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } } - return {}; -} -var SDK_HELPER_SYMBOL; -var init_stainless_helper_header = __esm(() => { - SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper"); + exports.stringifyCollection = stringifyCollection; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs -var Files; -var init_files = __esm(() => { - init_pagination(); - init_headers(); - init_stainless_helper_header(); - init_uploads(); - init_path(); - Files = class Files extends APIResource { - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/files?beta=true", Page, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, - options?.headers - ]) - }); - } - delete(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/files/${fileID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLMap.js +var require_YAMLMap = __commonJS((exports) => { + var stringifyCollection = require_stringifyCollection(); + var addPairToJSMap = require_addPairToJSMap(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + function findPair(items, key) { + const k = identity.isScalar(key) ? key.value : key; + for (const it of items) { + if (identity.isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (identity.isScalar(it.key) && it.key.value === k) + return it; + } } - download(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/files/${fileID}/content?beta=true`, { - ...options, - headers: buildHeaders([ - { - "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(), - Accept: "application/binary" - }, - options?.headers - ]), - __binaryResponse: true - }); + return; + } + + class YAMLMap extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; } - retrieveMetadata(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/files/${fileID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, - options?.headers - ]) - }); + constructor(schema) { + super(identity.MAP, schema); + this.items = []; } - upload(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/files?beta=true", multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, - stainlessHelperHeaderFromFile(body.file), - options?.headers - ]) - }, this._client)); + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map3 = new this(schema); + const add = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== undefined || keepUndefined) + map3.items.push(Pair.createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema.sortMapEntries === "function") { + map3.items.sort(schema.sortMapEntries); + } + return map3; } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs -var Models; -var init_models = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Models = class Models extends APIResource { - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/models/${modelID}?beta=true`, { - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - options?.headers - ]) - }); + add(pair, overwrite) { + let _pair; + if (identity.isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair.Pair(pair, pair?.value); + } else + _pair = new Pair.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/models?beta=true", Page, { - query: query3, - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - options?.headers - ]) - }); + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs -var UserProfiles; -var init_user_profiles = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - UserProfiles = class UserProfiles extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/user_profiles?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, - options?.headers - ]) - }); + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined; } - retrieve(userProfileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/user_profiles/${userProfileID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, - options?.headers - ]) - }); + has(key) { + return !!findPair(this.items, key); } - update(userProfileID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/user_profiles/${userProfileID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, - options?.headers - ]) - }); + set(key, value) { + this.add(new Pair.Pair(key, value), true); } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/user_profiles?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, - options?.headers - ]) - }); + toJSON(_, ctx, Type) { + const map3 = Type ? new Type : ctx?.mapAsMap ? new Map : {}; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const item of this.items) + addPairToJSMap.addPairToJSMap(ctx, map3, item); + return map3; } - createEnrollmentURL(userProfileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, - options?.headers - ]) + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!identity.isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment }); } - }; + } + exports.YAMLMap = YAMLMap; + exports.findPair = findPair; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs -var Versions; -var init_versions2 = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Versions = class Versions extends APIResource { - list(agentID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/agents/${agentID}/versions?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/map.js +var require_map = __commonJS((exports) => { + var identity = require_identity(); + var YAMLMap = require_YAMLMap(); + var map3 = { + collection: "map", + default: true, + nodeClass: YAMLMap.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map4, onError2) { + if (!identity.isMap(map4)) + onError2("Expected a mapping for this tag"); + return map4; + }, + createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) }; + exports.map = map3; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs -var Agents; -var init_agents3 = __esm(() => { - init_versions2(); - init_versions2(); - init_pagination(); - init_headers(); - init_path(); - Agents = class Agents extends APIResource { - constructor() { - super(...arguments); - this.versions = new Versions(this._client); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLSeq.js +var require_YAMLSeq = __commonJS((exports) => { + var createNode = require_createNode(); + var stringifyCollection = require_stringifyCollection(); + var Collection = require_Collection(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var toJS = require_toJS(); + + class YAMLSeq extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; } - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/agents?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + constructor(schema) { + super(identity.SEQ, schema); + this.items = []; } - retrieve(agentID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.get(path3`/v1/agents/${agentID}?beta=true`, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + add(value) { + this.items.push(value); } - update(agentID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/agents/${agentID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/agents?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - archive(agentID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/agents/${agentID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return; + const it = this.items[idx]; + return !keepScalar && identity.isScalar(it) ? it.value : it; } - }; - Agents.Versions = Versions; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs -var Memories; -var init_memories = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Memories = class Memories extends APIResource { - create(memoryStoreID, params, options) { - const { view: view2, betas, ...body } = params; - return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, { - query: { view: view2 }, - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; } - retrieve(memoryID, params, options) { - const { memory_store_id, betas, ...query3 } = params; - return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity.isScalar(prev) && Scalar.isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; } - update(memoryID, params, options) { - const { memory_store_id, view: view2, betas, ...body } = params; - return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query: { view: view2 }, - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJS.toJS(item, String(i++), ctx)); + return seq; } - list(memoryStoreID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment }); } - delete(memoryID, params, options) { - const { memory_store_id, expected_content_sha256, betas } = params; - return this._client.delete(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { - query: { expected_content_sha256 }, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode.createNode(it, undefined, ctx)); + } + } + return seq; } - }; + } + function asItemIndex(key) { + let idx = identity.isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; + } + exports.YAMLSeq = YAMLSeq; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs -var MemoryVersions; -var init_memory_versions = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - MemoryVersions = class MemoryVersions extends APIResource { - retrieve(memoryVersionID, params, options) { - const { memory_store_id, betas, ...query3 } = params; - return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - list(memoryStoreID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - redact(memoryVersionID, params, options) { - const { memory_store_id, betas } = params; - return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/seq.js +var require_seq = __commonJS((exports) => { + var identity = require_identity(); + var YAMLSeq = require_YAMLSeq(); + var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError2) { + if (!identity.isSeq(seq2)) + onError2("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) }; + exports.seq = seq; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs -var MemoryStores; -var init_memory_stores = __esm(() => { - init_memories(); - init_memories(); - init_memory_versions(); - init_memory_versions(); - init_pagination(); - init_headers(); - init_path(); - MemoryStores = class MemoryStores extends APIResource { - constructor() { - super(...arguments); - this.memories = new Memories(this._client); - this.memoryVersions = new MemoryVersions(this._client); - } - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/memory_stores?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - retrieve(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - update(memoryStoreID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/memory_stores?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - delete(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - archive(memoryStoreID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/string.js +var require_string = __commonJS((exports) => { + var stringifyString = require_stringifyString(); + var string7 = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); } }; - MemoryStores.Memories = Memories; - MemoryStores.MemoryVersions = MemoryVersions; + exports.string = string7; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/error.mjs -var init_error6 = __esm(() => { - init_error5(); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/null.js +var require_null = __commonJS((exports) => { + var Scalar = require_Scalar(); + var nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar.Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + exports.nullTag = nullTag; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/constants.mjs -var MODEL_NONSTREAMING_TOKENS; -var init_constants7 = __esm(() => { - MODEL_NONSTREAMING_TOKENS = { - "claude-opus-4-20250514": 8192, - "claude-opus-4-0": 8192, - "claude-4-opus-20250514": 8192, - "anthropic.claude-opus-4-20250514-v1:0": 8192, - "claude-opus-4@20250514": 8192, - "claude-opus-4-1-20250805": 8192, - "anthropic.claude-opus-4-1-20250805-v1:0": 8192, - "claude-opus-4-1@20250805": 8192 +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/bool.js +var require_bool = __commonJS((exports) => { + var Scalar = require_Scalar(); + var boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } }; + exports.boolTag = boolTag; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs -function getOutputFormat(params) { - return params?.output_format ?? params?.output_config?.format; -} -function maybeParseBetaMessage(message, params, opts) { - const outputFormat = getOutputFormat(params); - if (!params || !("parse" in (outputFormat ?? {}))) { - return { - ...message, - content: message.content.map((block) => { - if (block.type === "text") { - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: null, - enumerable: false - }); - return Object.defineProperty(parsedBlock, "parsed", { - get() { - opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); - return null; - }, - enumerable: false - }); - } - return block; - }), - parsed_output: null - }; - } - return parseBetaMessage(message, params, opts); -} -function parseBetaMessage(message, params, opts) { - let firstParsedOutput = null; - const content = message.content.map((block) => { - if (block.type === "text") { - const parsedOutput = parseBetaOutputFormat(params, block.text); - if (firstParsedOutput === null) { - firstParsedOutput = parsedOutput; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js +var require_stringifyNumber = __commonJS((exports) => { + function stringifyNumber({ format: format3, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n4 = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format3 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n4) && !n4.includes("e")) { + let i = n4.indexOf("."); + if (i < 0) { + i = n4.length; + n4 += "."; } - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: parsedOutput, - enumerable: false - }); - return Object.defineProperty(parsedBlock, "parsed", { - get() { - opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); - return parsedOutput; - }, - enumerable: false - }); + let d = minFractionDigits - (n4.length - i - 1); + while (d-- > 0) + n4 += "0"; } - return block; - }); - return { - ...message, - content, - parsed_output: firstParsedOutput - }; -} -function parseBetaOutputFormat(params, content) { - const outputFormat = getOutputFormat(params); - if (outputFormat?.type !== "json_schema") { - return null; + return n4; } - try { - if ("parse" in outputFormat) { - return outputFormat.parse(content); + exports.stringifyNumber = stringifyNumber; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/float.js +var require_float = __commonJS((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } - return JSON.parse(content); - } catch (error52) { - throw new AnthropicError(`Failed to parse structured output: ${error52}`); + }; + var float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.float = float; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/int.js +var require_int = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber.stringifyNumber(node); } -} -var init_beta_parser = __esm(() => { - init_error5(); + var intOct = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: (node) => intStringify(node, 8, "0o") + }; + var int3 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int3; + exports.intHex = intHex; + exports.intOct = intOct; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs -var tokenize = (input) => { - let current = 0; - let tokens = []; - while (current < input.length) { - let char = input[current]; - if (char === "\\") { - current++; - continue; - } - if (char === "{") { - tokens.push({ - type: "brace", - value: "{" - }); - current++; - continue; - } - if (char === "}") { - tokens.push({ - type: "brace", - value: "}" - }); - current++; - continue; - } - if (char === "[") { - tokens.push({ - type: "paren", - value: "[" - }); - current++; - continue; - } - if (char === "]") { - tokens.push({ - type: "paren", - value: "]" - }); - current++; - continue; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/schema.js +var require_schema = __commonJS((exports) => { + var map3 = require_map(); + var _null7 = require_null(); + var seq = require_seq(); + var string7 = require_string(); + var bool = require_bool(); + var float = require_float(); + var int3 = require_int(); + var schema = [ + map3.map, + seq.seq, + string7.string, + _null7.nullTag, + bool.boolTag, + int3.intOct, + int3.int, + int3.intHex, + float.floatNaN, + float.floatExp, + float.float + ]; + exports.schema = schema; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/json/schema.js +var require_schema2 = __commonJS((exports) => { + var Scalar = require_Scalar(); + var map3 = require_map(); + var seq = require_seq(); + function intIdentify(value) { + return typeof value === "bigint" || Number.isInteger(value); + } + var stringifyJSON = ({ value }) => JSON.stringify(value); + var jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON } - if (char === ":") { - tokens.push({ - type: "separator", - value: ":" - }); - current++; - continue; + ]; + var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError2) { + onError2(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; } - if (char === ",") { - tokens.push({ - type: "delimiter", - value: "," - }); - current++; - continue; + }; + var schema = [map3.map, seq.seq].concat(jsonScalars, jsonError); + exports.schema = schema; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/binary.js +var require_binary = __commonJS((exports) => { + var node_buffer = __require("buffer"); + var Scalar = require_Scalar(); + var stringifyString = require_stringifyString(); + var binary = { + identify: (value) => value instanceof Uint8Array, + default: false, + tag: "tag:yaml.org,2002:binary", + resolve(src, onError2) { + if (typeof node_buffer.Buffer === "function") { + return node_buffer.Buffer.from(src, "base64"); + } else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0;i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError2("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ""; + const buf = value; + let str; + if (typeof node_buffer.Buffer === "function") { + str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0;i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.Scalar.BLOCK_LITERAL); + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n4 = Math.ceil(str.length / lineWidth); + const lines = new Array(n4); + for (let i = 0, o = 0;i < n4; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? ` +` : " "); + } + return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); } - if (char === '"') { - let value = ""; - let danglingQuote = false; - char = input[++current]; - while (char !== '"') { - if (current === input.length) { - danglingQuote = true; - break; + }; + exports.binary = binary; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +var require_pairs = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLSeq = require_YAMLSeq(); + function resolvePairs(seq, onError2) { + if (identity.isSeq(seq)) { + for (let i = 0;i < seq.items.length; ++i) { + let item = seq.items[i]; + if (identity.isPair(item)) + continue; + else if (identity.isMap(item)) { + if (item.items.length > 1) + onError2("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; } - if (char === "\\") { - current++; - if (current === input.length) { - danglingQuote = true; - break; + seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); + } + } else + onError2("Expected a sequence for this tag"); + return seq; + } + function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq.YAMLSeq(schema); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); } - value += char + input[current]; - char = input[++current]; } else { - value += char; - char = input[++current]; + key = it; } + pairs2.items.push(Pair.createPair(key, value, ctx)); } - char = input[++current]; - if (!danglingQuote) { - tokens.push({ - type: "string", - value - }); - } - continue; - } - let WHITESPACE = /\s/; - if (char && WHITESPACE.test(char)) { - current++; - continue; - } - let NUMBERS = /[0-9]/; - if (char && NUMBERS.test(char) || char === "-" || char === ".") { - let value = ""; - if (char === "-") { - value += char; - char = input[++current]; - } - while (char && NUMBERS.test(char) || char === ".") { - value += char; - char = input[++current]; - } - tokens.push({ - type: "number", - value - }); - continue; + return pairs2; + } + var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + exports.createPairs = createPairs; + exports.pairs = pairs; + exports.resolvePairs = resolvePairs; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js +var require_omap = __commonJS((exports) => { + var identity = require_identity(); + var toJS = require_toJS(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var pairs = require_pairs(); + + class YAMLOMap extends YAMLSeq.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; } - let LETTERS = /[a-z]/i; - if (char && LETTERS.test(char)) { - let value = ""; - while (char && LETTERS.test(char)) { - if (current === input.length) { - break; + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map3 = new Map; + if (ctx?.onCreate) + ctx.onCreate(map3); + for (const pair of this.items) { + let key, value; + if (identity.isPair(pair)) { + key = toJS.toJS(pair.key, "", ctx); + value = toJS.toJS(pair.value, key, ctx); + } else { + key = toJS.toJS(pair, "", ctx); } - value += char; - char = input[++current]; - } - if (value == "true" || value == "false" || value === "null") { - tokens.push({ - type: "name", - value - }); - } else { - current++; - continue; + if (map3.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map3.set(key, value); } - continue; + return map3; + } + static from(schema, iterable, ctx) { + const pairs$1 = pairs.createPairs(schema, iterable, ctx); + const omap2 = new this; + omap2.items = pairs$1.items; + return omap2; } - current++; - } - return tokens; -}, strip2 = (tokens) => { - if (tokens.length === 0) { - return tokens; } - let lastToken = tokens[tokens.length - 1]; - switch (lastToken.type) { - case "separator": - tokens = tokens.slice(0, tokens.length - 1); - return strip2(tokens); - break; - case "number": - let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; - if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") { - tokens = tokens.slice(0, tokens.length - 1); - return strip2(tokens); - } - case "string": - let tokenBeforeTheLastToken = tokens[tokens.length - 2]; - if (tokenBeforeTheLastToken?.type === "delimiter") { - tokens = tokens.slice(0, tokens.length - 1); - return strip2(tokens); - } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") { - tokens = tokens.slice(0, tokens.length - 1); - return strip2(tokens); + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + var omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq, onError2) { + const pairs$1 = pairs.resolvePairs(seq, onError2); + const seenKeys = []; + for (const { key } of pairs$1.items) { + if (identity.isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError2(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } } - break; - case "delimiter": - tokens = tokens.slice(0, tokens.length - 1); - return strip2(tokens); - break; + return Object.assign(new YAMLOMap, pairs$1); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) + }; + exports.YAMLOMap = YAMLOMap; + exports.omap = omap; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js +var require_bool2 = __commonJS((exports) => { + var Scalar = require_Scalar(); + function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; } - return tokens; -}, unstrip = (tokens) => { - let tail = []; - tokens.map((token) => { - if (token.type === "brace") { - if (token.value === "{") { - tail.push("}"); - } else { - tail.splice(tail.lastIndexOf("}"), 1); - } + var trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar.Scalar(true), + stringify: boolStringify + }; + var falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar.Scalar(false), + stringify: boolStringify + }; + exports.falseTag = falseTag; + exports.trueTag = trueTag; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js +var require_float2 = __commonJS((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } - if (token.type === "paren") { - if (token.value === "[") { - tail.push("]"); - } else { - tail.splice(tail.lastIndexOf("]"), 1); + }; + var float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f3 = str.substring(dot + 1).replace(/_/g, ""); + if (f3[f3.length - 1] === "0") + node.minFractionDigits = f3.length; } - } - }); - if (tail.length > 0) { - tail.reverse().map((item) => { - if (item === "}") { - tokens.push({ - type: "brace", - value: "}" - }); - } else if (item === "]") { - tokens.push({ - type: "paren", - value: "]" - }); + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.float = float; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js +var require_int2 = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") + offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; } - }); + const n5 = BigInt(str); + return sign === "-" ? BigInt(-1) * n5 : n5; + } + const n4 = parseInt(str, radix); + return sign === "-" ? -1 * n4 : n4; } - return tokens; -}, generate = (tokens) => { - let output = ""; - tokens.map((token) => { - switch (token.type) { - case "string": - output += '"' + token.value + '"'; - break; - default: - output += token.value; - break; + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; } - }); - return output; -}, partialParse = (input) => JSON.parse(generate(unstrip(strip2(tokenize(input))))); -var init_parser = () => {}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/streaming.mjs -var init_streaming2 = __esm(() => { - init_streaming(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs -function tracksToolInput(content) { - return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use"; -} -function checkNever(x) {} -var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY = "__json_buf", BetaMessageStream; -var init_BetaMessageStream = __esm(() => { - init_tslib(); - init_parser(); - init_error6(); - init_streaming2(); - init_beta_parser(); - BetaMessageStream = class BetaMessageStream { - constructor(params, opts) { - _BetaMessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _BetaMessageStream_currentMessageSnapshot.set(this, undefined); - _BetaMessageStream_params.set(this, null); - this.controller = new AbortController; - _BetaMessageStream_connectedPromise.set(this, undefined); - _BetaMessageStream_resolveConnectedPromise.set(this, () => {}); - _BetaMessageStream_rejectConnectedPromise.set(this, () => {}); - _BetaMessageStream_endPromise.set(this, undefined); - _BetaMessageStream_resolveEndPromise.set(this, () => {}); - _BetaMessageStream_rejectEndPromise.set(this, () => {}); - _BetaMessageStream_listeners.set(this, {}); - _BetaMessageStream_ended.set(this, false); - _BetaMessageStream_errored.set(this, false); - _BetaMessageStream_aborted.set(this, false); - _BetaMessageStream_catchingPromiseCreated.set(this, false); - _BetaMessageStream_response.set(this, undefined); - _BetaMessageStream_request_id.set(this, undefined); - _BetaMessageStream_logger.set(this, undefined); - _BetaMessageStream_handleError.set(this, (error52) => { - __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error52)) { - error52 = new APIUserAbortError; - } - if (error52 instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); - return this._emit("abort", error52); - } - if (error52 instanceof AnthropicError) { - return this._emit("error", error52); - } - if (error52 instanceof Error) { - const anthropicError = new AnthropicError(error52.message); - anthropicError.cause = error52; - return this._emit("error", anthropicError); - } - return this._emit("error", new AnthropicError(String(error52))); - }); - __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve2, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve2, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); - }), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {}); - __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {}); - __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + return stringifyNumber.stringifyNumber(node); + } + var intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") + }; + var intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") + }; + var int3 = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int3; + exports.intBin = intBin; + exports.intHex = intHex; + exports.intOct = intOct; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js +var require_set = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + + class YAMLSet extends YAMLMap.YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; } - get response() { - return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + add(key) { + let pair; + if (identity.isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair.Pair(key.key, null); + else + pair = new Pair.Pair(key, null); + const prev = YAMLMap.findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); } - get request_id() { - return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + get(key, keepPair) { + const pair = YAMLMap.findPair(this.items, key); + return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; } - async withResponse() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); - if (!response) { - throw new Error("Could not resolve a `Response` object"); + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap.findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair.Pair(key)); } - return { - data: this, - response, - request_id: response.headers.get("request-id") - }; } - static fromReadableStream(stream2) { - const runner = new BetaMessageStream(null); - runner._run(() => runner._fromReadableStream(stream2)); - return runner; + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); } - static createMessage(messages, params, options, { logger } = {}) { - const runner = new BetaMessageStream(params, { logger }); - for (const message of params.messages) { - runner._addMessageParam(message); - } - __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); - return runner; + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit("end"); - }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set4 = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set4.items.push(Pair.createPair(value, null, ctx)); + } + return set4; } - _addMessageParam(message) { - this.messages.push(message); + } + YAMLSet.tag = "tag:yaml.org,2002:set"; + var set3 = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map3, onError2) { + if (identity.isMap(map3)) { + if (map3.hasAllNullValues(true)) + return Object.assign(new YAMLSet, map3); + else + onError2("Set items must all have null values"); + } else + onError2("Expected a mapping for this tag"); + return map3; } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit("message", message); + }; + exports.YAMLSet = YAMLSet; + exports.set = set3; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +var require_timestamp = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n4) => asBigInt ? BigInt(n4) : Number(n4); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; + } + function stringifySexagesimal(node) { + let { value } = node; + let num = (n4) => n4; + if (typeof value === "bigint") + num = (n4) => BigInt(n4); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber.stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); } } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); + return sign + parts.map((n4) => String(n4).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + } + var intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal + }; + var floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal + }; + var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"), + resolve(str) { + const match2 = str.match(timestamp.test); + if (!match2) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match2.map(Number); + const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0; + let date10 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match2[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date10 -= 60000 * d; } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); - this._connected(response); - for await (const event of stream2) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream2.controller.signal?.aborted) { - throw new APIUserAbortError; - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) { - signal.removeEventListener("abort", abortHandler); - } + return new Date(date10); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + exports.floatTime = floatTime; + exports.intTime = intTime; + exports.timestamp = timestamp; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js +var require_schema3 = __commonJS((exports) => { + var map3 = require_map(); + var _null7 = require_null(); + var seq = require_seq(); + var string7 = require_string(); + var binary = require_binary(); + var bool = require_bool2(); + var float = require_float2(); + var int3 = require_int2(); + var merge3 = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var set3 = require_set(); + var timestamp = require_timestamp(); + var schema = [ + map3.map, + seq.seq, + string7.string, + _null7.nullTag, + bool.trueTag, + bool.falseTag, + int3.intBin, + int3.intOct, + int3.int, + int3.intHex, + float.floatNaN, + float.floatExp, + float.float, + binary.binary, + merge3.merge, + omap.omap, + pairs.pairs, + set3.set, + timestamp.intTime, + timestamp.floatTime, + timestamp.timestamp + ]; + exports.schema = schema; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js +var require_tags = __commonJS((exports) => { + var map3 = require_map(); + var _null7 = require_null(); + var seq = require_seq(); + var string7 = require_string(); + var bool = require_bool(); + var float = require_float(); + var int3 = require_int(); + var schema = require_schema(); + var schema$1 = require_schema2(); + var binary = require_binary(); + var merge3 = require_merge(); + var omap = require_omap(); + var pairs = require_pairs(); + var schema$2 = require_schema3(); + var set3 = require_set(); + var timestamp = require_timestamp(); + var schemas5 = new Map([ + ["core", schema.schema], + ["failsafe", [map3.map, seq.seq, string7.string]], + ["json", schema$1.schema], + ["yaml11", schema$2.schema], + ["yaml-1.1", schema$2.schema] + ]); + var tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int3.int, + intHex: int3.intHex, + intOct: int3.intOct, + intTime: timestamp.intTime, + map: map3.map, + merge: merge3.merge, + null: _null7.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq.seq, + set: set3.set, + timestamp: timestamp.timestamp + }; + var coreKnownTags = { + "tag:yaml.org,2002:binary": binary.binary, + "tag:yaml.org,2002:merge": merge3.merge, + "tag:yaml.org,2002:omap": omap.omap, + "tag:yaml.org,2002:pairs": pairs.pairs, + "tag:yaml.org,2002:set": set3.set, + "tag:yaml.org,2002:timestamp": timestamp.timestamp + }; + function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas5.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge3.merge) ? schemaTags.concat(merge3.merge) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas5.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); } } - _connected(response) { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit("connect"); + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); } - get ended() { - return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + if (addMergeTag) + tags = tags.concat(merge3.merge); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); + } + exports.coreKnownTags = coreKnownTags; + exports.getTags = getTags; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js +var require_Schema = __commonJS((exports) => { + var identity = require_identity(); + var map3 = require_map(); + var seq = require_seq(); + var string7 = require_string(); + var tags = require_tags(); + var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + + class Schema { + constructor({ compat: compat3, customTags, merge: merge3, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat3) ? tags.getTags(compat3, "compat") : compat3 ? tags.getTags(null, compat3) : null; + this.name = typeof schema === "string" && schema || "core"; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge3); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity.MAP, { value: map3.map }); + Object.defineProperty(this, identity.SCALAR, { value: string7.string }); + Object.defineProperty(this, identity.SEQ, { value: seq.seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; } - get errored() { - return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; } - get aborted() { - return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + exports.Schema = Schema; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js +var require_stringifyDocument = __commonJS((exports) => { + var identity = require_identity(); + var stringify5 = require_stringify3(); + var stringifyComment = require_stringifyComment(); + function stringifyDocument(doc3, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc3.directives) { + const dir = doc3.directives.toString(doc3); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc3.directives.docStart) + hasDirectives = true; } - abort() { - this.controller.abort(); + if (hasDirectives) + lines.push("---"); + const ctx = stringify5.createStringifyContext(doc3, options); + const { commentString } = ctx.options; + if (doc3.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc3.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, "")); } - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; + let chompKeep = false; + let contentComment = null; + if (doc3.contents) { + if (identity.isNode(doc3.contents)) { + if (doc3.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc3.contents.commentBefore) { + const cs = commentString(doc3.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc3.comment; + contentComment = doc3.contents.comment; + } + const onChompKeep = contentComment ? undefined : () => chompKeep = true; + let body = stringify5.stringify(doc3.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += stringifyComment.lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body}`; + } else + lines.push(body); + } else { + lines.push(stringify5.stringify(doc3.contents, ctx)); } - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index2 = listeners.findIndex((l) => l.listener === listener); - if (index2 >= 0) - listeners.splice(index2, 1); - return this; + if (doc3.directives?.docEnd) { + if (doc3.comment) { + const cs = commentString(doc3.comment); + if (cs.includes(` +`)) { + lines.push("..."); + lines.push(stringifyComment.indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc3.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(stringifyComment.indentComment(commentString(dc), "")); + } } - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; + return lines.join(` +`) + ` +`; + } + exports.stringifyDocument = stringifyDocument; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/Document.js +var require_Document = __commonJS((exports) => { + var Alias = require_Alias(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var toJS = require_toJS(); + var Schema = require_Schema(); + var stringifyDocument = require_stringifyDocument(); + var anchors = require_anchors(); + var applyReviver = require_applyReviver(); + var createNode = require_createNode(); + var directives = require_directives(); + + class Document2 { + constructor(value, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version: version6 } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version6 = this.directives.yaml.version; + } else + this.directives = new directives.Directives({ version: version6 }); + this.setSchema(version6, options); + this.contents = value === undefined ? null : this.createNode(value, _replacer, options); } - emitted(event) { - return new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - if (event !== "error") - this.once("error", reject); - this.once(event, resolve2); + clone() { + const copy = Object.create(Document2.prototype, { + [identity.NODE_TYPE]: { value: identity.DOC } }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; } - async done() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); } - get currentMessage() { - return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + addIn(path2, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path2, value); } - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + } + return new Alias.Alias(node.anchor); } - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + createNode(value, replacer, options) { + let _replacer = undefined; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a"); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity.isCollection(node)) + node.flow = true; + setAnchors(); + return node; } - _emit(event, ...args) { - if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) - return; - if (event === "end") { - __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair.Pair(k, v); + } + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + deleteIn(path2) { + if (Collection.isEmptyPath(path2)) { + if (this.contents == null) + return false; + this.contents = null; + return true; } - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); + return assertCollection(this.contents) ? this.contents.deleteIn(path2) : false; + } + get(key, keepScalar) { + return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined; + } + getIn(path2, keepScalar) { + if (Collection.isEmptyPath(path2)) + return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; + return identity.isCollection(this.contents) ? this.contents.getIn(path2, keepScalar) : undefined; + } + has(key) { + return identity.isCollection(this.contents) ? this.contents.has(key) : false; + } + hasIn(path2) { + if (Collection.isEmptyPath(path2)) + return this.contents !== undefined; + return identity.isCollection(this.contents) ? this.contents.hasIn(path2) : false; + } + set(key, value) { + if (this.contents == null) { + this.contents = Collection.collectionFromPath(this.schema, [key], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value); } - if (event === "abort") { - const error52 = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error52); - } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error52); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error52); - this._emit("end"); - return; + } + setIn(path2, value) { + if (Collection.isEmptyPath(path2)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = Collection.collectionFromPath(this.schema, Array.from(path2), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path2, value); } - if (event === "error") { - const error52 = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error52); + } + setSchema(version6, options = {}) { + if (typeof version6 === "number") + version6 = String(version6); + let opt; + switch (version6) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new directives.Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version6; + else + this.directives = new directives.Directives({ version: version6 }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version6); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error52); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error52); - this._emit("end"); } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema.Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); - } + toJS({ json: json3, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver: reviver2 } = {}) { + const ctx = { + anchors: new Map, + doc: this, + keep: !json3, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver2 === "function" ? applyReviver.applyReviver(reviver2, { "": res }, "", res) : res; } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream2 = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream2) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream2.controller.signal?.aborted) { - throw new APIUserAbortError; - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) { - signal.removeEventListener("abort", abortHandler); - } + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); } + return stringifyDocument.stringifyDocument(this, options); } - [(_BetaMessageStream_currentMessageSnapshot = new WeakMap, _BetaMessageStream_params = new WeakMap, _BetaMessageStream_connectedPromise = new WeakMap, _BetaMessageStream_resolveConnectedPromise = new WeakMap, _BetaMessageStream_rejectConnectedPromise = new WeakMap, _BetaMessageStream_endPromise = new WeakMap, _BetaMessageStream_resolveEndPromise = new WeakMap, _BetaMessageStream_rejectEndPromise = new WeakMap, _BetaMessageStream_listeners = new WeakMap, _BetaMessageStream_ended = new WeakMap, _BetaMessageStream_errored = new WeakMap, _BetaMessageStream_aborted = new WeakMap, _BetaMessageStream_catchingPromiseCreated = new WeakMap, _BetaMessageStream_response = new WeakMap, _BetaMessageStream_request_id = new WeakMap, _BetaMessageStream_logger = new WeakMap, _BetaMessageStream_handleError = new WeakMap, _BetaMessageStream_instances = new WeakSet, _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() { - if (this.receivedMessages.length === 0) { - throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + function assertCollection(contents) { + if (identity.isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); + } + exports.Document = Document2; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/errors.js +var require_errors = __commonJS((exports) => { + class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + } + + class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + } + + class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + } + var prettifyError3 = (src, lc) => (error90) => { + if (error90.pos[0] === -1) + return; + error90.linePos = error90.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error90.linePos[0]; + error90.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + `… +`; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error90.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); } - return this.receivedMessages.at(-1); - }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() { - if (this.receivedMessages.length === 0) { - throw new AnthropicError("stream ended without producing a Message with role=assistant"); + const pointer2 = " ".repeat(ci) + "^".repeat(count); + error90.message += `: + +${lineStr} +${pointer2} +`; + } + }; + exports.YAMLError = YAMLError; + exports.YAMLParseError = YAMLParseError; + exports.YAMLWarning = YAMLWarning; + exports.prettifyError = prettifyError3; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-props.js +var require_resolve_props = __commonJS((exports) => { + function resolveProps(tokens, { flow, indicator, next, offset, onError: onError2, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError2(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; } - const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); - if (textBlocks.length === 0) { - throw new AnthropicError("stream ended without producing a content block with type=text"); + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; } - return textBlocks.join(" "); - }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); - this._emit("streamEvent", event, messageSnapshot); - switch (event.type) { - case "content_block_delta": { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case "text_delta": { - if (content.type === "text") { - this._emit("text", event.delta.text, content.text || ""); - } - break; - } - case "citations_delta": { - if (content.type === "text") { - this._emit("citation", event.delta.citation, content.citations ?? []); - } - break; - } - case "input_json_delta": { - if (tracksToolInput(content) && content.input) { - this._emit("inputJson", event.delta.partial_json, content.input); - } - break; - } - case "thinking_delta": { - if (content.type === "thinking") { - this._emit("thinking", event.delta.thinking, content.thinking); - } - break; - } - case "signature_delta": { - if (content.type === "thinking") { - this._emit("signature", content.signature); - } - break; - } - case "compaction_delta": { - if (content.type === "compaction" && content.content) { - this._emit("compaction", content.content); - } - break; - } - default: - checkNever(event.delta); + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) { + tab = token; } + hasSpace = true; break; - } - case "message_stop": { - this._addMessageParam(messageSnapshot); - this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + case "comment": { + if (!hasSpace) + onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; break; } - case "content_block_stop": { - this._emit("contentBlock", messageSnapshot.content.at(-1)); + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; break; - } - case "message_start": { - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + case "anchor": + if (anchor) + onError2(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError2(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError2(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; break; } - case "content_block_start": - case "message_delta": + case indicator: + if (anchor || tag) + onError2(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; break; + case "comma": + if (flow) { + if (comma) + onError2(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + default: + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; } - }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() { - if (this.ended) { - throw new AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); - }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) { - let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (event.type === "message_start") { - if (snapshot) { - throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; + } + exports.resolveProps = resolveProps; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-contains-newline.js +var require_util_contains_newline = __commonJS((exports) => { + function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes(` +`)) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; } - return event.message; - } - if (!snapshot) { - throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - } - switch (event.type) { - case "message_stop": - return snapshot; - case "message_delta": - snapshot.container = event.delta.container; - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - snapshot.context_management = event.context_management; - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - if (event.usage.iterations != null) { - snapshot.usage.iterations = event.usage.iterations; - } - return snapshot; - case "content_block_start": - snapshot.content.push(event.content_block); - return snapshot; - case "content_block_delta": { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case "text_delta": { - if (snapshotContent?.type === "text") { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || "") + event.delta.text - }; - } - break; - } - case "citations_delta": { - if (snapshotContent?.type === "text") { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...snapshotContent.citations ?? [], event.delta.citation] - }; - } - break; - } - case "input_json_delta": { - if (snapshotContent && tracksToolInput(snapshotContent)) { - let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ""; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true - }); - if (jsonBuf) { - try { - newContent.input = partialParse(jsonBuf); - } catch (err) { - const error52 = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); - __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error52); - } - } - snapshot.content[event.index] = newContent; - } - break; - } - case "thinking_delta": { - if (snapshotContent?.type === "thinking") { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking - }; - } - break; - } - case "signature_delta": { - if (snapshotContent?.type === "thinking") { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature - }; - } - break; - } - case "compaction_delta": { - if (snapshotContent?.type === "compaction") { - snapshot.content[event.index] = { - ...snapshotContent, - content: (snapshotContent.content || "") + event.delta.content - }; - } - break; - } - default: - checkNever(event.delta); + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; } - return snapshot; + if (containsNewline(it.key) || containsNewline(it.value)) + return true; } - case "content_block_stop": - return snapshot; + return false; + default: + return true; + } + } + exports.containsNewline = containsNewline; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-flow-indent-check.js +var require_util_flow_indent_check = __commonJS((exports) => { + var utilContainsNewline = require_util_contains_newline(); + function flowIndentCheck(indent, fc, onError2) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError2(end, "BAD_INDENT", msg, true); } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on("streamEvent", (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } else { - pushQueue.push(event); - } + } + } + exports.flowIndentCheck = flowIndentCheck; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-map-includes.js +var require_util_map_includes = __commonJS((exports) => { + var identity = require_identity(); + function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); + } + exports.mapIncludes = mapIncludes; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-map.js +var require_resolve_block_map = __commonJS((exports) => { + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + var utilMapIncludes = require_util_map_includes(); + var startColMsg = "All mapping items must start at the same column"; + function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError2, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; + const map3 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep: sep2, value } = collItem; + const keyProps = resolveProps.resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep2?.[0], + offset, + onError: onError2, + parentIndent: bm.indent, + startOnNewline: true }); - this.on("end", () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError2(offset, "BAD_INDENT", startColMsg); } - readQueue.length = 0; - }); - this.on("abort", (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + if (!keyProps.anchor && !keyProps.tag && !sep2) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map3.comment) + map3.comment += ` +` + keyProps.comment; + else + map3.comment = keyProps.comment; + } + continue; } - readQueue.length = 0; - }); - this.on("error", (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); + if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { + onError2(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); } - readQueue.length = 0; + } else if (keyProps.found?.indent !== bm.indent) { + onError2(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode(ctx, key, keyProps, onError2) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError2); + ctx.atKey = false; + if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode)) + onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps.resolveProps(sep2 ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError: onError2, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true }); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) + onError2(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); } - }; - } - toReadableStream() { - const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream2.toReadableStream(); - } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs -var ToolError; -var init_ToolError = __esm(() => { - ToolError = class ToolError extends Error { - constructor(content) { - const message = typeof content === "string" ? content : content.map((block) => { - if (block.type === "text") - return block.text; - return `[${block.type}]`; - }).join(" "); - super(message); - this.name = "ToolError"; - this.content = content; + const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : composeEmptyNode(ctx, offset, sep2, null, valueProps, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError2); + offset = valueNode.range[2]; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } else { + if (implicitKey) + onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += ` +` + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair.Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map3.items.push(pair); + } } - }; + if (commentEnd && commentEnd < offset) + onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map3.range = [bm.offset, offset, commentEnd ?? offset]; + return map3; + } + exports.resolveBlockMap = resolveBlockMap; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs -var DEFAULT_TOKEN_THRESHOLD = 1e5, DEFAULT_SUMMARY_PROMPT3 = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: -1. Task Overview -The user's core request and success criteria -Any clarifications or constraints they specified -2. Current State -What has been completed so far -Files created, modified, or analyzed (with paths if relevant) -Key outputs or artifacts produced -3. Important Discoveries -Technical constraints or requirements uncovered -Decisions made and their rationale -Errors encountered and how they were resolved -What approaches were tried that didn't work (and why) -4. Next Steps -Specific actions needed to complete the task -Any blockers or open questions to resolve -Priority order if multiple steps remain -5. Context to Preserve -User preferences or style requirements -Domain-specific details that aren't obvious -Any promises made to the user -Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. -Wrap your summary in tags.`; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs -function promiseWithResolvers() { - let resolve2; - let reject; - const promise2 = new Promise((res, rej) => { - resolve2 = res; - reject = rej; - }); - return { promise: promise2, resolve: resolve2, reject }; -} -async function generateToolResponse(params, lastMessage = params.messages.at(-1), requestOptions) { - if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") { - return null; - } - const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use"); - if (toolUseBlocks.length === 0) { - return null; - } - const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { - const tool2 = params.tools.find((t) => ("name" in t ? t.name : t.mcp_server_name) === toolUse.name); - if (!tool2 || !("run" in tool2)) { - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: `Error: Tool '${toolUse.name}' not found`, - is_error: true - }; - } - try { - let input = toolUse.input; - if ("parse" in tool2 && tool2.parse) { - input = tool2.parse(input); - } - const result = await tool2.run(input, { - toolUseBlock: toolUse, - signal: requestOptions?.signal +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-seq.js +var require_resolve_block_seq = __commonJS((exports) => { + var YAMLSeq = require_YAMLSeq(); + var resolveProps = require_resolve_props(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError2, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; + const seq = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps.resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError: onError2, + parentIndent: bs.indent, + startOnNewline: true }); - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: result - }; - } catch (error52) { - return { - type: "tool_result", - tool_use_id: toolUse.id, - content: error52 instanceof ToolError ? error52.content : `Error: ${error52 instanceof Error ? error52.message : String(error52)}`, - is_error: true - }; - } - })); - return { - role: "user", - content: toolResults - }; -} -var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse, BetaToolRunner; -var init_BetaToolRunner = __esm(() => { - init_tslib(); - init_ToolError(); - init_error5(); - init_headers(); - init_stainless_helper_header(); - BetaToolRunner = class BetaToolRunner { - constructor(client2, params, options) { - _BetaToolRunner_instances.add(this); - this.client = client2; - _BetaToolRunner_consumed.set(this, false); - _BetaToolRunner_mutated.set(this, false); - _BetaToolRunner_state.set(this, undefined); - _BetaToolRunner_options.set(this, undefined); - _BetaToolRunner_message.set(this, undefined); - _BetaToolRunner_toolResponse.set(this, undefined); - _BetaToolRunner_completion.set(this, undefined); - _BetaToolRunner_iterationCount.set(this, 0); - __classPrivateFieldSet(this, _BetaToolRunner_state, { - params: { - ...params, - messages: structuredClone(params.messages) + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === "block-seq") + onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError2(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq.comment = props.comment; + continue; } - }, "f"); - const helpers = collectStainlessHelpers(params.tools, params.messages); - const helperValue = ["BetaToolRunner", ...helpers].join(", "); - __classPrivateFieldSet(this, _BetaToolRunner_options, { - ...options, - headers: buildHeaders([{ "x-stainless-helper": helperValue }, options?.headers]) - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - if (params.compactionControl?.enabled) { - console.warn("Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. " + 'Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. ' + "See https://platform.claude.com/docs/en/build-with-claude/compaction"); } + const node = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, start, null, props, onError2); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError2); + offset = node.range[2]; + seq.items.push(node); } - async* [(_BetaToolRunner_consumed = new WeakMap, _BetaToolRunner_mutated = new WeakMap, _BetaToolRunner_state = new WeakMap, _BetaToolRunner_options = new WeakMap, _BetaToolRunner_message = new WeakMap, _BetaToolRunner_toolResponse = new WeakMap, _BetaToolRunner_completion = new WeakMap, _BetaToolRunner_iterationCount = new WeakMap, _BetaToolRunner_instances = new WeakSet, _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact2() { - const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; - if (!compactionControl || !compactionControl.enabled) { - return false; - } - let tokensUsed = 0; - if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) { - try { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0); - tokensUsed = totalInputTokens + message.usage.output_tokens; - } catch { - return false; + seq.range = [bs.offset, offset, commentEnd ?? offset]; + return seq; + } + exports.resolveBlockSeq = resolveBlockSeq; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-end.js +var require_resolve_end = __commonJS((exports) => { + function resolveEnd(end, offset, reqSpace, onError2) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep2 = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep2 + cb; + sep2 = ""; + break; + } + case "newline": + if (comment) + sep2 += source; + hasSpace = true; + break; + default: + onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); } + offset += source.length; } - const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; - if (tokensUsed < threshold) { - return false; - } - const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; - const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT3; - const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; - if (messages[messages.length - 1].role === "assistant") { - const lastMessage = messages[messages.length - 1]; - if (Array.isArray(lastMessage.content)) { - const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use"); - if (nonToolBlocks.length === 0) { - messages.pop(); - } else { - lastMessage.content = nonToolBlocks; + } + return { comment, offset }; + } + exports.resolveEnd = resolveEnd; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-collection.js +var require_resolve_flow_collection = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilMapIncludes = require_util_map_includes(); + var blockMsg = "Block collections are not allowed within flow collections"; + var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError2, tag) { + const isMap = fc.start.source === "{"; + const fcName = isMap ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0;i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep: sep2, value } = collItem; + const props = resolveProps.resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep2?.[0], + offset, + onError: onError2, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep2 && !value) { + if (i === 0 && props.comma) + onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += ` +` + props.comment; + else + coll.comment = props.comment; } + offset = props.end; + continue; } + if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) + onError2(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); } - const response = await this.client.beta.messages.create({ - model, - messages: [ - ...messages, - { - role: "user", - content: [ - { - type: "text", - text: summaryPrompt + if (i === 0) { + if (props.comma) + onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: + for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; } - ] + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity.isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += ` +` + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); } - ], - max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens - }, { - signal: __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal, - headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, { "x-stainless-helper": "compaction" }]) - }); - if (response.content[0]?.type !== "text") { - throw new AnthropicError("Expected text response for compaction"); - } - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ - { - role: "user", - content: response.content } - ]; - return true; - }, Symbol.asyncIterator)]() { - var _a3; - if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - throw new AnthropicError("Cannot iterate over a consumed stream"); } - __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - try { - while (true) { - let stream2; - try { - if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { - break; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a3 = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a3++, _a3), "f"); - __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); - const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - if (params.stream) { - stream2 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); - __classPrivateFieldSet(this, _BetaToolRunner_message, stream2.finalMessage(), "f"); - __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => {}); - yield stream2; - } else { - __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - } - const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); - if (!isCompacted) { - if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); - } - const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); - if (toolMessage) { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); - } else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - break; + if (!isMap && !sep2 && !props.found) { + const valueNode = value ? composeNode(ctx, value, props, onError2) : composeEmptyNode(ctx, props.end, sep2, null, props, onError2); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode(ctx, key, props, onError2) : composeEmptyNode(ctx, keyStart, start, null, props, onError2); + if (isBlock(key)) + onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps.resolveProps(sep2 ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError: onError2, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep2) + for (const st of sep2) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError2(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } } - } - } finally { - if (stream2) { - stream2.abort(); - } + if (props.start < valueProps.found.offset - 1024) + onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); } + } else if (value) { + if ("source" in value && value.source?.[0] === ":") + onError2(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); } - if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { - throw new AnthropicError("ToolRunner concluded without a message from the server"); + const valueNode = value ? composeNode(ctx, value, valueProps, onError2) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep2, null, valueProps, onError2) : null; + if (valueNode) { + if (isBlock(value)) + onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += ` +` + valueProps.comment; + else + keyNode.comment = valueProps.comment; } - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); - } catch (error52) { - __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => {}); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error52); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - throw error52; - } - } - setMessagesParams(paramsOrMutator) { - if (typeof paramsOrMutator === "function") { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); - } else { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - } - setRequestOptions(optionsOrMutator) { - if (typeof optionsOrMutator === "function") { - __classPrivateFieldSet(this, _BetaToolRunner_options, optionsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - } else { - __classPrivateFieldSet(this, _BetaToolRunner_options, { ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), ...optionsOrMutator }, "f"); - } - } - async generateToolResponse(signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1); - if (!message) { - return null; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap) { + const map3 = coll; + if (utilMapIncludes.mapIncludes(ctx, map3.items, keyNode)) + onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map3.items.push(pair); + } else { + const map3 = new YAMLMap.YAMLMap(ctx.schema); + map3.flow = true; + map3.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map3.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map3); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; } - return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message, signal); } - done() { - return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + const expectedEnd = isMap ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError2(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); } - async runUntilDone() { - if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - for await (const _ of this) {} + if (ee.length > 0) { + const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError2); + if (end.comment) { + if (coll.comment) + coll.comment += ` +` + end.comment; + else + coll.comment = end.comment; } - return this.done(); - } - get params() { - return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - } - pushMessages(...messages) { - this.setMessagesParams((params) => ({ - ...params, - messages: [...params.messages, ...messages] - })); - } - then(onfulfilled, onrejected) { - return this.runUntilDone().then(onfulfilled, onrejected); - } - }; - _BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage, signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { - if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; } - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage, { - ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), - signal - }), "f"); - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); - }; + return coll; + } + exports.resolveFlowCollection = resolveFlowCollection; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs -var JSONLDecoder; -var init_jsonl = __esm(() => { - init_error5(); - init_line(); - JSONLDecoder = class JSONLDecoder { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-collection.js +var require_compose_collection = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveBlockMap = require_resolve_block_map(); + var resolveBlockSeq = require_resolve_block_seq(); + var resolveFlowCollection = require_resolve_flow_collection(); + function resolveCollection(CN, ctx, token, onError2, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError2, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError2, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError2, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; } - async* decoder() { - const lineDecoder = new LineDecoder; - for await (const chunk of this.iterator) { - for (const line of lineDecoder.decode(chunk)) { - yield JSON.parse(line); - } - } - for (const line of lineDecoder.flush()) { - yield JSON.parse(line); + if (tagName) + coll.tag = tagName; + return coll; + } + function composeCollection(CN, ctx, token, props, onError2) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError2(lastProp, "MISSING_CHAR", message); } } - [Symbol.asyncIterator]() { - return this.decoder(); + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN, ctx, token, onError2, tagName); } - static fromResponse(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { - throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); } - throw new AnthropicError(`Attempted to iterate over a response with no body`); + return resolveCollection(CN, ctx, token, onError2, tagName); } - return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); } - }; + const coll = resolveCollection(CN, ctx, token, onError2, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = identity.isNode(res) ? res : new Scalar.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; + } + exports.composeCollection = composeCollection; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs -var Batches; -var init_batches = __esm(() => { - init_pagination(); - init_headers(); - init_jsonl(); - init_error6(); - init_path(); - Batches = class Batches extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/messages/batches?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, - options?.headers - ]) - }); - } - retrieve(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, - options?.headers - ]) - }); - } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/messages/batches?beta=true", Page, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, - options?.headers - ]) - }); - } - delete(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-block-scalar.js +var require_resolve_block_scalar = __commonJS((exports) => { + var Scalar = require_Scalar(); + function resolveBlockScalar(ctx, scalar, onError2) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1;i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; } - cancel(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, - options?.headers - ]) - }); + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? ` +`.repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; } - async results(messageBatchID, params = {}, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0;i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError2(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError2(offset, "BAD_INDENT", message); + } + break; } - const { betas } = params ?? {}; - return this._client.get(batch.results_url, { - ...options, - headers: buildHeaders([ - { - "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), - Accept: "application/binary" - }, - options?.headers - ]), - stream: true, - __binaryResponse: true - })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + offset += indent.length + content.length + 1; } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs -function transformOutputFormat(params) { - if (!params.output_format) { - return params; - } - if (params.output_config?.format) { - throw new AnthropicError("Both output_format and output_config.format were provided. " + "Please use only output_config.format (output_format is deprecated)."); - } - const { output_format, ...rest } = params; - return { - ...rest, - output_config: { - ...params.output_config, - format: output_format + for (let i = lines.length - 1;i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; } - }; -} -var DEPRECATED_MODELS, MODELS_TO_WARN_WITH_THINKING_ENABLED, Messages; -var init_messages8 = __esm(() => { - init_error6(); - init_constants7(); - init_headers(); - init_stainless_helper_header(); - init_beta_parser(); - init_BetaMessageStream(); - init_BetaToolRunner(); - init_ToolError(); - init_batches(); - init_batches(); - init_BetaToolRunner(); - init_ToolError(); - DEPRECATED_MODELS = { - "claude-1.3": "November 6th, 2024", - "claude-1.3-100k": "November 6th, 2024", - "claude-instant-1.1": "November 6th, 2024", - "claude-instant-1.1-100k": "November 6th, 2024", - "claude-instant-1.2": "November 6th, 2024", - "claude-3-sonnet-20240229": "July 21st, 2025", - "claude-3-opus-20240229": "January 5th, 2026", - "claude-2.1": "July 21st, 2025", - "claude-2.0": "July 21st, 2025", - "claude-3-7-sonnet-latest": "February 19th, 2026", - "claude-3-7-sonnet-20250219": "February 19th, 2026" - }; - MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-mythos-preview", "claude-opus-4-6"]; - Messages = class Messages extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches(this._client); - } - create(params, options) { - const modifiedParams = transformOutputFormat(params); - const { betas, ...body } = modifiedParams; - if (body.model in DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]} -Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - if (MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) && body.thinking && body.thinking.type === "enabled") { - console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + let value = ""; + let sep2 = ""; + let prevMoreIndented = false; + for (let i = 0;i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + ` +`; + for (let i = contentStart;i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError2(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + if (type === Scalar.Scalar.BLOCK_LITERAL) { + value += sep2 + indent.slice(trimIndent) + content; + sep2 = ` +`; + } else if (indent.length > trimIndent || content[0] === "\t") { + if (sep2 === " ") + sep2 = ` +`; + else if (!prevMoreIndented && sep2 === ` +`) + sep2 = ` + +`; + value += sep2 + indent.slice(trimIndent) + content; + sep2 = ` +`; + prevMoreIndented = true; + } else if (content === "") { + if (sep2 === ` +`) + value += ` +`; + else + sep2 = ` +`; + } else { + value += sep2 + content; + sep2 = " "; + prevMoreIndented = false; } - const helperHeader = stainlessHelperHeader(body.tools, body.messages); - return this._client.post("/v1/messages?beta=true", { - body, - timeout: timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - helperHeader, - options?.headers - ]), - stream: modifiedParams.stream ?? false - }); } - parse(params, options) { - options = { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() }, - options?.headers - ]) - }; - return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart;i < lines.length; ++i) + value += ` +` + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== ` +`) + value += ` +`; + break; + default: + value += ` +`; } - stream(body, options) { - return BetaMessageStream.createMessage(this, body, options); + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + function parseBlockScalarHeader({ offset, props }, strict, onError2) { + if (props[0].type !== "block-scalar-header") { + onError2(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; } - countTokens(params, options) { - const modifiedParams = transformOutputFormat(params); - const { betas, ...body } = modifiedParams; - return this._client.post("/v1/messages/count_tokens?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() }, - options?.headers - ]) - }); + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error90 = -1; + for (let i = 1;i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n4 = Number(ch); + if (!indent && n4) + indent = n4; + else if (error90 === -1) + error90 = offset + i; + } } - toolRunner(body, options) { - return new BetaToolRunner(this._client, body, options); + if (error90 !== -1) + onError2(error90, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1;i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError2(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError2(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError2(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } } - }; - Messages.Batches = Batches; - Messages.BetaToolRunner = BetaToolRunner; - Messages.ToolError = ToolError; + return { mode, indent, chomp, comment, length }; + } + function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines = [line0]; + for (let i = 1;i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; + } + exports.resolveBlockScalar = resolveBlockScalar; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs -var Events; -var init_events = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Events = class Events extends APIResource { - list(sessionID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/sessions/${sessionID}/events?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - send(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/sessions/${sessionID}/events?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - stream(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/sessions/${sessionID}/events/stream?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]), - stream: true - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/resolve-flow-scalar.js +var require_resolve_flow_scalar = __commonJS((exports) => { + var Scalar = require_Scalar(); + var resolveEnd = require_resolve_end(); + function resolveFlowScalar(scalar, strict, onError2) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError2(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + default: + onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs -var Resources; -var init_resources = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Resources = class Resources extends APIResource { - retrieve(resourceID, params, options) { - const { session_id, betas } = params; - return this._client.get(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError2); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; + } + function plainValue(source, onError2) { + let badChar = ""; + switch (source[0]) { + case "\t": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } } - update(resourceID, params, options) { - const { session_id, betas, ...body } = params; - return this._client.post(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + if (badChar) + onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); + } + function singleQuotedValue(source, onError2) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError2(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + } + function foldLines(source) { + let first, line; + try { + first = new RegExp(`(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } } - add(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/sessions/${sessionID}/resources?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + if (source[source.length - 1] !== '"' || source.length === 1) + onError2(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; + } + function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === "\t" || ch === ` +` || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== ` +`) + break; + if (ch === ` +`) + fold += ` +`; + offset += 1; + ch = source[offset + 1]; } + if (!fold) + fold = " "; + return { fold, offset }; + } + var escapeCodes = { + "0": "\x00", + a: "\x07", + b: "\b", + e: "\x1B", + f: "\f", + n: ` +`, + r: "\r", + t: "\t", + v: "\v", + N: "…", + _: " ", + L: "\u2028", + P: "\u2029", + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + "\t": "\t" }; + function parseCharCode(source, offset, length, onError2) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw2 = source.substr(offset - 2, length + 2); + onError2(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw2}`); + return raw2; + } + } + exports.resolveFlowScalar = resolveFlowScalar; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs -var Sessions; -var init_sessions = __esm(() => { - init_events(); - init_events(); - init_resources(); - init_resources(); - init_pagination(); - init_headers(); - init_path(); - Sessions = class Sessions extends APIResource { - constructor() { - super(...arguments); - this.events = new Events(this._client); - this.resources = new Resources(this._client); - } - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/sessions?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - retrieve(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/sessions/${sessionID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - update(sessionID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/sessions/${sessionID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-scalar.js +var require_compose_scalar = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + function composeScalar(ctx, token, tagToken, onError2) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError2) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError2); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[identity.SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError2); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError2); + else + tag = ctx.schema[identity.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); + } catch (error90) { + const msg = error90 instanceof Error ? error90.message : String(error90); + onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar.Scalar(value); } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/sessions?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; + } + function findScalarTagByName(schema, value, tagName, tagToken, onError2) { + if (tagName === "!") + return schema[identity.SCALAR]; + const matchWithTest = []; + for (const tag of schema.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } } - delete(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/sessions/${sessionID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); + return kt; } - archive(sessionID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/sessions/${sessionID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema[identity.SCALAR]; + } + function findScalarTagByTest({ atKey, directives, schema }, value, token, onError2) { + const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR]; + if (schema.compat) { + const compat3 = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR]; + if (tag.tag !== compat3.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat3.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError2(token, "TAG_RESOLVE_FAILED", msg, true); + } } - }; - Sessions.Events = Events; - Sessions.Resources = Resources; + return tag; + } + exports.composeScalar = composeScalar; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs -var Versions2; -var init_versions3 = __esm(() => { - init_pagination(); - init_headers(); - init_uploads(); - init_path(); - Versions2 = class Versions2 extends APIResource { - create(skillID, params = {}, options) { - const { betas, ...body } = params ?? {}; - return this._client.post(path3`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }, this._client)); - } - retrieve(version4, params, options) { - const { skill_id, betas } = params; - return this._client.get(path3`/v1/skills/${skill_id}/versions/${version4}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); - } - list(skillID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/skills/${skillID}/versions?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); - } - delete(version4, params, options) { - const { skill_id, betas } = params; - return this._client.delete(path3`/v1/skills/${skill_id}/versions/${version4}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/util-empty-scalar-position.js +var require_util_empty_scalar_position = __commonJS((exports) => { + function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1;i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } } - }; + return offset; + } + exports.emptyScalarPosition = emptyScalarPosition; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs -var Skills; -var init_skills = __esm(() => { - init_versions3(); - init_versions3(); - init_pagination(); - init_headers(); - init_uploads(); - init_path(); - Skills = class Skills extends APIResource { - constructor() { - super(...arguments); - this.versions = new Versions2(this._client); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-node.js +var require_compose_node = __commonJS((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var composeCollection = require_compose_collection(); + var composeScalar = require_compose_scalar(); + var resolveEnd = require_resolve_end(); + var utilEmptyScalarPosition = require_util_empty_scalar_position(); + var CN = { composeNode, composeEmptyNode }; + function composeNode(ctx, token, props, onError2) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError2); + if (anchor || tag) + onError2(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar.composeScalar(ctx, token, tag, onError2); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection.composeCollection(CN, ctx, token, props, onError2); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error90) { + const message = error90 instanceof Error ? error90.message : String(error90); + onError2(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError2(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } } - create(params = {}, options) { - const { betas, ...body } = params ?? {}; - return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }, this._client, false)); + node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError2)); + if (anchor && node.anchor === "") + onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError2(tag ?? token, "NON_STRING_KEY", msg); } - retrieve(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/skills?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; + } + function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError2) { + const token = { + type: "scalar", + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError2); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); } - delete(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, - options?.headers - ]) - }); + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; } - }; - Skills.Versions = Versions2; + return node; + } + function composeAlias({ options }, { offset, source, end }, onError2) { + const alias = new Alias.Alias(source.substring(1)); + if (alias.source === "") + onError2(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError2(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError2); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; + } + exports.composeEmptyNode = composeEmptyNode; + exports.composeNode = composeNode; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs -var Credentials; -var init_credentials = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Credentials = class Credentials extends APIResource { - create(vaultID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/vaults/${vaultID}/credentials?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - retrieve(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.get(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - update(credentialID, params, options) { - const { vault_id, betas, ...body } = params; - return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - list(vaultID, params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList(path3`/v1/vaults/${vaultID}/credentials?beta=true`, PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - delete(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.delete(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - archive(credentialID, params, options) { - const { vault_id, betas } = params; - return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/compose-doc.js +var require_compose_doc = __commonJS((exports) => { + var Document2 = require_Document(); + var composeNode = require_compose_node(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + function composeDoc(options, directives, { offset, start, value, end }, onError2) { + const opts = Object.assign({ _directives: directives }, options); + const doc3 = new Document2.Document(undefined, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc3.directives, + options: doc3.options, + schema: doc3.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError: onError2, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc3.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); } - }; + doc3.contents = value ? composeNode.composeNode(ctx, value, props, onError2) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError2); + const contentEnd = doc3.contents.range[2]; + const re = resolveEnd.resolveEnd(end, contentEnd, false, onError2); + if (re.comment) + doc3.comment = re.comment; + doc3.range = [offset, contentEnd, re.offset]; + return doc3; + } + exports.composeDoc = composeDoc; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs -var Vaults; -var init_vaults = __esm(() => { - init_credentials(); - init_credentials(); - init_pagination(); - init_headers(); - init_path(); - Vaults = class Vaults extends APIResource { - constructor() { - super(...arguments); - this.credentials = new Credentials(this._client); - } - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/vaults?beta=true", { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/compose/composer.js +var require_composer = __commonJS((exports) => { + var node_process = __require("process"); + var directives = require_directives(); + var Document2 = require_Document(); + var errors7 = require_errors(); + var identity = require_identity(); + var composeDoc = require_compose_doc(); + var resolveEnd = require_resolve_end(); + function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; + } + function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0;i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? ` + +` : ` +`) + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } } - retrieve(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/vaults/${vaultID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); - } - update(vaultID, params, options) { - const { betas, ...body } = params; - return this._client.post(path3`/v1/vaults/${vaultID}?beta=true`, { - body, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + return { comment, afterEmptyLine }; + } + + class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new errors7.YAMLWarning(pos, code, message)); + else + this.errors.push(new errors7.YAMLParseError(pos, code, message)); + }; + this.directives = new directives.Directives({ version: options.version || "1.2" }); + this.options = options; } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/vaults?beta=true", PageCursor, { - query: query3, - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + decorate(doc3, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc3.contents; + if (afterDoc) { + doc3.comment = doc3.comment ? `${doc3.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc3.directives.docStart || !dc) { + doc3.commentBefore = comment; + } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity.isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + for (let i = 0;i < this.errors.length; ++i) + doc3.errors.push(this.errors[i]); + for (let i = 0;i < this.warnings.length; ++i) + doc3.warnings.push(this.warnings[i]); + } else { + doc3.errors = this.errors; + doc3.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; } - delete(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path3`/v1/vaults/${vaultID}?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; } - archive(vaultID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path3`/v1/vaults/${vaultID}/archive?beta=true`, { - ...options, - headers: buildHeaders([ - { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, - options?.headers - ]) - }); + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); } - }; - Vaults.Credentials = Credentials; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs -var Beta; -var init_beta = __esm(() => { - init_environments(); - init_environments(); - init_files(); - init_files(); - init_models(); - init_models(); - init_user_profiles(); - init_user_profiles(); - init_agents3(); - init_agents3(); - init_memory_stores(); - init_memory_stores(); - init_messages8(); - init_messages8(); - init_sessions(); - init_sessions(); - init_skills(); - init_skills(); - init_vaults(); - init_vaults(); - Beta = class Beta extends APIResource { - constructor() { - super(...arguments); - this.models = new Models(this._client); - this.messages = new Messages(this._client); - this.agents = new Agents(this._client); - this.environments = new Environments(this._client); - this.sessions = new Sessions(this._client); - this.vaults = new Vaults(this._client); - this.memoryStores = new MemoryStores(this._client); - this.files = new Files(this._client); - this.skills = new Skills(this._client); - this.userProfiles = new UserProfiles(this._client); + *next(token) { + if (node_process.env.LOG_STREAM) + console.dir(token, { depth: null }); + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc3 = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc3.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc3, false); + if (this.doc) + yield this.doc; + this.doc = doc3; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error90 = new errors7.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error90); + else + this.doc.errors.push(error90); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new errors7.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new errors7.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } } - }; - Beta.Models = Models; - Beta.Messages = Messages; - Beta.Agents = Agents; - Beta.Environments = Environments; - Beta.Sessions = Sessions; - Beta.Vaults = Vaults; - Beta.MemoryStores = MemoryStores; - Beta.Files = Files; - Beta.Skills = Skills; - Beta.UserProfiles = UserProfiles; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/completions.mjs -var Completions; -var init_completions = __esm(() => { - init_headers(); - Completions = class Completions extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post("/v1/complete", { - body, - timeout: this._client._options.timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - options?.headers - ]), - stream: params.stream ?? false - }); + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc3 = new Document2.Document(undefined, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc3.range = [0, endOffset, endOffset]; + this.decorate(doc3, false); + yield doc3; + } } - }; + } + exports.Composer = Composer; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/parser.mjs -function getOutputFormat2(params) { - return params?.output_config?.format; -} -function maybeParseMessage(message, params, opts) { - const outputFormat = getOutputFormat2(params); - if (!params || !("parse" in (outputFormat ?? {}))) { - return { - ...message, - content: message.content.map((block) => { - if (block.type === "text") { - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: null, - enumerable: false - }); - return parsedBlock; - } - return block; - }), - parsed_output: null - }; - } - return parseMessage(message, params, opts); -} -function parseMessage(message, params, opts) { - let firstParsedOutput = null; - const content = message.content.map((block) => { - if (block.type === "text") { - const parsedOutput = parseOutputFormat(params, block.text); - if (firstParsedOutput === null) { - firstParsedOutput = parsedOutput; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-scalar.js +var require_cst_scalar = __commonJS((exports) => { + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + var errors7 = require_errors(); + var stringifyString = require_stringifyString(); + function resolveAsScalar(token, strict = true, onError2) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError2) + onError2(offset, code, message); + else + throw new errors7.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); } - const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { - value: parsedOutput, - enumerable: false - }); - return parsedBlock; } - return block; - }); - return { - ...message, - content, - parsed_output: firstParsedOutput - }; -} -function parseOutputFormat(params, content) { - const outputFormat = getOutputFormat2(params); - if (outputFormat?.type !== "json_schema") { return null; } - try { - if ("parse" in outputFormat) { - return outputFormat.parse(content); + function createScalarToken(value, context2) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context2; + const source = stringifyString.stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context2.end ?? [ + { type: "newline", offset: -1, indent, source: ` +` } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf(` +`); + const head = source.substring(0, he); + const body = source.substring(he + 1) + ` +`; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: ` +` }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; } - return JSON.parse(content); - } catch (error52) { - throw new AnthropicError(`Failed to parse structured output: ${error52}`); } -} -var init_parser2 = __esm(() => { - init_error5(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs -function tracksToolInput2(content) { - return content.type === "tool_use" || content.type === "server_tool_use"; -} -function checkNever2(x) {} -var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2 = "__json_buf", MessageStream; -var init_MessageStream = __esm(() => { - init_tslib(); - init_error6(); - init_streaming2(); - init_parser(); - init_parser2(); - MessageStream = class MessageStream { - constructor(params, opts) { - _MessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _MessageStream_currentMessageSnapshot.set(this, undefined); - _MessageStream_params.set(this, null); - this.controller = new AbortController; - _MessageStream_connectedPromise.set(this, undefined); - _MessageStream_resolveConnectedPromise.set(this, () => {}); - _MessageStream_rejectConnectedPromise.set(this, () => {}); - _MessageStream_endPromise.set(this, undefined); - _MessageStream_resolveEndPromise.set(this, () => {}); - _MessageStream_rejectEndPromise.set(this, () => {}); - _MessageStream_listeners.set(this, {}); - _MessageStream_ended.set(this, false); - _MessageStream_errored.set(this, false); - _MessageStream_aborted.set(this, false); - _MessageStream_catchingPromiseCreated.set(this, false); - _MessageStream_response.set(this, undefined); - _MessageStream_request_id.set(this, undefined); - _MessageStream_logger.set(this, undefined); - _MessageStream_handleError.set(this, (error52) => { - __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error52)) { - error52 = new APIUserAbortError; - } - if (error52 instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); - return this._emit("abort", error52); - } - if (error52 instanceof AnthropicError) { - return this._emit("error", error52); - } - if (error52 instanceof Error) { - const anthropicError = new AnthropicError(error52.message); - anthropicError.cause = error52; - return this._emit("error", anthropicError); + function setScalarValue(token, value, context2 = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context2; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; } - return this._emit("error", new AnthropicError(String(error52))); - }); - __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve2, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve2, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); - }), "f"); - __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {}); - __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {}); - __classPrivateFieldSet(this, _MessageStream_params, params, "f"); - __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); - } - get response() { - return __classPrivateFieldGet(this, _MessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); - } - async withResponse() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); - if (!response) { - throw new Error("Could not resolve a `Response` object"); + default: + type = "PLAIN"; } - return { - data: this, - response, - request_id: response.headers.get("request-id") - }; + const source = stringifyString.stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); } - static fromReadableStream(stream2) { - const runner = new MessageStream(null); - runner._run(() => runner._fromReadableStream(stream2)); - return runner; + } + function setBlockScalarValue(token, source) { + const he = source.indexOf(` +`); + const head = source.substring(0, he); + const body = source.substring(he + 1) + ` +`; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined)) + props.push({ type: "newline", offset: -1, indent, source: ` +` }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); } - static createMessage(messages, params, options, { logger } = {}) { - const runner = new MessageStream(params, { logger }); - for (const message of params.messages) { - runner._addMessageParam(message); + } + function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; + } + function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; } - __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f"); - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit("end"); - }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit("message", message); + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: ` +` }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); } } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); + } + exports.createScalarToken = createScalarToken; + exports.resolveAsScalar = resolveAsScalar; + exports.setScalarValue = setScalarValue; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-stringify.js +var require_cst_stringify = __commonJS((exports) => { + var stringify5 = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst); + function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); - this._connected(response); - for await (const event of stream2) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - } - if (stream2.controller.signal?.aborted) { - throw new APIUserAbortError; - } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) { - signal.removeEventListener("abort", abortHandler); - } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; } } - _connected(response) { - if (this.ended) + } + function stringifyItem({ start, key, sep: sep2, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep2) + for (const st of sep2) + res += st.source; + if (value) + res += stringifyToken(value); + return res; + } + exports.stringify = stringify5; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst-visit.js +var require_cst_visit = __commonJS((exports) => { + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove item"); + function visit(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); + } + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + visit.itemAtPath = (cst, path2) => { + let item = cst; + for (const [field, index2] of path2) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index2]; + } else return; - __classPrivateFieldSet(this, _MessageStream_response, response, "f"); - __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f"); - __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit("connect"); } - get ended() { - return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + return item; + }; + visit.parentCollection = (cst, path2) => { + const parent = visit.itemAtPath(cst, path2.slice(0, -1)); + const field = path2[path2.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); + }; + function _visit(path2, item, visitor) { + let ctrl = visitor(item, path2); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0;i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path2.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path2); + } } - get errored() { - return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + return typeof ctrl === "function" ? ctrl(item, path2) : ctrl; + } + exports.visit = visit; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/cst.js +var require_cst = __commonJS((exports) => { + var cstScalar = require_cst_scalar(); + var cstStringify = require_cst_stringify(); + var cstVisit = require_cst_visit(); + var BOM = "\uFEFF"; + var DOCUMENT = "\x02"; + var FLOW_END = "\x18"; + var SCALAR = "\x1F"; + var isCollection = (token) => !!token && ("items" in token); + var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR: + return ""; + default: + return JSON.stringify(token); } - get aborted() { - return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case ` +`: + case `\r +`: + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; } - abort() { - this.controller.abort(); + switch (source[0]) { + case " ": + case "\t": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; } - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; + return null; + } + exports.createScalarToken = cstScalar.createScalarToken; + exports.resolveAsScalar = cstScalar.resolveAsScalar; + exports.setScalarValue = cstScalar.setScalarValue; + exports.stringify = cstStringify.stringify; + exports.visit = cstVisit.visit; + exports.BOM = BOM; + exports.DOCUMENT = DOCUMENT; + exports.FLOW_END = FLOW_END; + exports.SCALAR = SCALAR; + exports.isCollection = isCollection; + exports.isScalar = isScalar; + exports.prettyToken = prettyToken; + exports.tokenType = tokenType; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/lexer.js +var require_lexer = __commonJS((exports) => { + var cst = require_cst(); + function isEmpty2(ch) { + switch (ch) { + case undefined: + case " ": + case ` +`: + case "\r": + case "\t": + return true; + default: + return false; } - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index2 = listeners.findIndex((l) => l.listener === listener); - if (index2 >= 0) - listeners.splice(index2, 1); - return this; + } + var hexDigits = new Set("0123456789ABCDEFabcdef"); + var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + var flowIndicatorChars = new Set(",[]{}"); + var invalidAnchorChars = new Set(` ,[]{} +\r `); + var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + + class Lexer { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; } - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); } - emitted(event) { - return new Promise((resolve2, reject) => { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - if (event !== "error") - this.once("error", reject); - this.once(event, resolve2); - }); + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === "\t") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === ` +`) + return true; + if (ch === "\r") + return this.buffer[i + 1] === ` +`; + return false; } - async done() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + charAt(n4) { + return this.buffer[this.pos + n4]; } - get currentMessage() { - return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === ` +` || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === ` +` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty2(this.buffer[offset + 3])) + return -1; + } + return offset; } - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf(` +`, this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); } - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + hasChars(n4) { + return this.pos + n4 <= this.buffer.length; } - _emit(event, ...args) { - if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) - return; - if (event === "end") { - __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n4) { + return this.buffer.substr(this.pos, n4); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); } - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === cst.BOM) { + yield* this.pushCount(1); + line = line.substring(1); } - if (event === "abort") { - const error52 = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error52); + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === "\t") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error52); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error52); - this._emit("end"); - return; + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === "\t") + dirEnd -= 1; + else + break; + } + const n4 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n4); + this.pushNewline(); + return "stream"; } - if (event === "error") { - const error52 = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error52); + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield cst.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty2(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error52); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error52); - this._emit("end"); } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty2(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty2(ch1)) { + const n4 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n4; + return "block-start"; } + return "doc"; } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener("abort", abortHandler); + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n4 = yield* this.pushIndicators(); + switch (line[n4]) { + case "#": + yield* this.pushCount(line.length - n4); + case undefined: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n4 += yield* this.parseBlockScalarHeader(); + n4 += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n4); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream2 = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream2) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; } - if (stream2.controller.signal?.aborted) { - throw new APIUserAbortError; + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty2(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield cst.FLOW_END; + return yield* this.parseLineStart(); } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } finally { - if (signal && abortHandler) { - signal.removeEventListener("abort", abortHandler); + } + let n4 = 0; + while (line[n4] === ",") { + n4 += yield* this.pushCount(1); + n4 += yield* this.pushSpaces(true); + this.flowKey = false; + } + n4 += yield* this.pushIndicators(); + switch (line[n4]) { + case undefined: + return "flow"; + case "#": + yield* this.pushCount(line.length - n4); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty2(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } } + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); } } - [(_MessageStream_currentMessageSnapshot = new WeakMap, _MessageStream_params = new WeakMap, _MessageStream_connectedPromise = new WeakMap, _MessageStream_resolveConnectedPromise = new WeakMap, _MessageStream_rejectConnectedPromise = new WeakMap, _MessageStream_endPromise = new WeakMap, _MessageStream_resolveEndPromise = new WeakMap, _MessageStream_rejectEndPromise = new WeakMap, _MessageStream_listeners = new WeakMap, _MessageStream_ended = new WeakMap, _MessageStream_errored = new WeakMap, _MessageStream_aborted = new WeakMap, _MessageStream_catchingPromiseCreated = new WeakMap, _MessageStream_response = new WeakMap, _MessageStream_request_id = new WeakMap, _MessageStream_logger = new WeakMap, _MessageStream_handleError = new WeakMap, _MessageStream_instances = new WeakSet, _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() { - if (this.receivedMessages.length === 0) { - throw new AnthropicError("stream ended without producing a Message with role=assistant"); + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n4 = 0; + while (this.buffer[end - 1 - n4] === "\\") + n4 += 1; + if (n4 % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } } - return this.receivedMessages.at(-1); - }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() { - if (this.receivedMessages.length === 0) { - throw new AnthropicError("stream ended without producing a Message with role=assistant"); + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf(` +`, this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf(` +`, cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } } - const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); - if (textBlocks.length === 0) { - throw new AnthropicError("stream ended without producing a content block with type=text"); + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; } - return textBlocks.join(" "); - }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() { - if (this.ended) - return; - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); - this._emit("streamEvent", event, messageSnapshot); - switch (event.type) { - case "content_block_delta": { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case "text_delta": { - if (content.type === "text") { - this._emit("text", event.delta.text, content.text || ""); - } - break; - } - case "citations_delta": { - if (content.type === "text") { - this._emit("citation", event.delta.citation, content.citations ?? []); - } - break; - } - case "input_json_delta": { - if (tracksToolInput2(content) && content.input) { - this._emit("inputJson", event.delta.partial_json, content.input); - } - break; - } - case "thinking_delta": { - if (content.type === "thinking") { - this._emit("thinking", event.delta.thinking, content.thinking); - } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty2(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: + for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; break; - } - case "signature_delta": { - if (content.type === "thinking") { - this._emit("signature", content.signature); - } + case ` +`: + nl = i2; + indent = 0; break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === ` +`) + break; } default: - checkNever2(event.delta); + break loop; } - break; - } - case "message_stop": { - this._addMessageParam(messageSnapshot); - this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); - break; } - case "content_block_stop": { - this._emit("contentBlock", messageSnapshot.content.at(-1)); - break; - } - case "message_start": { - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); } - case "content_block_start": - case "message_delta": - break; - } - }, _MessageStream_endRequest = function _MessageStream_endRequest2() { - if (this.ended) { - throw new AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); - }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) { - let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (event.type === "message_start") { - if (snapshot) { - throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf(` +`, cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; } - return event.message; } - if (!snapshot) { - throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === "\t") { + while (ch === "\t" || ch === " " || ch === "\r" || ch === ` +`) + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === ` +` && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); } - switch (event.type) { - case "message_stop": - return snapshot; - case "message_delta": - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; + yield cst.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty2(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty2(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === ` +`) { + i += 1; + ch = ` +`; + next = this.buffer[i + 1]; + } else + end = i; } - return snapshot; - case "content_block_start": - snapshot.content.push({ ...event.content_block }); - return snapshot; - case "content_block_delta": { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case "text_delta": { - if (snapshotContent?.type === "text") { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || "") + event.delta.text - }; - } - break; - } - case "citations_delta": { - if (snapshotContent?.type === "text") { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...snapshotContent.citations ?? [], event.delta.citation] - }; - } - break; - } - case "input_json_delta": { - if (snapshotContent && tracksToolInput2(snapshotContent)) { - let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || ""; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, JSON_BUF_PROPERTY2, { - value: jsonBuf, - enumerable: false, - writable: true - }); - if (jsonBuf) { - newContent.input = partialParse(jsonBuf); - } - snapshot.content[event.index] = newContent; - } - break; - } - case "thinking_delta": { - if (snapshotContent?.type === "thinking") { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking - }; - } - break; - } - case "signature_delta": { - if (snapshotContent?.type === "thinking") { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature - }; - } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === ` +`) { + const cs = this.continueScalar(i + 1); + if (cs === -1) break; - } - default: - checkNever2(event.delta); + i = Math.max(i, cs - 2); } - return snapshot; - } - case "content_block_stop": - return snapshot; - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on("streamEvent", (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); } else { - pushQueue.push(event); - } - }); - this.on("end", () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on("abort", (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on("error", (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true }); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; } - }; - } - toReadableStream() { - const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream2.toReadableStream(); - } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs -var Batches2; -var init_batches2 = __esm(() => { - init_pagination(); - init_headers(); - init_jsonl(); - init_error6(); - init_path(); - Batches2 = class Batches2 extends APIResource { - create(body, options) { - return this._client.post("/v1/messages/batches", { body, ...options }); - } - retrieve(messageBatchID, options) { - return this._client.get(path3`/v1/messages/batches/${messageBatchID}`, options); + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield cst.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; } - list(query3 = {}, options) { - return this._client.getAPIList("/v1/messages/batches", Page, { query: query3, ...options }); + *pushCount(n4) { + if (n4 > 0) { + yield this.buffer.substr(this.pos, n4); + this.pos += n4; + return n4; + } + return 0; } - delete(messageBatchID, options) { - return this._client.delete(path3`/v1/messages/batches/${messageBatchID}`, options); + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; } - cancel(messageBatchID, options) { - return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel`, options); + *pushIndicators() { + let n4 = 0; + loop: + while (true) { + switch (this.charAt(0)) { + case "!": + n4 += yield* this.pushTag(); + n4 += yield* this.pushSpaces(true); + continue loop; + case "&": + n4 += yield* this.pushUntil(isNotAnchorChar); + n4 += yield* this.pushSpaces(true); + continue loop; + case "-": + case "?": + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty2(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + n4 += yield* this.pushCount(1); + n4 += yield* this.pushSpaces(true); + continue loop; + } + } + } + break loop; + } + return n4; } - async results(messageBatchID, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty2(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); } - return this._client.get(batch.results_url, { - ...options, - headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), - stream: true, - __binaryResponse: true - })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs -var Messages2, DEPRECATED_MODELS2, MODELS_TO_WARN_WITH_THINKING_ENABLED2; -var init_messages9 = __esm(() => { - init_headers(); - init_stainless_helper_header(); - init_MessageStream(); - init_parser2(); - init_batches2(); - init_batches2(); - init_constants7(); - Messages2 = class Messages2 extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches2(this._client); + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === ` +`) + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === ` +`) + return yield* this.pushCount(2); + else + return 0; } - create(body, options) { - if (body.model in DEPRECATED_MODELS2) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]} -Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - if (MODELS_TO_WARN_WITH_THINKING_ENABLED2.includes(body.model) && body.thinking && body.thinking.type === "enabled") { - console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); - } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === "\t"); + const n4 = i - this.pos; + if (n4 > 0) { + yield this.buffer.substr(this.pos, n4); + this.pos = i; } - const helperHeader = stainlessHelperHeader(body.tools, body.messages); - return this._client.post("/v1/messages", { - body, - timeout: timeout ?? 600000, - ...options, - headers: buildHeaders([helperHeader, options?.headers]), - stream: body.stream ?? false - }); - } - parse(params, options) { - return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); - } - stream(body, options) { - return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); + return n4; } - countTokens(body, options) { - return this._client.post("/v1/messages/count_tokens", { body, ...options }); + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); } - }; - DEPRECATED_MODELS2 = { - "claude-1.3": "November 6th, 2024", - "claude-1.3-100k": "November 6th, 2024", - "claude-instant-1.1": "November 6th, 2024", - "claude-instant-1.1-100k": "November 6th, 2024", - "claude-instant-1.2": "November 6th, 2024", - "claude-3-sonnet-20240229": "July 21st, 2025", - "claude-3-opus-20240229": "January 5th, 2026", - "claude-2.1": "July 21st, 2025", - "claude-2.0": "July 21st, 2025", - "claude-3-7-sonnet-latest": "February 19th, 2026", - "claude-3-7-sonnet-20250219": "February 19th, 2026", - "claude-3-5-haiku-latest": "February 19th, 2026", - "claude-3-5-haiku-20241022": "February 19th, 2026", - "claude-opus-4-0": "June 15th, 2026", - "claude-opus-4-20250514": "June 15th, 2026", - "claude-sonnet-4-0": "June 15th, 2026", - "claude-sonnet-4-20250514": "June 15th, 2026" - }; - MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-mythos-preview", "claude-opus-4-6"]; - Messages2.Batches = Batches2; + } + exports.Lexer = Lexer; }); -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/models.mjs -var Models2; -var init_models2 = __esm(() => { - init_pagination(); - init_headers(); - init_path(); - Models2 = class Models2 extends APIResource { - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path3`/v1/models/${modelID}`, { - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - options?.headers - ]) - }); - } - list(params = {}, options) { - const { betas, ...query3 } = params ?? {}; - return this._client.getAPIList("/v1/models", Page, { - query: query3, - ...options, - headers: buildHeaders([ - { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, - options?.headers - ]) - }); +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/line-counter.js +var require_line_counter = __commonJS((exports) => { + class LineCounter { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; } - }; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/resources/index.mjs -var init_resources2 = __esm(() => { - init_beta(); - init_completions(); - init_messages9(); - init_models2(); - init_shared(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs -var readEnv = (env) => { - if (typeof globalThis.process !== "undefined") { - return globalThis.process.env?.[env]?.trim() || undefined; - } - if (typeof globalThis.Deno !== "undefined") { - return globalThis.Deno.env?.get?.(env)?.trim() || undefined; } - return; -}; - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/client.mjs -class BaseAnthropic { - constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) { - _BaseAnthropic_instances.add(this); - _BaseAnthropic_encoder.set(this, undefined); - const options = { - apiKey, - authToken, - ...opts, - baseURL: baseURL || `https://api.anthropic.com` - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new AnthropicError(`It looks like you're running in a browser-like environment. - -This is disabled by default, as it risks exposing your secret API credentials to attackers. -If you understand the risks and have appropriate mitigations in place, -you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., + exports.LineCounter = LineCounter; +}); -new Anthropic({ apiKey, dangerouslyAllowBrowser: true }); -`); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT; - this.logger = options.logger ?? console; - const defaultLogLevel = "warn"; - this.logLevel = defaultLogLevel; - this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); - this._options = options; - this.apiKey = typeof apiKey === "string" ? apiKey : null; - this.authToken = authToken; - } - withOptions(options) { - const client2 = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - authToken: this.authToken, - ...options - }); - return client2; - } - defaultQuery() { - return this._options.defaultQuery; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/parse/parser.js +var require_parser = __commonJS((exports) => { + var node_process = __require("process"); + var cst = require_cst(); + var lexer = require_lexer(); + function includesToken(list, type) { + for (let i = 0;i < list.length; ++i) + if (list[i].type === type) + return true; + return false; } - validateHeaders({ values, nulls }) { - if (values.get("x-api-key") || values.get("authorization")) { - return; - } - if (this.apiKey && values.get("x-api-key")) { - return; - } - if (nulls.has("x-api-key")) { - return; - } - if (this.authToken && values.get("authorization")) { - return; - } - if (nulls.has("authorization")) { - return; + function findNonEmptyIndex(list) { + for (let i = 0;i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } } - throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); - } - async authHeaders(opts) { - return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + return -1; } - async apiKeyAuth(opts) { - if (this.apiKey == null) { - return; + function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; } - return buildHeaders([{ "X-Api-Key": this.apiKey }]); } - async bearerAuth(opts) { - if (this.authToken == null) { - return; + function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + default: + return []; } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); - } - stringifyQuery(query3) { - return stringifyQuery(query3); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid42()}`; } - makeStatusError(status, error52, message, headers) { - return APIError.generate(status, error52, message, headers); + function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: + while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") {} + return prev.splice(i, prev.length); } - buildURL(path4, query3, defaultBaseURL) { - const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; - const url2 = isAbsoluteURL(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4)); - const defaultQuery = this.defaultQuery(); - const pathQuery = Object.fromEntries(url2.searchParams); - if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) { - query3 = { ...pathQuery, ...defaultQuery, ...query3 }; - } - if (typeof query3 === "object" && query3 && !Array.isArray(query3)) { - url2.search = this.stringifyQuery(query3); - } - return url2.toString(); + function arrayPushArray(target, source) { + if (source.length < 1e5) + Array.prototype.push.apply(target, source); + else + for (let i = 0;i < source.length; ++i) + target.push(source[i]); } - _calculateNonstreamingTimeout(maxTokens) { - const defaultTimeout = 10 * 60; - const expectedTimeout = 60 * 60 * maxTokens / 128000; - if (expectedTimeout > defaultTimeout) { - throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details"); + function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + arrayPushArray(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + arrayPushArray(it.start, it.sep); + delete it.sep; + } + } } - return defaultTimeout * 1000; - } - async prepareOptions(options) {} - async prepareRequest(request, { url: url2, options }) {} - get(path4, opts) { - return this.methodRequest("get", path4, opts); - } - post(path4, opts) { - return this.methodRequest("post", path4, opts); - } - patch(path4, opts) { - return this.methodRequest("patch", path4, opts); - } - put(path4, opts) { - return this.methodRequest("put", path4, opts); - } - delete(path4, opts) { - return this.methodRequest("delete", path4, opts); - } - methodRequest(method, path4, opts) { - return this.request(Promise.resolve(opts).then((opts2) => { - return { method, path: path4, ...opts2 }; - })); - } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; + + class Parser { + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new lexer.Lexer; + this.onNewLine = onNewLine; } - await this.prepareOptions(options); - const { req, url: url2, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining - }); - await this.prepareRequest(req, { url: url2, options }); - const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); - const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url: url2, - options, - headers: req.headers - })); - if (options.signal?.aborted) { - throw new APIUserAbortError; + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); } - const controller = new AbortController; - const response = await this.fetchWithTimeout(url2, req, timeout, controller).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError; - } - const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: url2, - durationMs: headersTime - startTime, - message: response.message - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) + console.log("|", cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url: url2, - durationMs: headersTime - startTime, - message: response.message - })); - if (isTimeout) { - throw new APIConnectionTimeoutError; + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; } - throw new APIConnectionError({ cause: response }); } - const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join(""); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url2} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err2) => castToError(err2).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path4, Page2, opts) { - return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts }); - } - requestAPIList(Page2, options) { - const request = this.makeRequest(options, null, undefined); - return new PagePromise(this, request, Page2); - } - async fetchWithTimeout(url2, init, ms, controller) { - const { signal, method, ...options } = init || {}; - const abort = this._makeAbort(controller); - if (signal) - signal.addEventListener("abort", abort, { once: true }); - const timeout = setTimeout(abort, ms); - const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; - const fetchOptions = { - signal: controller.signal, - ...isReadableBody ? { duplex: "half" } : {}, - method: "GET", - ...options - }; - if (method) { - fetchOptions.method = method.toUpperCase(); + *end() { + while (this.stack.length > 0) + yield* this.pop(); } - try { - return await this.fetch.call(undefined, url2, fetchOptions); - } finally { - clearTimeout(timeout); + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; } - } - async shouldRetry(response) { - const shouldRetryHeader = response.headers.get("x-should-retry"); - if (shouldRetryHeader === "true") - return true; - if (shouldRetryHeader === "false") - return false; - if (response.status === 408) - return true; - if (response.status === 409) - return true; - if (response.status === 429) - return true; - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); } + yield* this.pop(); } - const retryAfterHeader = responseHeaders?.get("retry-after"); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; + peek(n4) { + return this.stack[this.stack.length - n4]; + } + *pop(error90) { + const token = error90 ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; } else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } } } - if (timeoutMillis === undefined) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc3 = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc3.start.push(this.sourceToken); + this.stack.push(doc3); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; } - await sleep2(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8; - const numRetries = maxRetries - retriesRemaining; - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { - const maxTime = 60 * 60 * 1000; - const defaultTime = 60 * 10 * 1000; - const expectedTime = maxTime * maxTokens / 128000; - if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) { - throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details"); + *document(doc3) { + if (doc3.value) + return yield* this.lineEnd(doc3); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc3.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc3.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc3.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc3); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } } - return defaultTime; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path: path4, query: query3, defaultBaseURL } = options; - const url2 = this.buildURL(path4, query3, defaultBaseURL); - if ("timeout" in options) - validatePositiveInteger("timeout", options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...options.signal && { signal: options.signal }, - ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, - ...body && { body }, - ...this.fetchOptions ?? {}, - ...options.fetchOptions ?? {} - }; - return { req, url: url2, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== "get") { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep2; + if (scalar.end) { + sep2 = scalar.end; + sep2.push(this.sourceToken); + delete scalar.end; + } else + sep2 = [this.sourceToken]; + const map3 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep: sep2 }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else + yield* this.lineEnd(scalar); } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: "application/json", - "User-Agent": this.getUserAgent(), - "X-Stainless-Retry-Count": String(retryCount), - ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1000)) } : {}, - ...getPlatformHeaders(), - ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined, - "anthropic-version": "2023-06-01" - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers - ]); - this.validateHeaders(headers); - return headers.values; - } - _makeAbort(controller) { - return () => controller.abort(); - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf(` +`) + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf(` +`, nl) + 1; + } + } + yield* this.pop(); + break; + default: + yield* this.pop(); + yield* this.step(); + } } - const headers = buildHeaders([rawHeaders]); - if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) { - return { bodyHeaders: undefined, body }; - } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) { - return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; - } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + *blockMap(map3) { + const it = map3.items[map3.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map3.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map3.indent)) { + const prev = map3.items[map3.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + map3.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map3.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map3.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0;i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map3.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map3.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map3.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep2 = it.sep; + sep2.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep: sep2 }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map3.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map3.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs); + } else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map3); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map3.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const prev = seq.items[seq.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + arrayPushArray(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep2 = fc.end.splice(1, fc.end.length); + sep2.push(this.sourceToken); + const map3 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep: sep2 }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map3; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf(` +`) + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf(` +`, nl) + 1; + } + } return { - bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, - body: this.stringifyQuery(body) + type, + offset: this.offset, + indent: this.indent, + source: this.source }; - } else { - return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); } - } -} -var _BaseAnthropic_instances, _a3, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden, HUMAN_PROMPT = "\\n\\nHuman:", AI_PROMPT = "\\n\\nAssistant:", Anthropic; -var init_client5 = __esm(() => { - init_tslib(); - init_values4(); - init_detect_platform(); - init_query(); - init_error5(); - init_pagination(); - init_uploads2(); - init_resources2(); - init_api_promise(); - init_completions(); - init_models2(); - init_beta(); - init_messages9(); - init_detect_platform(); - init_headers(); - init_log(); - init_values4(); - _a3 = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap, _BaseAnthropic_instances = new WeakSet, _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() { - return this.baseURL !== "https://api.anthropic.com"; - }; - BaseAnthropic.Anthropic = _a3; - BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; - BaseAnthropic.AI_PROMPT = AI_PROMPT; - BaseAnthropic.DEFAULT_TIMEOUT = 600000; - BaseAnthropic.AnthropicError = AnthropicError; - BaseAnthropic.APIError = APIError; - BaseAnthropic.APIConnectionError = APIConnectionError; - BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; - BaseAnthropic.APIUserAbortError = APIUserAbortError; - BaseAnthropic.NotFoundError = NotFoundError; - BaseAnthropic.ConflictError = ConflictError; - BaseAnthropic.RateLimitError = RateLimitError; - BaseAnthropic.BadRequestError = BadRequestError; - BaseAnthropic.AuthenticationError = AuthenticationError; - BaseAnthropic.InternalServerError = InternalServerError; - BaseAnthropic.PermissionDeniedError = PermissionDeniedError; - BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; - BaseAnthropic.toFile = toFile; - Anthropic = class Anthropic extends BaseAnthropic { - constructor() { - super(...arguments); - this.completions = new Completions(this); - this.messages = new Messages2(this); - this.models = new Models2(this); - this.beta = new Beta(this); + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; } - }; - Anthropic.Completions = Completions; - Anthropic.Messages = Messages2; - Anthropic.Models = Models2; - Anthropic.Beta = Beta; -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/index.mjs -var init_sdk = __esm(() => { - init_client5(); - init_uploads2(); - init_api_promise(); - init_client5(); - init_pagination(); - init_error5(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs -var init_base64 = __esm(() => { - init_error5(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/internal/utils.mjs -var init_utils16 = __esm(() => { - init_values4(); - init_base64(); - init_log(); - init_query(); -}); - -// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.91.1_zod@4.4.3/node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs -function deepClone2(obj) { - return JSON.parse(JSON.stringify(obj)); -} -function transformJSONSchema(jsonSchema) { - const workingCopy = deepClone2(jsonSchema); - return _transformJSONSchema(workingCopy); -} -function _transformJSONSchema(jsonSchema) { - const strictSchema = {}; - const ref = pop(jsonSchema, "$ref"); - if (ref !== undefined) { - strictSchema["$ref"] = ref; - return strictSchema; - } - const defs = pop(jsonSchema, "$defs"); - if (defs !== undefined) { - const strictDefs = {}; - strictSchema["$defs"] = strictDefs; - for (const [name, defSchema] of Object.entries(defs)) { - strictDefs[name] = _transformJSONSchema(defSchema); + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); } - } - const type = pop(jsonSchema, "type"); - const anyOf = pop(jsonSchema, "anyOf"); - const oneOf = pop(jsonSchema, "oneOf"); - const allOf = pop(jsonSchema, "allOf"); - if (Array.isArray(anyOf)) { - strictSchema["anyOf"] = anyOf.map((variant) => _transformJSONSchema(variant)); - } else if (Array.isArray(oneOf)) { - strictSchema["anyOf"] = oneOf.map((variant) => _transformJSONSchema(variant)); - } else if (Array.isArray(allOf)) { - strictSchema["allOf"] = allOf.map((entry) => _transformJSONSchema(entry)); - } else { - if (type === undefined) { - throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used"); + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } } - strictSchema["type"] = type; } - const description = pop(jsonSchema, "description"); - if (description !== undefined) { - strictSchema["description"] = description; + exports.Parser = Parser; +}); + +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/public-api.js +var require_public_api = __commonJS((exports) => { + var composer = require_composer(); + var Document2 = require_Document(); + var errors7 = require_errors(); + var log = require_log(); + var identity = require_identity(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null; + return { lineCounter: lineCounter$1, prettyErrors }; } - const title = pop(jsonSchema, "title"); - if (title !== undefined) { - strictSchema["title"] = title; + function parseAllDocuments(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter2?.addNewLine); + const composer$1 = new composer.Composer(options); + const docs = Array.from(composer$1.compose(parser$1.parse(source))); + if (prettyErrors && lineCounter2) + for (const doc3 of docs) { + doc3.errors.forEach(errors7.prettifyError(source, lineCounter2)); + doc3.warnings.forEach(errors7.prettifyError(source, lineCounter2)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer$1.streamInfo()); } - if (type === "object") { - const properties = pop(jsonSchema, "properties") || {}; - strictSchema["properties"] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ - key, - _transformJSONSchema(propSchema) - ])); - pop(jsonSchema, "additionalProperties"); - strictSchema["additionalProperties"] = false; - const required2 = pop(jsonSchema, "required"); - if (required2 !== undefined) { - strictSchema["required"] = required2; + function parseDocument(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter2?.addNewLine); + const composer$1 = new composer.Composer(options); + let doc3 = null; + for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { + if (!doc3) + doc3 = _doc; + else if (doc3.options.logLevel !== "silent") { + doc3.errors.push(new errors7.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } } - } else if (type === "string") { - const format3 = pop(jsonSchema, "format"); - if (format3 !== undefined && SUPPORTED_STRING_FORMATS.has(format3)) { - strictSchema["format"] = format3; - } else if (format3 !== undefined) { - jsonSchema["format"] = format3; + if (prettyErrors && lineCounter2) { + doc3.errors.forEach(errors7.prettifyError(source, lineCounter2)); + doc3.warnings.forEach(errors7.prettifyError(source, lineCounter2)); } - } else if (type === "array") { - const items = pop(jsonSchema, "items"); - if (items !== undefined) { - strictSchema["items"] = _transformJSONSchema(items); + return doc3; + } + function parse16(src, reviver2, options) { + let _reviver2 = undefined; + if (typeof reviver2 === "function") { + _reviver2 = reviver2; + } else if (options === undefined && reviver2 && typeof reviver2 === "object") { + options = reviver2; } - const minItems = pop(jsonSchema, "minItems"); - if (minItems !== undefined && (minItems === 0 || minItems === 1)) { - strictSchema["minItems"] = minItems; - } else if (minItems !== undefined) { - jsonSchema["minItems"] = minItems; + const doc3 = parseDocument(src, options); + if (!doc3) + return null; + doc3.warnings.forEach((warning) => log.warn(doc3.options.logLevel, warning)); + if (doc3.errors.length > 0) { + if (doc3.options.logLevel !== "silent") + throw doc3.errors[0]; + else + doc3.errors = []; } + return doc3.toJS(Object.assign({ reviver: _reviver2 }, options)); } - if (Object.keys(jsonSchema).length > 0) { - const existingDescription = strictSchema["description"]; - strictSchema["description"] = (existingDescription ? existingDescription + ` - -` : "") + "{" + Object.entries(jsonSchema).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ") + "}"; + function stringify5(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === undefined) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return; + } + if (identity.isDocument(value) && !_replacer) + return value.toString(options); + return new Document2.Document(value, _replacer, options).toString(options); } - return strictSchema; -} -var SUPPORTED_STRING_FORMATS; -var init_transform_json_schema = __esm(() => { - init_utils16(); - SUPPORTED_STRING_FORMATS = new Set([ - "date-time", - "time", - "date", - "duration", - "email", - "hostname", - "uri", - "ipv4", - "ipv6", - "uuid" - ]); + exports.parse = parse16; + exports.parseAllDocuments = parseAllDocuments; + exports.parseDocument = parseDocument; + exports.stringify = stringify5; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/chat_models.js -function defaultMaxOutputTokensForModel(model) { - if (!model) - return FALLBACK_MAX_OUTPUT_TOKENS; - return Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1] ?? FALLBACK_MAX_OUTPUT_TOKENS; -} -function _toolsInParams(params) { - return !!(params.tools && params.tools.length > 0); -} -function _documentsInParams(params) { - for (const message of params.messages ?? []) { - if (typeof message.content === "string") - continue; - for (const block of message.content ?? []) - if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) - return true; +// ../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/index.js +var require_dist3 = __commonJS((exports) => { + var composer = require_composer(); + var Document2 = require_Document(); + var Schema = require_Schema(); + var errors7 = require_errors(); + var Alias = require_Alias(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var cst = require_cst(); + var lexer = require_lexer(); + var lineCounter = require_line_counter(); + var parser = require_parser(); + var publicApi = require_public_api(); + var visit = require_visit(); + exports.Composer = composer.Composer; + exports.Document = Document2.Document; + exports.Schema = Schema.Schema; + exports.YAMLError = errors7.YAMLError; + exports.YAMLParseError = errors7.YAMLParseError; + exports.YAMLWarning = errors7.YAMLWarning; + exports.Alias = Alias.Alias; + exports.isAlias = identity.isAlias; + exports.isCollection = identity.isCollection; + exports.isDocument = identity.isDocument; + exports.isMap = identity.isMap; + exports.isNode = identity.isNode; + exports.isPair = identity.isPair; + exports.isScalar = identity.isScalar; + exports.isSeq = identity.isSeq; + exports.Pair = Pair.Pair; + exports.Scalar = Scalar.Scalar; + exports.YAMLMap = YAMLMap.YAMLMap; + exports.YAMLSeq = YAMLSeq.YAMLSeq; + exports.CST = cst; + exports.Lexer = lexer.Lexer; + exports.LineCounter = lineCounter.LineCounter; + exports.Parser = parser.Parser; + exports.parse = publicApi.parse; + exports.parseAllDocuments = publicApi.parseAllDocuments; + exports.parseDocument = publicApi.parseDocument; + exports.stringify = publicApi.stringify; + exports.visit = visit.visit; + exports.visitAsync = visit.visitAsync; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/singletons/fetch.js +var DEFAULT_FETCH_IMPLEMENTATION2 = (...args) => fetch(...args), LANGSMITH_FETCH_IMPLEMENTATION_KEY2, _getFetchImplementation2 = () => { + return globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY2] ?? DEFAULT_FETCH_IMPLEMENTATION2; +}; +var init_fetch2 = __esm(() => { + LANGSMITH_FETCH_IMPLEMENTATION_KEY2 = Symbol.for("lg:fetch_implementation"); +}); + +// ../../node_modules/.pnpm/is-network-error@1.3.2/node_modules/is-network-error/index.js +function isNetworkError3(error90) { + const isValid3 = error90 && isError3(error90) && error90.name === "TypeError" && typeof error90.message === "string"; + if (!isValid3) { + return false; } - return false; -} -function _thinkingInParams(params) { - return !!(params.thinking && (params.thinking.type === "enabled" || params.thinking.type === "adaptive")); -} -function _compactionInParams(params) { - return !!params.context_management?.edits?.some((e) => e.type === "compact_20260112"); + const { message, stack } = error90; + if (message === "Load failed" || message.startsWith("Load failed (") && message.endsWith(")")) { + return stack === undefined || "__sentry_captured__" in error90; + } + if (message.startsWith("error sending request for url")) { + return true; + } + if (message === "Failed to fetch" || message.startsWith("Failed to fetch (") && message.endsWith(")")) { + return true; + } + return errorMessages3.has(message); } -function isAnthropicTool(tool2) { - return "input_schema" in tool2; +var objectToString4, isError3 = (value) => objectToString4.call(value) === "[object Error]", errorMessages3; +var init_is_network_error3 = __esm(() => { + objectToString4 = Object.prototype.toString; + errorMessages3 = new Set([ + "network error", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" + ]); +}); + +// ../../node_modules/.pnpm/p-retry@7.1.1/node_modules/p-retry/index.js +function validateRetries3(retries) { + if (typeof retries === "number") { + if (retries < 0) { + throw new TypeError("Expected `retries` to be a non-negative number."); + } + if (Number.isNaN(retries)) { + throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } + } else if (retries !== undefined) { + throw new TypeError("Expected `retries` to be a number or Infinity."); + } } -function isBuiltinTool(tool2) { - return typeof tool2 === "object" && tool2 !== null && "type" in tool2 && (("name" in tool2) || ("mcp_server_name" in tool2)) && typeof tool2.type === "string" && [ - "text_editor_", - "computer_", - "bash_", - "web_search_", - "web_fetch_", - "str_replace_editor_", - "str_replace_based_edit_tool_", - "code_execution_", - "memory_", - "tool_search_", - "mcp_toolset" - ].some((prefix) => typeof tool2.type === "string" && tool2.type.startsWith(prefix)); +function validateNumberOption3(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === undefined) { + return; + } + if (typeof value !== "number" || Number.isNaN(value)) { + throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + } + if (!allowInfinity && !Number.isFinite(value)) { + throw new TypeError(`Expected \`${name}\` to be a finite number.`); + } + if (value < min) { + throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`); + } } -function _combineBetas(a, b, ...rest) { - return Array.from(new Set([ - ...a ?? [], - ...b ?? [], - ...rest.flatMap((x) => Array.from(x)) - ])); +function calculateDelay3(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; } -function extractToken(chunk) { - if (typeof chunk.content === "string") - return chunk.content; - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) - return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") - return chunk.content[0].text; +function calculateRemainingTime3(start, max) { + if (!Number.isFinite(max)) { + return max; + } + return max - (performance.now() - start); } -var MODEL_DEFAULT_MAX_OUTPUT_TOKENS, FALLBACK_MAX_OUTPUT_TOKENS = 4096, ChatAnthropicMessages, ChatAnthropic; -var init_chat_models3 = __esm(() => { - init_output_parsers3(); - init_tools5(); - init_message_inputs(); - init_params(); - init_message_outputs(); - init_errors9(); - init_profiles2(); - init_stream_events(); - init_sdk(); - init_transform_json_schema(); - init_messages(); - init_outputs(); - init_env(); - init_chat_models(); - init_base5(); - init_json_schema2(); - init_types3(); - init_function_calling(); - init_standard_schema(); - init_structured_output(); - MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { - "claude-opus-4-7": 16384, - "claude-opus-4-6": 16384, - "claude-sonnet-4-6": 16384, - "claude-opus-4-5": 16384, - "claude-sonnet-4-5": 16384, - "claude-haiku-4-5": 16384, - "claude-opus-4-1": 16384, - "claude-sonnet-4": 16384, - "claude-opus-4": 16384, - "claude-3-7-sonnet": 8192, - "claude-3-5-sonnet": 8192, - "claude-3-5-haiku": 8192, - "claude-3-opus": 4096, - "claude-3-sonnet": 4096, - "claude-3-haiku": 4096 - }; - ChatAnthropicMessages = class extends BaseChatModel { - static lc_name() { - return "ChatAnthropic"; +async function onAttemptFailure3({ error: error90, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error90 instanceof Error ? error90 : new TypeError(`Non-error was thrown: "${error90}". You should only throw errors.`); + if (normalizedError instanceof AbortError3) { + throw normalizedError.originalError; + } + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context2 = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context2); + if (calculateRemainingTime3(startTime, maxRetryTime) <= 0) { + throw normalizedError; + } + const consumeRetry = await options.shouldConsumeRetry(context2); + const remainingTime = calculateRemainingTime3(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) { + throw normalizedError; + } + if (normalizedError instanceof TypeError && !isNetworkError3(normalizedError)) { + if (consumeRetry) { + throw normalizedError; } - get lc_secrets() { - return { - anthropicApiKey: "ANTHROPIC_API_KEY", - apiKey: "ANTHROPIC_API_KEY" + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context2)) { + throw normalizedError; + } + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = calculateDelay3(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + options.signal?.throwIfAborted(); + if (finalDelay > 0) { + await new Promise((resolve2, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve2(); + }, finalDelay); + if (options.unref) { + timeoutToken.unref?.(); + } + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + } + options.signal?.throwIfAborted(); + return true; +} +async function pRetry3(input, options = {}) { + options = { ...options }; + validateRetries3(options.retries); + if (Object.hasOwn(options, "forever")) { + throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + } + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1000; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + validateNumberOption3("factor", options.factor, { min: 0, allowInfinity: false }); + validateNumberOption3("minTimeout", options.minTimeout, { min: 0, allowInfinity: false }); + validateNumberOption3("maxTimeout", options.maxTimeout, { min: 0, allowInfinity: true }); + validateNumberOption3("maxRetryTime", options.maxRetryTime, { min: 0, allowInfinity: true }); + if (!(options.factor > 0)) { + options.factor = 1; + } + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error90) { + if (await onAttemptFailure3({ + error: error90, + attemptNumber, + retriesConsumed, + startTime, + options + })) { + retriesConsumed++; + } } - get lc_aliases() { - return { modelName: "model" }; + } + throw new Error("Retry attempts exhausted without throwing an error."); +} +var AbortError3; +var init_p_retry3 = __esm(() => { + init_is_network_error3(); + AbortError3 = class AbortError3 extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; } - lc_serializable = true; - anthropicApiKey; - apiKey; - apiUrl; - temperature; - topK; - topP; - maxTokens; - modelName = "claude-sonnet-4-5-20250929"; - model = "claude-sonnet-4-5-20250929"; - invocationKwargs; - stopSequences; - streaming = false; - clientOptions; - thinking = { type: "disabled" }; - contextManagement; - outputConfig; - inferenceGeo; - batchClient; - streamingClient; - streamUsage = true; - betas; - createClient; - constructor(modelOrFields, fieldsArg) { - const fields = typeof modelOrFields === "string" ? { - ...fieldsArg ?? {}, - model: modelOrFields - } : modelOrFields ?? {}; - super(fields ?? {}); - this._addVersion("@langchain/anthropic", "1.3.29"); - this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); - if (!this.anthropicApiKey && !fields?.createClient) - throw new Error("Anthropic API key not found"); - this.clientOptions = fields?.clientOptions ?? {}; - this.apiKey = this.anthropicApiKey; - this.apiUrl = fields?.anthropicApiUrl; - this.modelName = fields?.model ?? fields?.modelName ?? this.model; - this.model = this.modelName; - this.invocationKwargs = fields?.invocationKwargs ?? {}; - this.topP = fields?.topP ?? this.topP; - this.temperature = fields?.temperature ?? this.temperature; - this.topK = fields?.topK ?? this.topK; - this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); - this.stopSequences = fields?.stopSequences ?? this.stopSequences; - this.streaming = fields?.streaming ?? false; - this.streamUsage = fields?.streamUsage ?? this.streamUsage; - this.thinking = fields?.thinking ?? this.thinking; - this.contextManagement = fields?.contextManagement ?? this.contextManagement; - this.outputConfig = fields?.outputConfig ?? this.outputConfig; - this.inferenceGeo = fields?.inferenceGeo ?? this.inferenceGeo; - this.betas = fields?.betas ?? this.betas; - this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); + }; +}); + +// ../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js +var require_eventemitter32 = __commonJS((exports, module) => { + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() {} + if (Object.create) { + Events.prototype = Object.create(null); + if (!new Events().__proto__) + prefix = false; + } + function EE(fn, context2, once) { + this.fn = fn; + this.context = context2; + this.once = once || false; + } + function addListener(emitter, event, fn, context2, once) { + if (typeof fn !== "function") { + throw new TypeError("The listener must be a function"); } - getLsParams(options) { - const params = this.invocationParams(options); - return { - ls_provider: "anthropic", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: params.temperature ?? undefined, - ls_max_tokens: params.max_tokens ?? undefined, - ls_stop: options.stop - }; + var listener = new EE(fn, context2 || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) + emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) + emitter._events[evt].push(listener); + else + emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) + emitter._events = new Events; + else + delete emitter._events[evt]; + } + function EventEmitter() { + this._events = new Events; + this._eventsCount = 0; + } + EventEmitter.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) + return names; + for (name in events = this._events) { + if (has.call(events, name)) + names.push(prefix ? name.slice(1) : name); } - formatStructuredToolToAnthropic(tools) { - if (!tools) - return; - return tools.map((tool2) => { - if (isLangChainTool(tool2) && tool2.extras?.providerToolDefinition) - return tool2.extras.providerToolDefinition; - if (isBuiltinTool(tool2)) - return tool2; - if (isAnthropicTool(tool2)) - return tool2; - if (isOpenAITool(tool2)) - return { - name: tool2.function.name, - description: tool2.function.description, - input_schema: tool2.function.parameters - }; - if (isLangChainTool(tool2)) - return { - name: tool2.name, - description: tool2.description, - input_schema: isInteropZodSchema(tool2.schema) ? toJsonSchema(tool2.schema) : tool2.schema, - ...tool2.extras ? AnthropicToolExtrasSchema.parse(tool2.extras) : {} - }; - throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool2, null, 2)}`); - }); + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); } - bindTools(tools, kwargs) { - return this.withConfig({ - tools: this.formatStructuredToolToAnthropic(tools), - ...kwargs - }); + return names; + }; + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) + return []; + if (handlers.fn) + return [handlers.fn]; + for (var i = 0, l = handlers.length, ee = new Array(l);i < l; i++) { + ee[i] = handlers[i].fn; } - invocationParams(options) { - const tool_choice = handleToolChoice(options?.tool_choice); - const toolBetas = options?.tools?.reduce((acc, tool2) => { - if (typeof tool2 === "object" && "type" in tool2 && tool2.type in ANTHROPIC_TOOL_BETAS) { - const beta = ANTHROPIC_TOOL_BETAS[tool2.type]; - if (!acc.includes(beta)) - return [...acc, beta]; + return ee; + }; + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) + return 0; + if (listeners.fn) + return 1; + return listeners.length; + }; + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) + return false; + var listeners = this._events[evt], len = arguments.length, args, i; + if (listeners.fn) { + if (listeners.once) + this.removeListener(event, listeners.fn, undefined, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i = 1, args = new Array(len - 1);i < len; i++) { + args[i - 1] = arguments[i]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j; + for (i = 0;i < length; i++) { + if (listeners[i].once) + this.removeListener(event, listeners[i].fn, undefined, true); + switch (len) { + case 1: + listeners[i].fn.call(listeners[i].context); + break; + case 2: + listeners[i].fn.call(listeners[i].context, a1); + break; + case 3: + listeners[i].fn.call(listeners[i].context, a1, a2); + break; + case 4: + listeners[i].fn.call(listeners[i].context, a1, a2, a3); + break; + default: + if (!args) + for (j = 1, args = new Array(len - 1);j < len; j++) { + args[j - 1] = arguments[j]; + } + listeners[i].fn.apply(listeners[i].context, args); } - return acc; - }, []); - const mergedOutputConfig = (() => { - const base = { - ...this.outputConfig, - ...options?.outputConfig - }; - if (options?.outputFormat && !base.format) - base.format = options.outputFormat; - return Object.keys(base).length > 0 ? base : undefined; - })(); - const compactionBetas = this.contextManagement?.edits?.some((e) => e.type === "compact_20260112") ? ["compact-2026-01-12"] : []; - const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig); - const output = { - model: this.model, - stop_sequences: options?.stop ?? this.stopSequences, - stream: this.streaming, - max_tokens: this.maxTokens, - tools: this.formatStructuredToolToAnthropic(options?.tools), - tool_choice, - thinking: this.thinking, - context_management: this.contextManagement, - ...this.invocationKwargs, - container: options?.container, - betas: _combineBetas(this.betas, options?.betas, toolBetas ?? [], compactionBetas, taskBudgetBetas), - output_config: mergedOutputConfig, - inference_geo: options?.inferenceGeo ?? this.inferenceGeo, - mcp_servers: options?.mcp_servers, - cache_control: options?.cache_control - }; - validateInvocationParamCompatibility({ - model: this.model, - thinking: this.thinking, - topK: this.topK, - topP: this.topP, - temperature: this.temperature - }); - Object.assign(output, getSamplingParams({ - model: this.model, - thinking: this.thinking, - topK: this.topK, - topP: this.topP, - temperature: this.temperature - })); - return output; - } - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; + } } - identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; + return true; + }; + EventEmitter.prototype.on = function on(event, fn, context2) { + return addListener(this, event, fn, context2, false); + }; + EventEmitter.prototype.once = function once(event, fn, context2) { + return addListener(this, event, fn, context2, true); + }; + EventEmitter.prototype.removeListener = function removeListener(event, fn, context2, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) + return this; + if (!fn) { + clearEvent(this, evt); + return this; } - async* _streamResponseChunks(messages, options, runManager) { - const params = this.invocationParams(options); - const formattedMessages = _convertMessagesToAnthropicPayload(messages); - const payload = { - ...params, - ...formattedMessages, - stream: true - }; - const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload) && !_compactionInParams(payload); - const stream2 = await this.createStreamWithRetry(payload, { - headers: options.headers, - signal: options.signal - }); - for await (const data of stream2) { - if (options.signal?.aborted) { - stream2.controller.abort(); - return; + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn && (!once || listeners.once) && (!context2 || listeners.context === context2)) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length;i < length; i++) { + if (listeners[i].fn !== fn || once && !listeners[i].once || context2 && listeners[i].context !== context2) { + events.push(listeners[i]); } - const shouldStreamUsage = this.streamUsage ?? options.streamUsage; - const result = _makeMessageChunkFromAnthropicEvent(data, { - streamUsage: shouldStreamUsage, - coerceContentToString - }); - if (!result) - continue; - const { chunk } = result; - const token = extractToken(chunk); - const generationChunk = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: chunk.content, - additional_kwargs: chunk.additional_kwargs, - tool_call_chunks: chunk.tool_call_chunks, - usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined, - response_metadata: chunk.response_metadata, - id: chunk.id - }), - text: token ?? "" - }); - yield generationChunk; - await runManager?.handleLLMNewToken(token ?? "", undefined, undefined, undefined, undefined, { chunk: generationChunk }); } + if (events.length) + this._events[evt] = events.length === 1 ? events[0] : events; + else + clearEvent(this, evt); } - async* _streamChatModelEvents(messages, options, _runManager) { - const params = this.invocationParams(options); - const formattedMessages = _convertMessagesToAnthropicPayload(messages); - const payload = { - ...params, - ...formattedMessages, - stream: true - }; - const stream2 = await this.createStreamWithRetry(payload, { - headers: options.headers, - signal: options.signal - }); - const shouldStreamUsage = this.streamUsage ?? options.streamUsage; - const abortableStream = async function* (source, signal) { - for await (const data of source) { - if (signal?.aborted) { - source.controller?.abort(); - return; - } - yield data; - } - }; - yield* convertAnthropicStream(abortableStream(stream2, options.signal), { streamUsage: shouldStreamUsage ?? true }); + return this; + }; + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) + clearEvent(this, evt); + } else { + this._events = new Events; + this._eventsCount = 0; } - async _generateNonStreaming(messages, params, requestOptions) { - const formattedMessages = _convertMessagesToAnthropicPayload(messages); - const { content, ...additionalKwargs } = await this.completionWithRetry({ - ...params, - stream: false, - ...formattedMessages - }, requestOptions); - const generations = anthropicResponseToChatMessages(content, additionalKwargs); - const { role: _role, type: _type, ...rest } = additionalKwargs; - return { - generations, - llmOutput: rest - }; + return this; + }; + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + EventEmitter.prefixed = prefix; + EventEmitter.EventEmitter = EventEmitter; + if (typeof module !== "undefined") { + module.exports = EventEmitter; + } +}); + +// ../../node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs +var import__3; +var init_eventemitter3 = __esm(() => { + import__3 = __toESM(require_eventemitter32(), 1); +}); + +// ../../node_modules/.pnpm/p-timeout@7.0.1/node_modules/p-timeout/index.js +function pTimeout(promise3, options) { + const { + milliseconds, + fallback, + message, + customTimers = { setTimeout, clearTimeout }, + signal + } = options; + let timer; + let abortHandler; + const wrappedPromise = new Promise((resolve2, reject) => { + if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) { + throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``); } - async _generate(messages, options, runManager) { - options.signal?.throwIfAborted(); - if (this.stopSequences && options.stop) - throw new Error(`"stopSequence" parameter found in input and default params`); - const params = this.invocationParams(options); - if (params.stream) { - let finalChunk; - const stream2 = this._streamResponseChunks(messages, options, runManager); - for await (const chunk of stream2) - if (finalChunk === undefined) - finalChunk = chunk; - else - finalChunk = finalChunk.concat(chunk); - if (finalChunk === undefined) - throw new Error("No chunks returned from Anthropic API."); - return { generations: [{ - text: finalChunk.text, - message: finalChunk.message - }] }; - } else - return this._generateNonStreaming(messages, params, { - signal: options.signal, - headers: options.headers - }); + if (signal?.aborted) { + reject(getAbortedReason(signal)); + return; } - async createStreamWithRetry(request, options) { - if (!this.streamingClient) { - const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined; - this.streamingClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options_, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const { betas, ...rest } = request; - const makeCompletionRequest = async () => { - try { - if (request?.betas?.length) - return await this.streamingClient.beta.messages.create({ - ...rest, - betas, - ...this.invocationKwargs, - stream: true - }, options); - return await this.streamingClient.messages.create({ - ...rest, - ...this.invocationKwargs, - stream: true - }, options); - } catch (e) { - throw wrapAnthropicClientError(e); - } + if (signal) { + abortHandler = () => { + reject(getAbortedReason(signal)); }; - return this.caller.call(makeCompletionRequest); + signal.addEventListener("abort", abortHandler, { once: true }); } - async completionWithRetry(request, options) { - if (!this.batchClient) { - const options2 = this.apiUrl ? { baseURL: this.apiUrl } : undefined; - this.batchClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options2, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const { betas, ...rest } = request; - const makeCompletionRequest = async () => { + promise3.then(resolve2, reject); + if (milliseconds === Number.POSITIVE_INFINITY) { + return; + } + const timeoutError = new TimeoutError; + timer = customTimers.setTimeout.call(undefined, () => { + if (fallback) { try { - if (request?.betas?.length) - return await this.batchClient.beta.messages.create({ - ...rest, - ...this.invocationKwargs, - betas - }, options); - return await this.batchClient.messages.create({ - ...rest, - ...this.invocationKwargs - }, options); - } catch (e) { - throw wrapAnthropicClientError(e); + resolve2(fallback()); + } catch (error90) { + reject(error90); } - }; - return this.caller.callWithOptions({ signal: options.signal ?? undefined }, makeCompletionRequest); - } - _llmType() { - return "anthropic"; - } - get profile() { - return PROFILES[this.model] ?? {}; - } - withStructuredOutput(outputSchema, config2) { - let llm; - let outputParser; - const { schema, name, includeRaw } = { - ...config2, - schema: outputSchema - }; - let method = config2?.method ?? "functionCalling"; - if (method === "jsonMode") { - console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`); - method = "jsonSchema"; + return; } - if (method === "jsonSchema") { - outputParser = createContentParser(schema); - const jsonSchema = transformJSONSchema(toJsonSchema(schema)); - llm = this.withConfig({ - outputVersion: "v0", - outputConfig: { format: { - type: "json_schema", - schema: jsonSchema - } }, - ls_structured_output_format: { - kwargs: { method: "json_schema" }, - schema: jsonSchema - } - }); - } else if (method === "functionCalling") { - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema) || isSerializableSchema(schema)) { - const jsonSchema = toJsonSchema(schema); - tools = [{ - name: functionName, - description: jsonSchema.description ?? "A function available to call.", - input_schema: jsonSchema - }]; - } else if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { - tools = [schema]; - functionName = schema.name; - } else - tools = [{ - name: functionName, - description: schema.description ?? "", - input_schema: schema - }]; - outputParser = createFunctionCallingParser(schema, functionName, AnthropicToolsOutputParser); - if (this.thinking?.type === "enabled" || this.thinking?.type === "adaptive") { - const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; - console.warn(thinkingAdmonition); - llm = this.withConfig({ - outputVersion: "v0", - tools, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - const raiseIfNoToolCalls = (message) => { - if (!message.tool_calls || message.tool_calls.length === 0) - throw new Error(thinkingAdmonition); - return message; - }; - llm = llm.pipe(raiseIfNoToolCalls); - } else - llm = this.withConfig({ - outputVersion: "v0", - tools, - tool_choice: { - type: "tool", - name: functionName - }, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - } else - throw new TypeError(`Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`); - return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatAnthropicStructuredOutput"); + if (typeof promise3.cancel === "function") { + promise3.cancel(); + } + if (message === false) { + resolve2(); + } else if (message instanceof Error) { + reject(message); + } else { + timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`; + reject(timeoutError); + } + }, milliseconds); + }); + const cancelablePromise = wrappedPromise.finally(() => { + cancelablePromise.clear(); + if (abortHandler && signal) { + signal.removeEventListener("abort", abortHandler); } + }); + cancelablePromise.clear = () => { + customTimers.clearTimeout.call(undefined, timer); + timer = undefined; }; - ChatAnthropic = class extends ChatAnthropicMessages { + return cancelablePromise; +} +var TimeoutError, getAbortedReason = (signal) => signal.reason ?? new DOMException("This operation was aborted.", "AbortError"); +var init_p_timeout = __esm(() => { + TimeoutError = class TimeoutError extends Error { + name = "TimeoutError"; + constructor(message, options) { + super(message, options); + Error.captureStackTrace?.(this, TimeoutError); + } }; }); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/utils/prompts.js -function convertPromptToAnthropic(formattedPrompt) { - const anthropicBody = _convertMessagesToAnthropicPayload(formattedPrompt.toChatMessages()); - if (anthropicBody.messages === undefined) - anthropicBody.messages = []; - return anthropicBody; +// ../../node_modules/.pnpm/p-queue@9.3.0/node_modules/p-queue/dist/lower-bound.js +function lowerBound(array3, value, comparator) { + let first = 0; + let count = array3.length; + while (count > 0) { + const step = Math.trunc(count / 2); + let it = first + step; + if (comparator(array3[it], value) <= 0) { + first = ++it; + count -= step + 1; + } else { + count = step; + } + } + return first; } -var init_prompts3 = __esm(() => { - init_message_inputs(); -}); -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/types.js -var Memory20250818ViewCommandSchema, Memory20250818CreateCommandSchema, Memory20250818StrReplaceCommandSchema, Memory20250818InsertCommandSchema, Memory20250818DeleteCommandSchema, Memory20250818RenameCommandSchema, Memory20250818CommandSchema, TextEditor20250728ViewCommandSchema, TextEditor20250728StrReplaceCommandSchema, TextEditor20250728CreateCommandSchema, TextEditor20250728InsertCommandSchema, TextEditor20250728CommandSchema, coordinateSchema, ComputerScreenshotActionSchema, ComputerLeftClickActionSchema, ComputerRightClickActionSchema, ComputerMiddleClickActionSchema, ComputerDoubleClickActionSchema, ComputerTripleClickActionSchema, ComputerLeftClickDragActionSchema, ComputerLeftMouseDownActionSchema, ComputerLeftMouseUpActionSchema, ComputerScrollActionSchema, ComputerTypeActionSchema, ComputerKeyActionSchema, ComputerMouseMoveActionSchema, ComputerHoldKeyActionSchema, ComputerWaitActionSchema, ComputerZoomActionSchema, Computer20250124ActionSchema, Computer20251124ActionSchema, Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema, Bash20250124CommandSchema; -var init_types11 = __esm(() => { - init_v43(); - Memory20250818ViewCommandSchema = exports_external.object({ - command: exports_external.literal("view"), - path: exports_external.string() - }); - Memory20250818CreateCommandSchema = exports_external.object({ - command: exports_external.literal("create"), - path: exports_external.string(), - file_text: exports_external.string() - }); - Memory20250818StrReplaceCommandSchema = exports_external.object({ - command: exports_external.literal("str_replace"), - path: exports_external.string(), - old_str: exports_external.string(), - new_str: exports_external.string() - }); - Memory20250818InsertCommandSchema = exports_external.object({ - command: exports_external.literal("insert"), - path: exports_external.string(), - insert_line: exports_external.number(), - insert_text: exports_external.string() - }); - Memory20250818DeleteCommandSchema = exports_external.object({ - command: exports_external.literal("delete"), - path: exports_external.string() - }); - Memory20250818RenameCommandSchema = exports_external.object({ - command: exports_external.literal("rename"), - old_path: exports_external.string(), - new_path: exports_external.string() - }); - Memory20250818CommandSchema = exports_external.discriminatedUnion("command", [ - Memory20250818ViewCommandSchema, - Memory20250818CreateCommandSchema, - Memory20250818StrReplaceCommandSchema, - Memory20250818InsertCommandSchema, - Memory20250818DeleteCommandSchema, - Memory20250818RenameCommandSchema - ]); - TextEditor20250728ViewCommandSchema = exports_external.object({ - command: exports_external.literal("view"), - path: exports_external.string(), - view_range: exports_external.tuple([exports_external.number(), exports_external.number()]).optional() - }); - TextEditor20250728StrReplaceCommandSchema = exports_external.object({ - command: exports_external.literal("str_replace"), - path: exports_external.string(), - old_str: exports_external.string(), - new_str: exports_external.string() - }); - TextEditor20250728CreateCommandSchema = exports_external.object({ - command: exports_external.literal("create"), - path: exports_external.string(), - file_text: exports_external.string() - }); - TextEditor20250728InsertCommandSchema = exports_external.object({ - command: exports_external.literal("insert"), - path: exports_external.string(), - insert_line: exports_external.number(), - new_str: exports_external.string() - }); - TextEditor20250728CommandSchema = exports_external.discriminatedUnion("command", [ - TextEditor20250728ViewCommandSchema, - TextEditor20250728StrReplaceCommandSchema, - TextEditor20250728CreateCommandSchema, - TextEditor20250728InsertCommandSchema - ]); - coordinateSchema = exports_external.tuple([exports_external.number(), exports_external.number()]); - ComputerScreenshotActionSchema = exports_external.object({ action: exports_external.literal("screenshot") }); - ComputerLeftClickActionSchema = exports_external.object({ - action: exports_external.literal("left_click"), - coordinate: coordinateSchema - }); - ComputerRightClickActionSchema = exports_external.object({ - action: exports_external.literal("right_click"), - coordinate: coordinateSchema - }); - ComputerMiddleClickActionSchema = exports_external.object({ - action: exports_external.literal("middle_click"), - coordinate: coordinateSchema - }); - ComputerDoubleClickActionSchema = exports_external.object({ - action: exports_external.literal("double_click"), - coordinate: coordinateSchema - }); - ComputerTripleClickActionSchema = exports_external.object({ - action: exports_external.literal("triple_click"), - coordinate: coordinateSchema - }); - ComputerLeftClickDragActionSchema = exports_external.object({ - action: exports_external.literal("left_click_drag"), - start_coordinate: coordinateSchema, - end_coordinate: coordinateSchema - }); - ComputerLeftMouseDownActionSchema = exports_external.object({ - action: exports_external.literal("left_mouse_down"), - coordinate: coordinateSchema - }); - ComputerLeftMouseUpActionSchema = exports_external.object({ - action: exports_external.literal("left_mouse_up"), - coordinate: coordinateSchema - }); - ComputerScrollActionSchema = exports_external.object({ - action: exports_external.literal("scroll"), - coordinate: coordinateSchema, - scroll_direction: exports_external.enum([ - "up", - "down", - "left", - "right" - ]), - scroll_amount: exports_external.number() - }); - ComputerTypeActionSchema = exports_external.object({ - action: exports_external.literal("type"), - text: exports_external.string() - }); - ComputerKeyActionSchema = exports_external.object({ - action: exports_external.literal("key"), - key: exports_external.string() - }); - ComputerMouseMoveActionSchema = exports_external.object({ - action: exports_external.literal("mouse_move"), - coordinate: coordinateSchema - }); - ComputerHoldKeyActionSchema = exports_external.object({ - action: exports_external.literal("hold_key"), - key: exports_external.string() - }); - ComputerWaitActionSchema = exports_external.object({ - action: exports_external.literal("wait"), - duration: exports_external.number().optional() - }); - ComputerZoomActionSchema = exports_external.object({ - action: exports_external.literal("zoom"), - region: exports_external.tuple([ - exports_external.number(), - exports_external.number(), - exports_external.number(), - exports_external.number() - ]) - }); - Computer20250124ActionSchema = exports_external.discriminatedUnion("action", [ - ComputerScreenshotActionSchema, - ComputerLeftClickActionSchema, - ComputerRightClickActionSchema, - ComputerMiddleClickActionSchema, - ComputerDoubleClickActionSchema, - ComputerTripleClickActionSchema, - ComputerLeftClickDragActionSchema, - ComputerLeftMouseDownActionSchema, - ComputerLeftMouseUpActionSchema, - ComputerScrollActionSchema, - ComputerTypeActionSchema, - ComputerKeyActionSchema, - ComputerMouseMoveActionSchema, - ComputerHoldKeyActionSchema, - ComputerWaitActionSchema - ]); - Computer20251124ActionSchema = exports_external.discriminatedUnion("action", [ - ComputerScreenshotActionSchema, - ComputerLeftClickActionSchema, - ComputerRightClickActionSchema, - ComputerMiddleClickActionSchema, - ComputerDoubleClickActionSchema, - ComputerTripleClickActionSchema, - ComputerLeftClickDragActionSchema, - ComputerLeftMouseDownActionSchema, - ComputerLeftMouseUpActionSchema, - ComputerScrollActionSchema, - ComputerTypeActionSchema, - ComputerKeyActionSchema, - ComputerMouseMoveActionSchema, - ComputerHoldKeyActionSchema, - ComputerWaitActionSchema, - ComputerZoomActionSchema - ]); - Bash20250124ExecuteCommandSchema = exports_external.object({ command: exports_external.string().describe("The bash command to run") }); - Bash20250124RestartCommandSchema = exports_external.object({ restart: exports_external.literal(true).describe("Set to true to restart the bash session") }); - Bash20250124CommandSchema = exports_external.union([Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema]); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/memory.js -function memory_20250818(options) { - const memoryTool = tool(options?.execute, { - name: "memory", - schema: Memory20250818CommandSchema - }); - memoryTool.extras = { - ...memoryTool.extras ?? {}, - providerToolDefinition: { - type: "memory_20250818", - name: "memory" +// ../../node_modules/.pnpm/p-queue@9.3.0/node_modules/p-queue/dist/priority-queue.js +class PriorityQueue { + #queue = []; + #head = 0; + enqueue(run2, options) { + const { priority = 0, id } = options ?? {}; + const { size } = this; + const element = { + priority, + id, + run: run2 + }; + if (size === 0) { + this.#queue.length = 0; + this.#head = 0; + this.#queue.push(element); + return; } - }; - return memoryTool; -} -var init_memory5 = __esm(() => { - init_types11(); - init_tools2(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/webSearch.js -function webSearch_20250305(options) { - return { - type: "web_search_20250305", - name: "web_search", - max_uses: options?.maxUses, - allowed_domains: options?.allowedDomains, - blocked_domains: options?.blockedDomains, - cache_control: options?.cacheControl, - defer_loading: options?.deferLoading, - strict: options?.strict, - user_location: options?.userLocation - }; -} -var init_webSearch = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/webFetch.js -function webFetch_20250910(options) { - return { - type: "web_fetch_20250910", - name: "web_fetch", - max_uses: options?.maxUses, - allowed_domains: options?.allowedDomains, - blocked_domains: options?.blockedDomains, - cache_control: options?.cacheControl, - citations: options?.citations, - max_content_tokens: options?.maxContentTokens - }; -} -var init_webFetch = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/toolSearch.js -function toolSearchRegex_20251119(options) { - return { - type: "tool_search_tool_regex_20251119", - name: "tool_search_tool_regex", - cache_control: options?.cacheControl - }; -} -function toolSearchBM25_20251119(options) { - return { - type: "tool_search_tool_bm25_20251119", - name: "tool_search_tool_bm25", - cache_control: options?.cacheControl - }; -} -var init_toolSearch = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/textEditor.js -function textEditor_20250728(options) { - const name = "str_replace_based_edit_tool"; - const textEditorTool = tool(options?.execute, { - name, - description: "A tool for editing text files", - schema: TextEditor20250728CommandSchema - }); - textEditorTool.extras = { - ...textEditorTool.extras ?? {}, - providerToolDefinition: { - type: "text_editor_20250728", - name, - ...options?.maxCharacters !== undefined && { max_characters: options.maxCharacters } + if (this.#queue.at(-1).priority >= priority) { + this.#queue.push(element); + return; } - }; - return textEditorTool; -} -var init_textEditor = __esm(() => { - init_types11(); - init_tools2(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/computer.js -function computer_20251124(options) { - const name = TOOL_NAME; - const computerTool = tool(options.execute, { - name, - schema: Computer20251124ActionSchema - }); - computerTool.extras = { - ...computerTool.extras ?? {}, - providerToolDefinition: { - type: "computer_20251124", - name, - display_width_px: options.displayWidthPx, - display_height_px: options.displayHeightPx, - ...options.displayNumber !== undefined && { display_number: options.displayNumber }, - ...options.enableZoom !== undefined && { enable_zoom: options.enableZoom } + this.#compact(); + const index2 = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority); + this.#queue.splice(index2, 0, element); + } + setPriority(id, priority) { + const index2 = this.#queue.findIndex((element, index3) => index3 >= this.#head && element.id === id); + if (index2 === -1) { + throw new ReferenceError(`No promise function with the id "${id}" exists in the queue.`); } - }; - return computerTool; -} -function computer_20250124(options) { - const name = TOOL_NAME; - const computerTool = tool(options.execute, { - name, - description: "A tool for interacting with the computer", - schema: Computer20250124ActionSchema - }); - computerTool.extras = { - ...computerTool.extras ?? {}, - providerToolDefinition: { - type: "computer_20250124", - name, - display_width_px: options.displayWidthPx, - display_height_px: options.displayHeightPx, - ...options.displayNumber !== undefined && { display_number: options.displayNumber } + const [item] = this.#queue.splice(index2, 1); + this.enqueue(item.run, { priority, id }); + } + remove(idOrRun) { + const index2 = this.#queue.findIndex((element, index3) => { + if (index3 < this.#head) { + return false; + } + if (typeof idOrRun === "string") { + return element.id === idOrRun; + } + return element.run === idOrRun; + }); + if (index2 !== -1) { + this.#queue.splice(index2, 1); } - }; - return computerTool; -} -var TOOL_NAME = "computer"; -var init_computer = __esm(() => { - init_types11(); - init_tools2(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/codeExecution.js -function codeExecution_20250825(options) { - return { - type: "code_execution_20250825", - name: "code_execution", - cache_control: options?.cacheControl - }; -} -var init_codeExecution = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/bash.js -function bash_20250124(options) { - const name = "bash"; - const bashTool = tool(options?.execute, { - name, - description: "A tool for executing bash commands", - schema: Bash20250124CommandSchema - }); - bashTool.extras = { - ...bashTool.extras ?? {}, - providerToolDefinition: { - type: "bash_20250124", - name + } + dequeue() { + if (this.#head === this.#queue.length) { + return; } - }; - return bashTool; -} -var init_bash = __esm(() => { - init_types11(); - init_tools2(); -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/mcpToolset.js -function mcpToolset_20251120(options) { - const defaultConfig = options.defaultConfig?.enabled !== undefined || options.defaultConfig?.deferLoading !== undefined ? { - enabled: options.defaultConfig?.enabled, - defer_loading: options.defaultConfig?.deferLoading - } : undefined; - const configs = options.configs ? Object.fromEntries(Object.entries(options.configs).map(([toolName, config2]) => [toolName, { - enabled: config2.enabled, - defer_loading: config2.deferLoading - }])) : undefined; - return { - type: "mcp_toolset", - mcp_server_name: options.serverName, - default_config: defaultConfig, - configs, - cache_control: options.cacheControl - }; -} -var init_mcpToolset = () => {}; - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/tools/index.js -var tools; -var init_tools6 = __esm(() => { - init_memory5(); - init_webSearch(); - init_webFetch(); - init_toolSearch(); - init_textEditor(); - init_computer(); - init_codeExecution(); - init_bash(); - init_mcpToolset(); - tools = { - memory_20250818, - webSearch_20250305, - webFetch_20250910, - toolSearchRegex_20251119, - toolSearchBM25_20251119, - textEditor_20250728, - computer_20251124, - computer_20250124, - codeExecution_20250825, - bash_20250124, - mcpToolset_20251120 - }; -}); - -// ../../node_modules/.pnpm/@langchain+anthropic@1.3.29_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sd_vvum3ebcgqtzgcmia7suwlwwbu/node_modules/@langchain/anthropic/dist/index.js -var exports_dist3 = {}; -__export(exports_dist3, { - tools: () => tools, - convertPromptToAnthropic: () => convertPromptToAnthropic, - ChatAnthropicMessages: () => ChatAnthropicMessages, - ChatAnthropic: () => ChatAnthropic -}); -var init_dist9 = __esm(() => { - init_chat_models3(); - init_prompts3(); - init_tools6(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/setup/async_local_storage.js -import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks"; -function initializeAsyncLocalStorageSingleton2() { - AsyncLocalStorageProviderSingleton2.initializeGlobalInstance(new AsyncLocalStorage2); -} -var init_async_local_storage3 = __esm(() => { - init_singletons(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/constants.js -function _isSendInterface2(x) { - const operation = x; - return operation !== null && operation !== undefined && typeof operation.node === "string" && operation.args !== undefined; -} -function _isSend2(x) { - return x instanceof Send2; -} -function _getOverwriteValue2(value) { - if (typeof value === "object" && value !== null && "__overwrite__" in value) - return [true, value[OVERWRITE2]]; - return [false, undefined]; -} -function _isOverwriteValue2(value) { - return _getOverwriteValue2(value)[0]; -} -function isInterrupted2(values2) { - if (!values2 || typeof values2 !== "object") - return false; - if (!("__interrupt__" in values2)) - return false; - return Array.isArray(values2[INTERRUPT3]); -} -function isCommand2(x) { - if (typeof x !== "object") - return false; - if (x === null || x === undefined) - return false; - if ("lg_name" in x && x.lg_name === "Command") - return true; - return false; -} -function _deserializeCommandSendObjectGraph2(x, seen = /* @__PURE__ */ new Map) { - if (x !== undefined && x !== null && typeof x === "object") { - if (seen.has(x)) - return seen.get(x); - let result; - if (Array.isArray(x)) { - result = []; - seen.set(x, result); - x.forEach((item, index2) => { - result[index2] = _deserializeCommandSendObjectGraph2(item, seen); - }); - } else if (isCommand2(x) && !(x instanceof Command2)) { - result = new Command2(x); - seen.set(x, result); - } else if (_isSendInterface2(x) && !(x instanceof Send2)) { - result = new Send2(x.node, x.args); - seen.set(x, result); - } else if (isCommand2(x) || _isSend2(x)) { - result = x; - seen.set(x, result); - } else if ("lc_serializable" in x && x.lc_serializable) { - result = x; - seen.set(x, result); - } else { - result = {}; - seen.set(x, result); - for (const [key, value] of Object.entries(x)) - result[key] = _deserializeCommandSendObjectGraph2(value, seen); + const item = this.#queue[this.#head]; + this.#head++; + if (this.#head === this.#queue.length) { + this.#queue.length = 0; + this.#head = 0; + } else if (this.#head > compactionThreshold && this.#head > this.#queue.length / 2) { + this.#compact(); + } + return item?.run; + } + filter(options) { + const result = []; + for (let index2 = this.#head;index2 < this.#queue.length; index2++) { + const element = this.#queue[index2]; + if (element.priority === options.priority) { + result.push(element.run); + } } return result; } - return x; -} -var START2 = "__start__", END2 = "__end__", INPUT2 = "__input__", ERROR5 = "__error__", CACHE_NS_WRITES2 = "__pregel_ns_writes", CONFIG_KEY_SEND2 = "__pregel_send", CONFIG_KEY_CALL2 = "__pregel_call", CONFIG_KEY_READ2 = "__pregel_read", CONFIG_KEY_CHECKPOINTER2 = "__pregel_checkpointer", CONFIG_KEY_RESUMING2 = "__pregel_resuming", CONFIG_KEY_TASK_ID2 = "__pregel_task_id", CONFIG_KEY_STREAM2 = "__pregel_stream", CONFIG_KEY_RESUME_VALUE2 = "__pregel_resume_value", CONFIG_KEY_RESUME_MAP2 = "__pregel_resume_map", CONFIG_KEY_SCRATCHPAD2 = "__pregel_scratchpad", CONFIG_KEY_PREVIOUS_STATE2 = "__pregel_previous", CONFIG_KEY_DURABILITY2 = "__pregel_durability", CONFIG_KEY_CHECKPOINT_ID2 = "checkpoint_id", CONFIG_KEY_CHECKPOINT_NS2 = "checkpoint_ns", CONFIG_KEY_NODE_FINISHED2 = "__pregel_node_finished", CONFIG_KEY_CHECKPOINT_MAP2 = "checkpoint_map", CONFIG_KEY_ABORT_SIGNALS2 = "__pregel_abort_signals", INTERRUPT3 = "__interrupt__", RESUME3 = "__resume__", NO_WRITES2 = "__no_writes__", RETURN2 = "__return__", PREVIOUS2 = "__previous__", TAG_HIDDEN2 = "langsmith:hidden", SELF2 = "__self__", TASKS3 = "__pregel_tasks", PUSH2 = "__pregel_push", PULL2 = "__pregel_pull", NULL_TASK_ID2 = "00000000-0000-0000-0000-000000000000", RESERVED2, COMMAND_SYMBOL2, CommandInstance2, Send2 = class { - lg_name = "Send"; - node; - args; - constructor(node, args) { - this.node = node; - this.args = _deserializeCommandSendObjectGraph2(args); + get size() { + return this.#queue.length - this.#head; } - toJSON() { - return { - lg_name: this.lg_name, - node: this.node, - args: this.args - }; + #compact() { + if (this.#head === 0) { + return; + } + this.#queue.splice(0, this.#head); + this.#head = 0; } -}, OVERWRITE2 = "__overwrite__", Overwrite2, Command2; -var init_constants8 = __esm(() => { - RESERVED2 = [ - TAG_HIDDEN2, - INPUT2, - INTERRUPT3, - RESUME3, - ERROR5, - NO_WRITES2, - CONFIG_KEY_SEND2, - CONFIG_KEY_READ2, - CONFIG_KEY_CHECKPOINTER2, - CONFIG_KEY_DURABILITY2, - CONFIG_KEY_STREAM2, - CONFIG_KEY_RESUMING2, - CONFIG_KEY_TASK_ID2, - CONFIG_KEY_CALL2, - CONFIG_KEY_RESUME_VALUE2, - CONFIG_KEY_SCRATCHPAD2, - CONFIG_KEY_PREVIOUS_STATE2, - CONFIG_KEY_CHECKPOINT_MAP2, - CONFIG_KEY_CHECKPOINT_NS2, - CONFIG_KEY_CHECKPOINT_ID2 - ]; - COMMAND_SYMBOL2 = Symbol.for("langgraph.command"); - CommandInstance2 = class { - [COMMAND_SYMBOL2]; - constructor(args) { - this[COMMAND_SYMBOL2] = args; +} +var compactionThreshold = 100; +var init_priority_queue = () => {}; + +// ../../node_modules/.pnpm/p-queue@9.3.0/node_modules/p-queue/dist/index.js +var PQueue2; +var init_dist7 = __esm(() => { + init_eventemitter3(); + init_p_timeout(); + init_priority_queue(); + PQueue2 = class PQueue2 extends import__3.default { + #carryoverIntervalCount; + #isIntervalIgnored; + #intervalCount = 0; + #intervalCap; + #rateLimitedInInterval = false; + #rateLimitFlushScheduled = false; + #interval; + #intervalEnd = 0; + #lastExecutionTime = 0; + #intervalId; + #timeoutId; + #strict; + #strictTicks = []; + #strictTicksStartIndex = 0; + #queue; + #queueClass; + #pending = 0; + #concurrency; + #isPaused; + #idAssigner = 1n; + #runningTasks = new Map; + #queueAbortListenerCleanupFunctions = new Set; + timeout; + constructor(options) { + super(); + options = { + carryoverIntervalCount: false, + intervalCap: Number.POSITIVE_INFINITY, + interval: 0, + concurrency: Number.POSITIVE_INFINITY, + autoStart: true, + queueClass: PriorityQueue, + strict: false, + ...options + }; + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${typeof options.intervalCap})`); + } + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`); + } + if (options.strict && options.interval === 0) { + throw new TypeError("The `strict` option requires a non-zero `interval`"); + } + if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) { + throw new TypeError("The `strict` option requires a finite `intervalCap`"); + } + this.#carryoverIntervalCount = options.carryoverIntervalCount ?? options.carryoverConcurrencyCount ?? false; + this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0; + this.#intervalCap = options.intervalCap; + this.#interval = options.interval; + this.#strict = options.strict; + this.#queue = new options.queueClass; + this.#queueClass = options.queueClass; + this.concurrency = options.concurrency; + if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) { + throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${options.timeout}\` (${typeof options.timeout})`); + } + this.timeout = options.timeout; + this.#isPaused = options.autoStart === false; + this.#setupRateLimitTracking(); } - }; - Overwrite2 = class { - lg_name = "Overwrite"; - [OVERWRITE2]; - constructor(value) { - this[OVERWRITE2] = value; + #cleanupStrictTicks(now) { + while (this.#strictTicksStartIndex < this.#strictTicks.length) { + const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; + if (oldestTick !== undefined && now - oldestTick >= this.#interval) { + this.#strictTicksStartIndex++; + } else { + break; + } + } + const shouldCompact = this.#strictTicksStartIndex > 100 && this.#strictTicksStartIndex > this.#strictTicks.length / 2 || this.#strictTicksStartIndex === this.#strictTicks.length; + if (shouldCompact) { + this.#strictTicks = this.#strictTicks.slice(this.#strictTicksStartIndex); + this.#strictTicksStartIndex = 0; + } } - get value() { - return this[OVERWRITE2]; + #consumeIntervalSlot(now) { + if (this.#strict) { + this.#strictTicks.push(now); + } else { + this.#intervalCount++; + } } - toJSON() { - return { [OVERWRITE2]: this[OVERWRITE2] }; + #rollbackIntervalSlot() { + if (this.#strict) { + if (this.#strictTicks.length > this.#strictTicksStartIndex) { + this.#strictTicks.pop(); + } + } else if (this.#intervalCount > 0) { + this.#intervalCount--; + } } - static isInstance(value) { - if (!value || typeof value !== "object") - return false; - if ("__overwrite__" in value) - return true; - if ("lg_name" in value && value.lg_name === "Overwrite") + #getActiveTicksCount() { + return this.#strictTicks.length - this.#strictTicksStartIndex; + } + get #doesIntervalAllowAnother() { + if (this.#isIntervalIgnored) { return true; - return false; + } + if (this.#strict) { + return this.#getActiveTicksCount() < this.#intervalCap; + } + return this.#intervalCount < this.#intervalCap; } - }; - Command2 = class extends CommandInstance2 { - lg_name = "Command"; - lc_direct_tool_output = true; - graph; - update; - resume; - goto = []; - static PARENT = "__parent__"; - constructor(args) { - super(args); - this.resume = args.resume; - this.graph = args.graph; - this.update = args.update; - if (args.goto) - this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph2(args.goto) : [_deserializeCommandSendObjectGraph2(args.goto)]; + get #doesConcurrentAllowAnother() { + return this.#pending < this.#concurrency; } - _updateAsTuples() { - if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) - return Object.entries(this.update); - else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) - return this.update; - else - return [["__root__", this.update]]; + #next() { + this.#pending--; + if (this.#pending === 0) { + this.emit("pendingZero"); + } + this.#tryToStartAnother(); + this.emit("next"); } - toJSON() { - let serializedGoto; - if (typeof this.goto === "string") - serializedGoto = this.goto; - else if (_isSend2(this.goto)) - serializedGoto = this.goto.toJSON(); - else - serializedGoto = this.goto?.map((innerGoto) => { - if (typeof innerGoto === "string") - return innerGoto; - else - return innerGoto.toJSON(); - }); - return { - lg_name: this.lg_name, - update: this.update, - resume: this.resume, - goto: serializedGoto - }; + #onResumeInterval() { + this.#timeoutId = undefined; + this.#onInterval(); + this.#initializeIntervalIfNeeded(); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/errors.js -function isParentCommand2(e) { - return e !== undefined && e.name === ParentCommand2.unminifiable_name; -} -function isGraphBubbleUp2(e) { - return e !== undefined && e.is_bubble_up === true; -} -function isGraphInterrupt2(e) { - return e !== undefined && [GraphInterrupt2.unminifiable_name, NodeInterrupt2.unminifiable_name].includes(e.name); -} -var BaseLangGraphError2, GraphBubbleUp2, GraphRecursionError2, GraphValueError2, GraphInterrupt2, NodeInterrupt2, ParentCommand2, EmptyInputError2, EmptyChannelError2, InvalidUpdateError2, MultipleSubgraphsError2, UnreachableNodeError2, RemoteException2, StateGraphInputError2, getSubgraphsSeenSet2 = () => { - if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === undefined) - globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set; - return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; -}; -var init_errors10 = __esm(() => { - BaseLangGraphError2 = class extends Error { - lc_error_code; - constructor(message, fields) { - let finalMessage = message ?? ""; - if (fields?.lc_error_code) - finalMessage = `${finalMessage} - -Troubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/ -`; - super(finalMessage); - this.lc_error_code = fields?.lc_error_code; + #isIntervalPausedAt(now) { + if (this.#strict) { + this.#cleanupStrictTicks(now); + const activeTicksCount = this.#getActiveTicksCount(); + if (activeTicksCount >= this.#intervalCap) { + const oldestTick = this.#strictTicks[this.#strictTicksStartIndex]; + const delay = this.#interval - (now - oldestTick); + this.#createIntervalTimeout(delay); + return true; + } + return false; + } + if (this.#intervalId === undefined) { + const delay = this.#intervalEnd - now; + if (delay < 0) { + if (this.#lastExecutionTime > 0) { + const timeSinceLastExecution = now - this.#lastExecutionTime; + if (timeSinceLastExecution < this.#interval) { + this.#createIntervalTimeout(this.#interval - timeSinceLastExecution); + return true; + } + } + this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; + } else { + this.#createIntervalTimeout(delay); + return true; + } + } + return false; } - }; - GraphBubbleUp2 = class extends BaseLangGraphError2 { - get is_bubble_up() { - return true; + #createIntervalTimeout(delay) { + if (this.#timeoutId !== undefined) { + return; + } + this.#timeoutId = setTimeout(() => { + this.#onResumeInterval(); + }, delay); } - }; - GraphRecursionError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "GraphRecursionError"; + #clearIntervalTimer() { + if (this.#intervalId) { + clearInterval(this.#intervalId); + this.#intervalId = undefined; + } } - static get unminifiable_name() { - return "GraphRecursionError"; + #clearTimeoutTimer() { + if (this.#timeoutId) { + clearTimeout(this.#timeoutId); + this.#timeoutId = undefined; + } } - }; - GraphValueError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "GraphValueError"; + #tryToStartAnother() { + if (this.#queue.size === 0) { + this.#clearIntervalTimer(); + this.emit("empty"); + if (this.#pending === 0) { + this.#clearTimeoutTimer(); + if (this.#strict && this.#strictTicksStartIndex > 0) { + const now = Date.now(); + this.#cleanupStrictTicks(now); + } + this.emit("idle"); + } + return false; + } + let taskStarted = false; + if (!this.#isPaused) { + const now = Date.now(); + const canInitializeInterval = !this.#isIntervalPausedAt(now); + if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) { + const job = this.#queue.dequeue(); + if (!this.#isIntervalIgnored) { + this.#consumeIntervalSlot(now); + this.#scheduleRateLimitUpdate(); + } + this.emit("active"); + job(); + if (canInitializeInterval) { + this.#initializeIntervalIfNeeded(); + } + taskStarted = true; + } + } + return taskStarted; } - static get unminifiable_name() { - return "GraphValueError"; + #initializeIntervalIfNeeded() { + if (this.#isIntervalIgnored || this.#intervalId !== undefined) { + return; + } + if (this.#strict) { + return; + } + this.#intervalId = setInterval(() => { + this.#onInterval(); + }, this.#interval); + this.#intervalEnd = Date.now() + this.#interval; } - }; - GraphInterrupt2 = class extends GraphBubbleUp2 { - interrupts; - constructor(interrupts, fields) { - super(JSON.stringify(interrupts, null, 2), fields); - this.name = "GraphInterrupt"; - this.interrupts = interrupts ?? []; + #onInterval() { + if (!this.#strict) { + if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) { + this.#clearIntervalTimer(); + } + this.#intervalCount = this.#carryoverIntervalCount ? this.#pending : 0; + } + this.#processQueue(); + this.#scheduleRateLimitUpdate(); } - static get unminifiable_name() { - return "GraphInterrupt"; + #processQueue() { + while (this.#tryToStartAnother()) {} } - }; - NodeInterrupt2 = class extends GraphInterrupt2 { - constructor(message, fields) { - super([{ value: message }], fields); - this.name = "NodeInterrupt"; + get concurrency() { + return this.#concurrency; } - static get unminifiable_name() { - return "NodeInterrupt"; + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this.#concurrency = newConcurrency; + this.#processQueue(); } - }; - ParentCommand2 = class extends GraphBubbleUp2 { - command; - constructor(command) { - super(); - this.name = "ParentCommand"; - this.command = command; + setPriority(id, priority) { + if (typeof priority !== "number" || !Number.isFinite(priority)) { + throw new TypeError(`Expected \`priority\` to be a finite number, got \`${priority}\` (${typeof priority})`); + } + this.#queue.setPriority(id, priority); } - static get unminifiable_name() { - return "ParentCommand"; + async add(function_, options = {}) { + options = { + timeout: this.timeout, + ...options, + id: options.id ?? (this.#idAssigner++).toString() + }; + return new Promise((resolve2, reject) => { + const taskSymbol = Symbol(`task-${options.id}`); + let cleanupQueueAbortHandler = () => { + return; + }; + const run2 = async () => { + cleanupQueueAbortHandler(); + this.#pending++; + this.#runningTasks.set(taskSymbol, { + id: options.id, + priority: options.priority ?? 0, + startTime: Date.now(), + timeout: options.timeout + }); + let eventListener; + try { + try { + options.signal?.throwIfAborted(); + } catch (error90) { + this.#rollbackIntervalConsumption(); + this.#runningTasks.delete(taskSymbol); + throw error90; + } + this.#lastExecutionTime = Date.now(); + let operation = function_({ signal: options.signal }); + if (options.timeout) { + operation = pTimeout(Promise.resolve(operation), { + milliseconds: options.timeout, + message: `Task timed out after ${options.timeout}ms (queue has ${this.#pending} running, ${this.#queue.size} waiting)` + }); + } + if (options.signal) { + const { signal } = options; + operation = Promise.race([operation, new Promise((_resolve, reject2) => { + eventListener = () => { + reject2(signal.reason); + }; + signal.addEventListener("abort", eventListener, { once: true }); + })]); + } + const result = await operation; + resolve2(result); + this.emit("completed", result); + } catch (error90) { + reject(error90); + this.emit("error", error90); + } finally { + if (eventListener) { + options.signal?.removeEventListener("abort", eventListener); + } + this.#runningTasks.delete(taskSymbol); + queueMicrotask(() => { + this.#next(); + }); + } + }; + this.#queue.enqueue(run2, options); + const removeQueuedTask = () => { + if (this.#queue instanceof PriorityQueue) { + this.#queue.remove(run2); + return; + } + this.#queue.remove?.(options.id); + }; + if (options.signal) { + const { signal } = options; + const queueAbortHandler = () => { + cleanupQueueAbortHandler(); + removeQueuedTask(); + reject(signal.reason); + this.#tryToStartAnother(); + this.emit("next"); + }; + cleanupQueueAbortHandler = () => { + signal.removeEventListener("abort", queueAbortHandler); + this.#queueAbortListenerCleanupFunctions.delete(cleanupQueueAbortHandler); + }; + if (signal.aborted) { + queueAbortHandler(); + return; + } + signal.addEventListener("abort", queueAbortHandler, { once: true }); + this.#queueAbortListenerCleanupFunctions.add(cleanupQueueAbortHandler); + } + this.emit("add"); + this.#tryToStartAnother(); + }); } - }; - EmptyInputError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyInputError"; + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); } - static get unminifiable_name() { - return "EmptyInputError"; + start() { + if (!this.#isPaused) { + return this; + } + this.#isPaused = false; + this.#processQueue(); + return this; } - }; - EmptyChannelError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyChannelError"; + pause() { + this.#isPaused = true; } - static get unminifiable_name() { - return "EmptyChannelError"; + clear() { + for (const cleanupQueueAbortHandler of this.#queueAbortListenerCleanupFunctions) { + cleanupQueueAbortHandler(); + } + this.#queue = new this.#queueClass; + this.#clearIntervalTimer(); + this.#updateRateLimitState(); + this.emit("empty"); + if (this.#pending === 0) { + this.#clearTimeoutTimer(); + this.emit("idle"); + } + this.emit("next"); } - }; - InvalidUpdateError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "InvalidUpdateError"; + async onEmpty() { + if (this.#queue.size === 0) { + return; + } + await this.#onEvent("empty"); } - static get unminifiable_name() { - return "InvalidUpdateError"; + async onSizeLessThan(limit) { + if (this.#queue.size < limit) { + return; + } + await this.#onEvent("next", () => this.#queue.size < limit); } - }; - MultipleSubgraphsError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "MultipleSubgraphError"; + async onIdle() { + if (this.#pending === 0 && this.#queue.size === 0) { + return; + } + await this.#onEvent("idle"); } - static get unminifiable_name() { - return "MultipleSubgraphError"; + async onPendingZero() { + if (this.#pending === 0) { + return; + } + await this.#onEvent("pendingZero"); } - }; - UnreachableNodeError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "UnreachableNodeError"; + async onRateLimit() { + if (this.isRateLimited) { + return; + } + await this.#onEvent("rateLimit"); } - static get unminifiable_name() { - return "UnreachableNodeError"; + async onRateLimitCleared() { + if (!this.isRateLimited) { + return; + } + await this.#onEvent("rateLimitCleared"); } - }; - RemoteException2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "RemoteException"; + onError() { + return new Promise((_resolve, reject) => { + const handleError = (error90) => { + this.off("error", handleError); + reject(error90); + }; + this.on("error", handleError); + }); } - static get unminifiable_name() { - return "RemoteException"; + async#onEvent(event, filter) { + return new Promise((resolve2) => { + const listener = () => { + if (filter && !filter()) { + return; + } + this.off(event, listener); + resolve2(); + }; + this.on(event, listener); + }); } - }; - StateGraphInputError2 = class extends BaseLangGraphError2 { - constructor(message, fields) { - super(message, fields); - this.name = "StateGraphInputError"; - this.message = "Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema."; + get size() { + return this.#queue.size; } - static get unminifiable_name() { - return "StateGraphInputError"; + sizeBy(options) { + return this.#queue.filter(options).length; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/base.js -function isBaseChannel2(obj) { - return obj != null && obj.lg_is_channel === true; -} -function getOnlyChannels2(channels) { - if (channels[IS_ONLY_BASE_CHANNEL2] === true) - return channels; - const newChannels = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) - continue; - const value = channels[k]; - if (isBaseChannel2(value)) - newChannels[k] = value; - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL2]: true }); - return newChannels; -} -function emptyChannels2(channels, checkpoint) { - const filteredChannels = getOnlyChannels2(channels); - const newChannels = {}; - for (const k in filteredChannels) { - if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) - continue; - const channelValue = checkpoint.channel_values[k]; - newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL2]: true }); - return newChannels; -} -function createCheckpoint2(checkpoint, channels, step, options) { - let values2; - if (channels === undefined) - values2 = checkpoint.channel_values; - else { - values2 = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) - continue; - try { - values2[k] = channels[k].checkpoint(); - } catch (error52) { - if (error52.name === EmptyChannelError2.unminifiable_name) {} else - throw error52; - } + get pending() { + return this.#pending; } - } - return { - v: 4, - id: options?.id ?? uuid62(step), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: values2, - channel_versions: checkpoint.channel_versions, - versions_seen: checkpoint.versions_seen - }; -} -var BaseChannel2 = class { - ValueType; - UpdateType; - lg_is_channel = true; - consume() { - return false; - } - finish() { - return false; - } - isAvailable() { - try { - this.get(); - return true; - } catch (error52) { - if (error52.name === EmptyChannelError2.unminifiable_name) - return false; - throw error52; - } - } - equals(other) { - return this === other; - } -}, IS_ONLY_BASE_CHANNEL2; -var init_base17 = __esm(() => { - init_errors10(); - init_dist3(); - IS_ONLY_BASE_CHANNEL2 = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/binop.js -var isBinaryOperatorAggregate2 = (value) => { - return value != null && value.lc_graph_name === "BinaryOperatorAggregate"; -}, BinaryOperatorAggregate3; -var init_binop2 = __esm(() => { - init_constants8(); - init_errors10(); - init_base17(); - BinaryOperatorAggregate3 = class BinaryOperatorAggregate4 extends BaseChannel2 { - lc_graph_name = "BinaryOperatorAggregate"; - value; - operator; - initialValueFactory; - constructor(operator, initialValueFactory) { - super(); - this.operator = operator; - this.initialValueFactory = initialValueFactory; - this.value = initialValueFactory?.(); - } - fromCheckpoint(checkpoint) { - const empty = new BinaryOperatorAggregate4(this.operator, this.initialValueFactory); - if (typeof checkpoint !== "undefined") - empty.value = checkpoint; - return empty; + get isPaused() { + return this.#isPaused; } - update(values2) { - let newValues = values2; - if (!newValues.length) - return false; - if (this.value === undefined) { - const first = newValues[0]; - const [isOverwrite, overwriteVal] = _getOverwriteValue2(first); - if (isOverwrite) - this.value = overwriteVal; - else - this.value = first; - newValues = newValues.slice(1); + #setupRateLimitTracking() { + if (this.#isIntervalIgnored) { + return; } - let seenOverwrite = false; - for (const incoming of newValues) - if (_isOverwriteValue2(incoming)) { - if (seenOverwrite) - throw new InvalidUpdateError2("Can receive only one Overwrite value per step."); - const [, val] = _getOverwriteValue2(incoming); - this.value = val; - seenOverwrite = true; - continue; - } else if (!seenOverwrite && this.value !== undefined) - this.value = this.operator(this.value, incoming); - return true; - } - get() { - if (this.value === undefined) - throw new EmptyChannelError2; - return this.value; - } - checkpoint() { - if (this.value === undefined) - throw new EmptyChannelError2; - return this.value; - } - isAvailable() { - return this.value !== undefined; - } - equals(other) { - if (this === other) - return true; - if (!isBinaryOperatorAggregate2(other)) - return false; - return this.operator === other.operator; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/last_value.js -var LastValue3, LastValueAfterFinish3; -var init_last_value2 = __esm(() => { - init_errors10(); - init_base17(); - LastValue3 = class LastValue4 extends BaseChannel2 { - lc_graph_name = "LastValue"; - value = []; - constructor(initialValueFactory) { - super(); - this.initialValueFactory = initialValueFactory; - if (initialValueFactory) - this.value = [initialValueFactory()]; - } - fromCheckpoint(checkpoint) { - const empty = new LastValue4(this.initialValueFactory); - if (typeof checkpoint !== "undefined") - empty.value = [checkpoint]; - return empty; - } - update(values2) { - if (values2.length === 0) - return false; - if (values2.length !== 1) - throw new InvalidUpdateError2("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this.value = [values2[values2.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) - throw new EmptyChannelError2; - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) - throw new EmptyChannelError2; - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; + this.on("add", () => { + if (this.#queue.size > 0) { + this.#scheduleRateLimitUpdate(); + } + }); + this.on("next", () => { + this.#scheduleRateLimitUpdate(); + }); } - }; - LastValueAfterFinish3 = class LastValueAfterFinish4 extends BaseChannel2 { - lc_graph_name = "LastValueAfterFinish"; - value = []; - finished = false; - fromCheckpoint(checkpoint) { - const empty = new LastValueAfterFinish4; - if (typeof checkpoint !== "undefined") { - const [value, finished] = checkpoint; - empty.value = [value]; - empty.finished = finished; + #scheduleRateLimitUpdate() { + if (this.#isIntervalIgnored || this.#rateLimitFlushScheduled) { + return; } - return empty; - } - update(values2) { - if (values2.length === 0) - return false; - this.finished = false; - this.value = [values2[values2.length - 1]]; - return true; - } - get() { - if (this.value.length === 0 || !this.finished) - throw new EmptyChannelError2; - return this.value[0]; + this.#rateLimitFlushScheduled = true; + queueMicrotask(() => { + this.#rateLimitFlushScheduled = false; + this.#updateRateLimitState(); + }); } - checkpoint() { - if (this.value.length === 0) + #rollbackIntervalConsumption() { + if (this.#isIntervalIgnored) { return; - return [this.value[0], this.finished]; - } - consume() { - if (this.finished) { - this.finished = false; - this.value = []; - return true; } - return false; + this.#rollbackIntervalSlot(); + this.#scheduleRateLimitUpdate(); } - finish() { - if (!this.finished && this.value.length > 0) { - this.finished = true; - return true; + #updateRateLimitState() { + const previous = this.#rateLimitedInInterval; + if (this.#isIntervalIgnored || this.#queue.size === 0) { + if (previous) { + this.#rateLimitedInInterval = false; + this.emit("rateLimitCleared"); + } + return; + } + let count; + if (this.#strict) { + const now = Date.now(); + this.#cleanupStrictTicks(now); + count = this.#getActiveTicksCount(); + } else { + count = this.#intervalCount; + } + const shouldBeRateLimited = count >= this.#intervalCap; + if (shouldBeRateLimited !== previous) { + this.#rateLimitedInInterval = shouldBeRateLimited; + this.emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared"); } - return false; } - isAvailable() { - return this.value.length !== 0 && this.finished; + get isRateLimited() { + return this.#rateLimitedInInterval; + } + get isSaturated() { + return this.#pending === this.#concurrency && this.#queue.size > 0 || this.isRateLimited && this.#queue.size > 0; + } + get runningTasks() { + return [...this.#runningTasks.values()].map((task3) => ({ + ...task3, + timeoutRemaining: task3.timeout ? Math.max(0, task3.startTime + task3.timeout - Date.now()) : undefined + })); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/annotation.js -function getChannel2(reducer) { - if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) - return new BinaryOperatorAggregate3(reducer.reducer, reducer.default); - if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) - return new BinaryOperatorAggregate3(reducer.value, reducer.default); - return new LastValue3; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/async_caller.js +function isResponse(x) { + if (x == null || typeof x !== "object") + return false; + return "status" in x && "statusText" in x && "text" in x; } -var AnnotationRoot2 = class { - lc_graph_name = "AnnotationRoot"; - spec; - constructor(s) { - this.spec = s; +var STATUS_NO_RETRY2, HTTPError, AsyncCaller3 = class { + maxConcurrency; + maxRetries; + queue; + onFailedResponseHook; + customFetch; + constructor(params) { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 4; + if ("default" in PQueue2) + this.queue = new PQueue2.default({ concurrency: this.maxConcurrency }); + else + this.queue = new PQueue2({ concurrency: this.maxConcurrency }); + this.onFailedResponseHook = params?.onFailedResponseHook; + this.customFetch = params.fetch; } - static isInstance(value) { - return typeof value === "object" && value !== null && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot"; + call(callable, ...args) { + const { onFailedResponseHook } = this; + return this.queue.add(() => pRetry3(() => callable(...args).catch(async (error90) => { + if (error90 instanceof Error) + throw error90; + else if (isResponse(error90)) + throw await HTTPError.fromResponse(error90, { includeResponse: !!onFailedResponseHook }); + else + throw new Error(error90); + }), { + async onFailedAttempt({ error: error90, retriesLeft }) { + const errorMessage = error90.message ?? ""; + if (errorMessage.startsWith("Cancel") || errorMessage.startsWith("TimeoutError") || errorMessage.startsWith("AbortError")) + throw error90; + if (error90?.code === "ECONNABORTED") + throw error90; + if (errorMessage.includes("ECONNREFUSED") || errorMessage.includes("fetch failed") || errorMessage.includes("Failed to fetch") || errorMessage.includes("NetworkError")) { + if (retriesLeft > 0) + return; + const connectionError = /* @__PURE__ */ new Error(`Unable to connect to LangGraph server. Please ensure the server is running and accessible. Original error: ${errorMessage}`); + connectionError.name = "ConnectionError"; + throw connectionError; + } + if (error90 instanceof HTTPError) { + if (STATUS_NO_RETRY2.includes(error90.status)) + throw error90; + if (onFailedResponseHook && error90.response) + await onFailedResponseHook(error90.response); + } + }, + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + callWithOptions(options, callable, ...args) { + if (options.signal) + return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(/* @__PURE__ */ new Error("AbortError")); + }); + })]); + return this.call(callable, ...args); + } + fetch(...args) { + const fetchFn = this.customFetch ?? _getFetchImplementation2(); + return this.call(() => fetchFn(...args).then((res) => res.ok ? res : Promise.reject(res))); } -}, Annotation2 = function(annotation) { - if (annotation) - return getChannel2(annotation); - else - return new LastValue3; }; -var init_annotation3 = __esm(() => { - init_binop2(); - init_last_value2(); - Annotation2.Root = (sd) => new AnnotationRoot2(sd); +var init_async_caller3 = __esm(() => { + init_fetch2(); + init_p_retry3(); + init_dist7(); + STATUS_NO_RETRY2 = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 408, + 409, + 422 + ]; + HTTPError = class HTTPError2 extends Error { + status; + text; + response; + constructor(status, message, response) { + super(`HTTP ${status}: ${message}`); + this.status = status; + this.text = message; + this.response = response; + } + static async fromResponse(response, options) { + try { + return new HTTPError2(response.status, await response.text(), options?.includeResponse ? response : undefined); + } catch { + return new HTTPError2(response.status, response.statusText, options?.includeResponse ? response : undefined); + } + } + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/utils/config.js -function propagateConfigurableToMetadata2(configurable, metadata) { - if (!configurable) - return metadata; - const result = metadata ?? {}; - for (const key of PROPAGATE_TO_METADATA2) { - if (key in result) - continue; - const value = configurable[key]; - if (value !== undefined) - result[key] = value; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/env.js +function getEnvironmentVariable3(name) { + try { + return typeof process !== "undefined" ? process.env?.[name] : undefined; + } catch { + return; } - return result; } -function ensureLangGraphConfig2(...configs) { - const empty = { - tags: [], - metadata: {}, - callbacks: undefined, - recursionLimit: DEFAULT_RECURSION_LIMIT2, - configurable: {} - }; - const implicitConfig = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (implicitConfig !== undefined) { - for (const [k, v] of Object.entries(implicitConfig)) - if (v !== undefined) - if (COPIABLE_KEYS2.includes(k)) { - let copiedValue; - if (Array.isArray(v)) - copiedValue = [...v]; - else if (typeof v === "object") - if (k === "callbacks" && "copy" in v && typeof v.copy === "function") - copiedValue = v.copy(); - else - copiedValue = { ...v }; - else - copiedValue = v; - empty[k] = copiedValue; - } else - empty[k] = v; - } - for (const config2 of configs) { - if (config2 === undefined) - continue; - for (const [k, v] of Object.entries(config2)) - if (v !== undefined && CONFIG_KEYS2.includes(k)) - empty[k] = v; +var init_env4 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/signals.js +function mergeSignals(...signals) { + const nonZeroSignals = signals.filter((signal) => signal != null); + if (nonZeroSignals.length === 0) + return; + if (nonZeroSignals.length === 1) + return nonZeroSignals[0]; + const controller = new AbortController; + for (const signal of signals) { + if (signal?.aborted) { + controller.abort(signal.reason); + return controller.signal; + } + signal?.addEventListener("abort", () => controller.abort(signal.reason), { once: true }); } - empty.metadata = propagateConfigurableToMetadata2(empty.configurable, empty.metadata) ?? {}; - return empty; -} -function getStore2(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join(` -`)); - return runConfig?.store; -} -function getWriter2(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join(` -`)); - return runConfig?.writer || runConfig?.configurable?.writer; + return controller.signal; } -function getConfig2() { - return AsyncLocalStorageProviderSingleton2.getRunnableConfig(); +var init_signals = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/sse.js +function BytesLineDecoder() { + let buffer = []; + let trailingCr = false; + return new TransformStream({ + start() { + buffer = []; + trailingCr = false; + }, + transform(chunk, controller) { + let text = chunk; + if (trailingCr) { + text = joinArrays([[CR], text]); + trailingCr = false; + } + if (text.length > 0 && text.at(-1) === CR) { + trailingCr = true; + text = text.subarray(0, -1); + } + if (!text.length) + return; + const trailingNewline = TRAILING_NEWLINE.includes(text.at(-1)); + const lastIdx = text.length - 1; + const { lines } = text.reduce((acc, cur, idx) => { + if (acc.from > idx) + return acc; + if (cur === CR || cur === LF) { + acc.lines.push(text.subarray(acc.from, idx)); + if (cur === CR && text[idx + 1] === LF) + acc.from = idx + 2; + else + acc.from = idx + 1; + } + if (idx === lastIdx && acc.from <= lastIdx) + acc.lines.push(text.subarray(acc.from)); + return acc; + }, { + lines: [], + from: 0 + }); + if (lines.length === 1 && !trailingNewline) { + buffer.push(lines[0]); + return; + } + if (buffer.length) { + buffer.push(lines[0]); + lines[0] = joinArrays(buffer); + buffer = []; + } + if (!trailingNewline) { + if (lines.length) + buffer = [lines.pop()]; + } + for (const line of lines) + controller.enqueue(line); + }, + flush(controller) { + if (buffer.length) + controller.enqueue(joinArrays(buffer)); + } + }); } -function getCurrentTaskInput2(config2) { - const runConfig = config2 ?? AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (runConfig === undefined) - throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join(` -`)); - if (runConfig.configurable?.["__pregel_scratchpad"]?.currentTaskInput === undefined) - throw new Error("BUG: internal scratchpad not initialized."); - return runConfig.configurable[CONFIG_KEY_SCRATCHPAD2].currentTaskInput; +function SSEDecoder() { + let event = ""; + let data = []; + let lastEventId = ""; + let retry = null; + const decoder = new TextDecoder; + return new TransformStream({ + transform(chunk, controller) { + if (!chunk.length) { + if (!event && !data.length && !lastEventId && retry == null) + return; + const sse = { + id: lastEventId || undefined, + event, + data: data.length ? decodeArraysToJson(decoder, data) : null + }; + event = ""; + data = []; + retry = null; + controller.enqueue(sse); + return; + } + if (chunk[0] === COLON) + return; + const sepIdx = chunk.indexOf(COLON); + if (sepIdx === -1) + return; + const fieldName = decoder.decode(chunk.subarray(0, sepIdx)); + let value = chunk.subarray(sepIdx + 1); + if (value[0] === SPACE) + value = value.subarray(1); + if (fieldName === "event") + event = decoder.decode(value); + else if (fieldName === "data") + data.push(value); + else if (fieldName === "id") { + if (value.indexOf(NULL) === -1) + lastEventId = decoder.decode(value); + } else if (fieldName === "retry") { + const retryNum = Number.parseInt(decoder.decode(value), 10); + if (!Number.isNaN(retryNum)) + retry = retryNum; + } + }, + flush(controller) { + if (event) + controller.enqueue({ + id: lastEventId || undefined, + event, + data: data.length ? decodeArraysToJson(decoder, data) : null + }); + } + }); } -function recastCheckpointNamespace2(namespace) { - return namespace.split("|").filter((part) => !part.match(/^\d+$/)).map((part) => part.split(":")[0]).join("|"); +function joinArrays(data) { + const totalLength = data.reduce((acc, curr) => acc + curr.length, 0); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const c of data) { + merged.set(c, offset); + offset += c.length; + } + return merged; } -function getParentCheckpointNamespace2(namespace) { - const parts = namespace.split("|"); - while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) - parts.pop(); - return parts.slice(0, -1).join("|"); +function decodeArraysToJson(decoder, data) { + return JSON.parse(decoder.decode(joinArrays(data))); } -var COPIABLE_KEYS2, CONFIG_KEYS2, DEFAULT_RECURSION_LIMIT2 = 25, PROPAGATE_TO_METADATA2; -var init_config3 = __esm(() => { - init_constants8(); - init_singletons(); - COPIABLE_KEYS2 = [ - "tags", - "metadata", - "callbacks", - "configurable" - ]; - CONFIG_KEYS2 = [ - "tags", - "metadata", - "callbacks", - "runName", - "maxConcurrency", - "recursionLimit", - "configurable", - "runId", - "outputKeys", - "streamMode", - "store", - "writer", - "interrupt", - "context", - "interruptBefore", - "interruptAfter", - "checkpointDuring", - "durability", - "signal", - "executionInfo", - "serverInfo" - ]; - PROPAGATE_TO_METADATA2 = new Set([ - "thread_id", - "checkpoint_id", - "checkpoint_ns", - "task_id", - "run_id", - "assistant_id", - "graph_id" - ]); +var CR = 13, LF = 10, NULL = 0, COLON = 58, SPACE = 32, TRAILING_NEWLINE; +var init_sse = __esm(() => { + TRAILING_NEWLINE = [CR, LF]; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/stream-channel.js -function isStreamChannel2(value) { - return StreamChannel3.isInstance(value); -} -var STREAM_CHANNEL_BRAND2, StreamChannel3; -var init_stream_channel2 = __esm(() => { - STREAM_CHANNEL_BRAND2 = Symbol.for("langgraph.stream_channel"); - StreamChannel3 = class StreamChannel4 { - [STREAM_CHANNEL_BRAND2] = true; - channelName; - #items = []; - #waiters = []; - #done = false; - #error; - #onPush; - constructor(name) { - this.channelName = name; - } - static local() { - return new StreamChannel4; - } - static remote(name) { - return new StreamChannel4(name); - } - static isInstance(value) { - return typeof value === "object" && value !== null && STREAM_CHANNEL_BRAND2 in value && value[STREAM_CHANNEL_BRAND2] === true; - } - push(item) { - this.#items.push(item); - this.#wake(); - this.#onPush?.(item); - } - iterate(startAt = 0) { - let cursor = startAt; - return { next: async () => { +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/error.js +var isError4 = (error90) => { + if ("isError" in Error && typeof Error.isError === "function") + return Error.isError(error90); + const stringTag = Object.prototype.toString.call(error90); + return stringTag === "[object Error]" || stringTag === "[object DOMException]" || stringTag === "[object DOMError]" || stringTag === "[object Exception]"; +}, getCauseError = (error90) => { + const { cause } = error90; + if (typeof cause !== "object" || cause == null) + return null; + if (!isError4(cause)) + return null; + return cause; +}, isNetworkError4 = (error90) => { + if (!isError4(error90)) + return false; + if (error90.name !== "TypeError" || typeof error90.message !== "string") + return false; + const msg = error90.message.toLowerCase(); + const causeMsg = getCauseError(error90)?.message?.toLowerCase() ?? ""; + return msg.includes("fetch") || msg.includes("network") || msg.includes("connection") || msg.includes("error sending request") || msg.includes("load failed") || msg.includes("terminated") || causeMsg.includes("other side closed") || causeMsg.includes("socket"); +}; +var init_error3 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/utils/stream.js +async function* streamWithRetry(makeRequest, options = {}) { + const maxRetries = options.maxRetries ?? 5; + let attempt = 0; + let lastEventId; + let reconnectPath; + while (true) { + let shouldRetry = false; + let lastError; + let reader; + try { + if (options.signal?.aborted) + return; + const { response, stream: stream2 } = await makeRequest(reconnectPath ? { + lastEventId, + reconnectPath + } : undefined); + const locationHeader = response.headers.get("location"); + if (locationHeader) + reconnectPath = locationHeader; + const contentType = response.headers.get("content-type")?.split(";")[0]; + if (contentType && !contentType.includes("text/event-stream")) + throw new Error(`Expected response header Content-Type to contain 'text/event-stream', got '${contentType}'`); + reader = stream2.getReader(); + try { while (true) { - if (cursor < this.#items.length) - return { - value: this.#items[cursor++], - done: false - }; - if (this.#done) { - if (this.#error) - throw this.#error; - return { - value: undefined, - done: true - }; + if (options.signal?.aborted) { + await reader.cancel(); + return; } - await new Promise((resolve2) => this.#waiters.push(resolve2)); + const { done, value } = await reader.read(); + if (done) + break; + if (value.id) + lastEventId = value.id; + yield value; } - } }; - } - toAsyncIterable(startAt = 0) { - return { [Symbol.asyncIterator]: () => this.iterate(startAt) }; - } - toEventStream(options = {}) { - const encoder2 = new TextEncoder; - const iterator = this.iterate(options.startAt); - const event = options.event ?? this.channelName; - const serialize2 = options.serialize ?? ((item) => JSON.stringify(item) ?? "null"); - return new ReadableStream({ - async pull(controller) { + break; + } catch (error90) { + if (reconnectPath && !options.signal?.aborted) + shouldRetry = true; + else + throw error90; + } finally { + if (reader) try { - const next = await iterator.next(); - if (next.done) { - controller.close(); - return; - } - const lines = []; - if (event != null) - lines.push(`event: ${event}`); - for (const line of serialize2(next.value).split(/\r\n|\r|\n/)) - lines.push(`data: ${line}`); - controller.enqueue(encoder2.encode(`${lines.join(` -`)} - -`)); - } catch (error52) { - controller.error(error52); - } - }, - async cancel() { - await iterator.return?.(); - } + reader.releaseLock(); + } catch {} + } + } catch (error90) { + lastError = error90; + if (isNetworkError4(error90) && reconnectPath && !options.signal?.aborted) + shouldRetry = true; + else + throw error90; + } + if (shouldRetry) { + attempt += 1; + if (attempt > maxRetries) + throw new MaxReconnectAttemptsError(maxRetries, lastError); + options.onReconnect?.({ + attempt, + lastEventId, + cause: lastError + }); + const delay = Math.min(1000 * 2 ** (attempt - 1), 5000) + Math.random() * 1000; + await new Promise((resolve2) => { + setTimeout(resolve2, delay); }); + continue; } - get(index2) { - if (index2 < 0 || index2 >= this.#items.length) - throw new RangeError(`StreamChannel index ${index2} out of bounds (size=${this.#items.length})`); - return this.#items[index2]; + break; + } +} +var MaxReconnectAttemptsError; +var init_stream9 = __esm(() => { + init_error3(); + MaxReconnectAttemptsError = class extends Error { + constructor(maxAttempts, cause) { + super(`Exceeded maximum SSE reconnection attempts (${maxAttempts})`); + this.name = "MaxReconnectAttemptsError"; + this.cause = cause; } - get size() { - return this.#items.length; + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/base.js +function* iterateHeaders(headers) { + let iter; + let shouldClear = false; + if (headers instanceof Headers) { + const entries = []; + headers.forEach((value, name) => { + entries.push([name, value]); + }); + iter = entries; + } else if (Array.isArray(headers)) + iter = headers; + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (const item of iter) { + const name = item[0]; + if (typeof name !== "string") + throw new TypeError(`Expected header name to be a string, got ${typeof name}`); + const values = Array.isArray(item[1]) ? item[1] : [item[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; } - get done() { - return this.#done; + } +} +function mergeHeaders(...headerObjects) { + const outputHeaders = new Headers; + for (const headers of headerObjects) { + if (!headers) + continue; + for (const [name, value] of iterateHeaders(headers)) + if (value === null) + outputHeaders.delete(name); + else + outputHeaders.append(name, value); + } + const headerEntries = []; + outputHeaders.forEach((value, name) => { + headerEntries.push([name, value]); + }); + return Object.fromEntries(headerEntries); +} +function getApiKey(apiKey) { + if (apiKey === null) + return; + if (apiKey) + return apiKey; + for (const prefix of [ + "LANGGRAPH", + "LANGSMITH", + "LANGCHAIN" + ]) { + const envKey = getEnvironmentVariable3(`${prefix}_API_KEY`); + if (envKey) + return envKey.trim().replace(/^["']|["']$/g, ""); + } +} +function getRunMetadataFromResponse(response) { + const contentLocation = response.headers.get("Content-Location"); + if (!contentLocation) + return; + const match2 = REGEX_RUN_METADATA.exec(contentLocation); + if (!match2?.groups?.run_id) + return; + return { + run_id: match2.groups.run_id, + thread_id: match2.groups.thread_id || undefined + }; +} +var BaseClient = class { + asyncCaller; + timeoutMs; + apiUrl; + defaultHeaders; + onRequest; + streamProtocol; + constructor(config3) { + const callerOptions = { + maxRetries: 4, + maxConcurrency: 4, + ...config3?.callerOptions + }; + let defaultApiUrl = "http://localhost:8123"; + if (!config3?.apiUrl && typeof globalThis === "object" && globalThis != null) { + const fetchSmb = Symbol.for("langgraph_api:fetch"); + const urlSmb = Symbol.for("langgraph_api:url"); + const global2 = globalThis; + if (global2[fetchSmb]) + callerOptions.fetch ??= global2[fetchSmb]; + if (global2[urlSmb]) + defaultApiUrl = global2[urlSmb]; } - close() { - this.#done = true; - this.#wake(); + this.asyncCaller = new AsyncCaller3(callerOptions); + this.timeoutMs = config3?.timeoutMs; + this.apiUrl = config3?.apiUrl?.replace(/\/$/, "") || defaultApiUrl; + this.defaultHeaders = config3?.defaultHeaders || {}; + this.onRequest = config3?.onRequest; + this.streamProtocol = config3?.streamProtocol ?? "legacy"; + const apiKey = getApiKey(config3?.apiKey); + if (apiKey) + this.defaultHeaders["x-api-key"] = apiKey; + } + prepareFetchOptions(path2, options) { + const mutatedOptions = { + ...options, + headers: mergeHeaders(this.defaultHeaders, options?.headers) + }; + if (mutatedOptions.json) { + mutatedOptions.body = JSON.stringify(mutatedOptions.json); + mutatedOptions.headers = mergeHeaders(mutatedOptions.headers, { "content-type": "application/json" }); + delete mutatedOptions.json; } - fail(err) { - this.#error = err; - this.#done = true; - this.#wake(); + if (mutatedOptions.withResponse) + delete mutatedOptions.withResponse; + let timeoutSignal = null; + if (typeof options?.timeoutMs !== "undefined") { + if (options.timeoutMs != null) + timeoutSignal = AbortSignal.timeout(options.timeoutMs); + } else if (this.timeoutMs != null) + timeoutSignal = AbortSignal.timeout(this.timeoutMs); + mutatedOptions.signal = mergeSignals(timeoutSignal, mutatedOptions.signal); + const targetUrl = new URL(`${this.apiUrl}${path2}`); + if (mutatedOptions.params) { + for (const [key, value] of Object.entries(mutatedOptions.params)) { + if (value == null) + continue; + const strValue = typeof value === "string" || typeof value === "number" ? value.toString() : JSON.stringify(value); + targetUrl.searchParams.append(key, strValue); + } + delete mutatedOptions.params; } - _wire(fn) { - this.#onPush = fn; + return [targetUrl, mutatedOptions]; + } + async fetch(path2, options) { + const [url3, init] = this.prepareFetchOptions(path2, options); + let finalInit = init; + if (this.onRequest) + finalInit = await this.onRequest(url3, init); + const response = await this.asyncCaller.fetch(url3.toString(), finalInit); + const body = (() => { + if (response.status === 202 || response.status === 204) + return; + return response.json(); + })(); + if (options?.withResponse) + return [await body, response]; + return body; + } + async* streamWithRetry(config3) { + const makeRequest = async (reconnectParams) => { + const requestEndpoint = reconnectParams?.reconnectPath || config3.endpoint; + const isReconnect = !!reconnectParams?.reconnectPath; + const method = isReconnect ? "GET" : config3.method || "GET"; + const requestHeaders = isReconnect && reconnectParams?.lastEventId ? { + ...config3.headers, + "Last-Event-ID": reconnectParams.lastEventId + } : config3.headers; + let [url3, init] = this.prepareFetchOptions(requestEndpoint, { + method, + timeoutMs: null, + signal: config3.signal, + headers: requestHeaders, + params: config3.params, + json: isReconnect ? undefined : config3.json + }); + if (this.onRequest != null) + init = await this.onRequest(url3, init); + const response = await this.asyncCaller.fetch(url3.toString(), init); + if (!response.body) + throw new Error("Expected response body from stream endpoint"); + if (!isReconnect && config3.onInitialResponse) + await config3.onInitialResponse(response); + return { + response, + stream: response.body.pipeThrough(BytesLineDecoder()).pipeThrough(SSEDecoder()) + }; + }; + yield* streamWithRetry(makeRequest, { + maxRetries: config3.maxRetries ?? 5, + signal: config3.signal, + onReconnect: config3.onReconnect + }); + } +}, REGEX_RUN_METADATA; +var init_base17 = __esm(() => { + init_async_caller3(); + init_env4(); + init_signals(); + init_sse(); + init_stream9(); + REGEX_RUN_METADATA = /(\/threads\/(?.+))?\/runs\/(?.+)/; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/multi-cursor-buffer.js +var MultiCursorBuffer; +var init_multi_cursor_buffer = __esm(() => { + MultiCursorBuffer = class { + #items = []; + #wakeups = /* @__PURE__ */ new Set; + #closed = false; + push(item) { + this.#items.push(item); + for (const cb of this.#wakeups) + cb(); + this.#wakeups.clear(); } - _close() { - this.close(); + close() { + this.#closed = true; + for (const cb of this.#wakeups) + cb(); + this.#wakeups.clear(); } - _fail(err) { - this.fail(err); + get length() { + return this.#items.length; } [Symbol.asyncIterator]() { - return this.iterate(); - } - #wake() { - const waiters = this.#waiters.splice(0); - for (const w of waiters) - w(); + let cursor = 0; + return { + next: async () => { + while (true) { + if (cursor < this.#items.length) + return { + done: false, + value: this.#items[cursor++] + }; + if (this.#closed) + return { + done: true, + value: undefined + }; + await new Promise((resolve2) => { + this.#wakeups.add(resolve2); + }); + } + }, + return: async () => ({ + done: true, + value: undefined + }) + }; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/convert.js -function unwrapMessagesPayload2(payload) { - if (!Array.isArray(payload) || payload.length !== 2) - return { data: payload }; - const [data, metadata] = payload; - if (metadata == null || typeof metadata !== "object") - return { data: payload }; - const record2 = metadata; - const node = typeof record2.langgraph_node === "string" ? record2.langgraph_node : undefined; - const runId = typeof record2.run_id === "string" ? record2.run_id : undefined; - return { - data: runId != null && data != null && typeof data === "object" ? { - ...data, - run_id: runId - } : data, - node - }; -} -function convertToProtocolEvent2({ namespace: ns3, mode, payload, seq, meta: meta3 }) { - const timestamp = Date.now(); - const base = { type: "event" }; - switch (mode) { - case "messages": { - const { data, node } = unwrapMessagesPayload2(payload); - return [{ - ...base, - seq, - method: "messages", - params: { - namespace: ns3, - timestamp, - ...node ? { node } : {}, - data - } - }]; - } - case "tools": - return [{ - ...base, - seq, - method: "tools", - params: { - namespace: ns3, - timestamp, - data: convertToolsPayload2(payload) - } - }]; - case "values": { - const events = []; - if (meta3?.checkpoint != null) - events.push({ - ...base, - seq, - method: "checkpoints", - params: { - namespace: ns3, - timestamp, - data: meta3.checkpoint - } - }); - events.push({ - ...base, - seq: meta3?.checkpoint != null ? seq + 1 : seq, - method: "values", - params: { - namespace: ns3, - timestamp, - data: payload - } - }); - return events; - } - case "updates": { - const data = convertUpdatesPayload2(payload); - return [{ - ...base, - seq, - method: "updates", - params: { - namespace: ns3, - timestamp, - ...typeof data.node === "string" ? { node: data.node } : {}, - data - } - }]; - } - case "custom": { - const data = typeof payload === "object" && payload !== null && !Array.isArray(payload) && "name" in payload ? payload : { payload }; - return [{ - ...base, - seq, - method: "custom", - params: { - namespace: ns3, - timestamp, - data - } - }]; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/messages.js +function applyCoreContentDelta(target, delta) { + if (target.type !== delta.type) + return structuredClone(delta); + switch (delta.type) { + case "text": + return { + ...target, + ...delta, + text: `${"text" in target ? target.text : ""}${delta.text}` + }; + case "reasoning": + return { + ...target, + ...delta, + reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` + }; + case "tool_call_chunk": + case "server_tool_call_chunk": { + const merged = { + ...target, + ...delta + }; + if (delta.id == null && "id" in target && target.id != null) + merged.id = target.id; + if (delta.name == null && "name" in target && target.name != null) + merged.name = target.name; + merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; + return merged; } - case "tasks": - return [{ - ...base, - seq, - method: "tasks", - params: { - namespace: ns3, - timestamp, - data: payload - } - }]; default: - return []; - } -} -function convertToolsPayload2(payload) { - if (typeof payload !== "object" || payload === null) - return { - event: "tool-error", - tool_call_id: "", - message: "Unexpected tools payload shape" - }; - const p = payload; - const tool_call_id = String(p.toolCallId ?? ""); - switch (p.event) { - case "on_tool_start": return { - event: "tool-started", - tool_call_id, - tool_name: String(p.name ?? "unknown"), - input: p.input + ...target, + ...delta }; - case "on_tool_event": + } +} +function coreContentBlockFromDelta(delta, current) { + switch (delta.type) { + case "text-delta": return { - event: "tool-output-delta", - tool_call_id, - delta: typeof p.data === "string" ? p.data : JSON.stringify(p.data ?? "") + type: "text", + text: delta.text }; - case "on_tool_end": + case "reasoning-delta": return { - event: "tool-finished", - tool_call_id, - output: p.output + type: "reasoning", + reasoning: delta.reasoning }; - case "on_tool_error": { - const err = p.error; - return { - event: "tool-error", - tool_call_id, - message: typeof err === "object" && err !== null && "message" in err && typeof err.message === "string" ? err.message : String(err ?? "unknown error") + case "data-delta": { + const merged = { + ...current ?? {}, + data: delta.data }; + if (delta.encoding) + merged.encoding = delta.encoding; + return merged; } - default: + case "block-delta": + return delta.fields; + } +} +function applyCoreEventDelta(current, event) { + if (event.content) + return current ? applyCoreContentDelta(current, event.content) : event.content; + switch (event.delta.type) { + case "text-delta": + if (current?.type === "text") + return { + ...current, + text: `${"text" in current ? current.text : ""}${event.delta.text}` + }; + return coreContentBlockFromDelta(event.delta, current); + case "reasoning-delta": + if (current?.type === "reasoning") + return { + ...current, + reasoning: `${"reasoning" in current ? current.reasoning : ""}${event.delta.reasoning}` + }; + return coreContentBlockFromDelta(event.delta, current); + case "data-delta": { + const merged = { ...current ?? {} }; + merged.data = `${merged.data ?? ""}${event.delta.data}`; + if (event.delta.encoding) + merged.encoding = event.delta.encoding; + return merged; + } + case "block-delta": return { - event: "tool-error", - tool_call_id: "", - message: `Unknown tool event: ${String(p.event)}` + ...current ?? {}, + ...event.delta.fields }; } } -function convertUpdatesPayload2(payload) { - if (typeof payload !== "object" || payload === null) - return { values: {} }; - const entries = Object.entries(payload); - if (entries.length === 0) - return { values: {} }; - const [node, values2] = entries[0]; +function normalizeUsage2(usage) { + if (!usage) + return; return { - node, - values: typeof values2 === "object" && values2 !== null ? values2 : { value: values2 } + ...usage, + input_tokens: usage.input_tokens ?? 0, + output_tokens: usage.output_tokens ?? 0, + total_tokens: usage.total_tokens ?? 0 }; } -var STREAM_EVENTS_V3_MODES2; -var init_convert2 = __esm(() => { - STREAM_EVENTS_V3_MODES2 = [ - "values", - "updates", - "messages", - "tools", - "custom", - "tasks" - ]; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/mux.js -function isPromiseLike2(value) { - return value != null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"; -} -async function pump2(source, mux) { - let seq = 0; - try { - for await (const chunk of source) { - const [ns3, mode, payload, meta3] = chunk; - if (mode === "values" && isInterrupted2(payload)) { - const interrupts = payload[INTERRUPT3]; - mux.markInterrupted(interrupts.map((i) => ({ - interruptId: i.id ?? "", - payload: i.value - }))); - } - const events = convertToProtocolEvent2({ - namespace: ns3, - mode, - payload, - seq, - meta: meta3 - }); - seq += events.length; - for (const event of events) - mux.push(ns3, event); +function toStreamingMessageHandle(message) { + return new Proxy(message, { + get(target, prop) { + if (prop === "then") + return; + const value = Reflect.get(target, prop, target); + return typeof value === "function" ? value.bind(target) : value; + }, + has(target, prop) { + if (prop === "then") + return false; + return prop in target; } - } catch (err) { - mux.fail(err); - return; - } - mux.close(); + }); } -function nsKey2(ns3) { - return ns3.join("\x00"); +function cloneBlock(block) { + return structuredClone(block); } -function hasPrefix3(ns3, prefix) { - if (prefix.length > ns3.length) - return false; - for (let i = 0;i < prefix.length; i += 1) - if (ns3[i] !== prefix[i]) - return false; - return true; +function blockFromDelta(delta, current) { + return coreContentBlockFromDelta(delta, current); } -var RESOLVE_VALUES2, REJECT_VALUES2, StreamMux2 = class { - _events = StreamChannel3.local(); - _discoveries = StreamChannel3.local(); - #nextEmitSeq = 0; - #closed = false; - #error; - #interrupted = false; - #currentNamespace = []; - #transformers = []; - #channels = []; - #streamMap = /* @__PURE__ */ new Map; - #latestValues = /* @__PURE__ */ new Map; - #interrupts = []; - #finalValues = []; - register(path4, stream2) { - this.#streamMap.set(nsKey2(path4), stream2); - } - addTransformer(transformer) { - const snapshot = this._events.size; - this.#transformers.push(transformer); - if (transformer.onRegister) - transformer.onRegister({ push: (ns3, event) => this.push(ns3, event) }); - for (let i = 0;i < snapshot; i += 1) - transformer.process(this._events.get(i)); - if (this.#closed) - if (this.#error !== undefined) - transformer.fail?.(this.#error); - else - transformer.finalize?.(); - } - wireChannels(projection) { - for (const [key, value] of Object.entries(projection)) { - if (isStreamChannel2(value)) { - this.#channels.push(value); - if (typeof value.channelName !== "string") - continue; - value._wire((item) => { - this._events.push({ - type: "event", - seq: this.#nextEmitSeq++, - method: value.channelName, - params: { - namespace: this.#currentNamespace, - timestamp: Date.now(), - data: item - } - }); - }); - continue; - } - if (isPromiseLike2(value)) - this.#finalValues.push({ - name: key, - promise: Promise.resolve(value) - }); - } - } - push(ns3, event) { - if (event.method === "values") - this.#latestValues.set(nsKey2(ns3), event.params.data); - const outerNamespace = this.#currentNamespace; - this.#currentNamespace = ns3; - let keep = true; - for (const transformer of this.#transformers) - if (!transformer.process(event)) - keep = false; - this.#currentNamespace = outerNamespace; - if (keep) - this._events.push({ - ...event, - seq: this.#nextEmitSeq++ - }); - } - close() { - this.#closed = true; - for (const [key, values2] of this.#latestValues.entries()) { - const ns3 = key ? key.split("\x00") : []; - this.#streamMap.get(nsKey2(ns3))?.[RESOLVE_VALUES2](values2); - } - const finalizePromises = []; - for (const transformer of this.#transformers) { - const result = transformer.finalize?.(); - if (result != null && typeof result.then === "function") - finalizePromises.push(result); +function applyContentDelta(target, delta) { + if (target.type !== delta.type) + return cloneBlock(delta); + switch (delta.type) { + case "text": + return { + ...target, + ...delta, + text: `${"text" in target ? target.text : ""}${delta.text}` + }; + case "reasoning": + return { + ...target, + ...delta, + reasoning: `${"reasoning" in target ? target.reasoning : ""}${delta.reasoning}` + }; + case "tool_call_chunk": + case "server_tool_call_chunk": { + const merged = { + ...target, + ...delta + }; + if (delta.id == null && "id" in target && target.id != null) + merged.id = target.id; + if (delta.name == null && "name" in target && target.name != null) + merged.name = target.name; + merged.args = `${("args" in target ? target.args : "") ?? ""}${delta.args ?? ""}`; + return merged; } - for (const channel of this.#channels) - channel._close(); - const finalValues = this.#finalValues; - if (finalValues.length === 0 && finalizePromises.length === 0) { - this._events.close(); - this._discoveries.close(); - } else - Promise.allSettled([...finalizePromises, ...finalValues.map(async ({ name, promise: promise2 }) => { - try { - const resolved = await promise2; - if (!this._events.done) - this._events.push({ - type: "event", - seq: this.#nextEmitSeq++, - method: "custom", - params: { - namespace: [], - timestamp: Date.now(), - data: { - name, - payload: resolved - } - } - }); - } catch {} - })]).then(() => { - this._events.close(); - this._discoveries.close(); - }); - for (const stream2 of this.#streamMap.values()) - stream2[RESOLVE_VALUES2](undefined); - } - fail(err) { - this.#closed = true; - this.#error = err; - for (const transformer of this.#transformers) - transformer.fail?.(err); - for (const channel of this.#channels) - channel._fail(err); - this._events.fail(err); - this._discoveries.fail(err); - for (const stream2 of this.#streamMap.values()) - stream2[REJECT_VALUES2](err); - } - markInterrupted(interrupts) { - this.#interrupted = true; - this.#interrupts.push(...interrupts); - } - get interrupted() { - return this.#interrupted; - } - get interrupts() { - return this.#interrupts; - } - subscribeEvents(path4, startAt = 0) { - const base = this._events.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return result; - if (hasPrefix3(result.value.params.namespace, path4)) - return result; - } - } }; + default: + return { + ...target, + ...delta + }; } -}; -var init_mux2 = __esm(() => { - init_constants8(); - init_stream_channel2(); - init_convert2(); - RESOLVE_VALUES2 = Symbol("resolveValues"); - REJECT_VALUES2 = Symbol("rejectValues"); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/transformers/lifecycle.js -function filterLifecycleEntries2(log2, path4, startAt = 0) { - return { [Symbol.asyncIterator]() { - const base = log2.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - if (hasPrefix3(result.value.namespace, path4)) - return { - value: result.value, - done: false - }; - } - } }; - } }; -} -function defaultGuessGraphName2(ns3) { - if (ns3.length === 0) - return DEFAULT_ROOT_GRAPH_NAME2; - const last = ns3[ns3.length - 1]; - const colon = last.indexOf(":"); - return colon === -1 ? last : last.slice(0, colon); } -function defaultSerializeError2(err) { - if (err instanceof Error) - return err.message; - if (typeof err === "string") - return err; - try { - return JSON.stringify(err); - } catch { - return String(err); - } +function messageKeyFor(event) { + const { namespace, node, data } = event.params; + const namespaceKey = namespace.join("/"); + const messageId = data.event === "message-start" ? data.id ?? "" : ""; + return `${namespaceKey}::${node ?? ""}::${messageId}`; } -function isRecord3(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); +function toChatModelStreamEvent(event) { + return event.params.data; } -function extractCause2(data) { - if (!isRecord3(data)) - return; - if (data.event !== "started") - return; - const cause = data.cause; - if (!isRecord3(cause)) - return; - if (typeof cause.type !== "string") - return; - return cause; +function blockIndexKey(activeKey, protocolIndex, blockType) { + return `${activeKey}::${protocolIndex}::${blockType}`; } -function extractTaskResultCompletion2(data) { - if (!isRecord3(data)) - return; - if (!("result" in data)) - return; - if (typeof data.name !== "string") - return; - if (typeof data.id !== "string") - return; - if (data.name.startsWith("__")) - return; - return { - name: data.name, - id: data.id - }; +function areCompatibleBlockTypes(currentType, nextType) { + const toolCallTypes = new Set([ + "tool_call", + "tool_call_chunk", + "tool_use", + "input_json_delta" + ]); + const serverToolCallTypes = new Set(["server_tool_call", "server_tool_call_chunk"]); + return toolCallTypes.has(currentType) && toolCallTypes.has(nextType) || serverToolCallTypes.has(currentType) && serverToolCallTypes.has(nextType); } -function createLifecycleTransformer2(options = {}) { - const rootGraphName = options.rootGraphName ?? DEFAULT_ROOT_GRAPH_NAME2; - const initialStatus = options.initialStatus ?? "running"; - const emitRootOnRegister = options.emitRootOnRegister ?? true; - const getGraphName = options.getGraphName ?? defaultGuessGraphName2; - const serializeError = options.serializeError ?? defaultSerializeError2; - const getTerminalStatusOverride = options.getTerminalStatusOverride; - const log2 = StreamChannel3.local(); - const namespaces = /* @__PURE__ */ new Map; - const namespaceCause = /* @__PURE__ */ new Map; - const pendingInterruptIds = /* @__PURE__ */ new Set; - const pendingCompletions = []; - let emitter; - let inSelfEmit = 0; - let finalized = false; - const resolveGraphName = (ns3) => ns3.length === 0 ? rootGraphName : getGraphName(ns3); - const emit = (ns3, status, extras) => { - const key = nsKey2(ns3); - let current = namespaces.get(key); - const graphName = current?.graphName ?? resolveGraphName(ns3); - if (current != null && current.status === status && current.graphName === graphName && extras?.error == null) - return; - if (current == null) { - current = { - namespace: ns3, - graphName, - status +var PUSH_TEXT, PUSH_REASONING, PUSH_EVENT, UPDATE_CONTEXT, FINISH, ERROR5, StreamingMessage, MessageAssembler = class { + activeMessages = /* @__PURE__ */ new Map; + activeByNamespaceNode = /* @__PURE__ */ new Map; + blockIndexByProtocolIndexAndType = /* @__PURE__ */ new Map; + consume(event) { + const data = event.params.data; + const namespaceNodeKey = `${event.params.namespace.join("/")}::${event.params.node ?? ""}`; + if (data.event === "message-start") { + const key = messageKeyFor(event); + this.activeByNamespaceNode.set(namespaceNodeKey, key); + const message2 = { + id: data.id, + namespace: [...event.params.namespace], + node: event.params.node, + metadata: data.metadata, + blocks: [] }; - namespaces.set(key, current); - } else - current.status = status; - const data = { - event: status, - graph_name: graphName, - ...extras?.cause != null ? { cause: extras.cause } : {}, - ...extras?.error != null ? { error: extras.error } : {} - }; - const timestamp = Date.now(); - log2.push({ - namespace: ns3, - timestamp, - ...data - }); - if (ns3.length === 0 && !emitRootOnRegister) - return; - if (emitter == null) - return; - inSelfEmit += 1; - try { - emitter.push(ns3, { - type: "event", - seq: 0, - method: "lifecycle", - params: { - namespace: ns3, - timestamp, - data - } - }); - } finally { - inSelfEmit -= 1; - } - }; - const trackNamespace = (ns3) => { - const key = nsKey2(ns3); - let rec = namespaces.get(key); - if (rec == null) { - rec = { - namespace: ns3, - graphName: resolveGraphName(ns3), - status: undefined + this.activeMessages.set(key, message2); + return { + kind: "message-start", + key, + message: message2, + event }; - namespaces.set(key, rec); - } - return rec; - }; - const flushPendingCompletions = () => { - if (pendingCompletions.length === 0) - return; - const toFlush = pendingCompletions.splice(0, pendingCompletions.length); - for (const completion of toFlush) { - const key = nsKey2(completion.namespace); - const rec = namespaces.get(key); - if (rec == null || rec.status !== "started") - continue; - emit(completion.namespace, "completed"); - } - }; - const enqueueCompletion = (completion) => { - const key = nsKey2(completion.namespace); - const rec = namespaces.get(key); - if (rec == null || rec.status !== "started") - return; - if (pendingCompletions.some((pending) => nsKey2(pending.namespace) === key)) - return; - pendingCompletions.push(completion); - }; - const removePendingNodeCompletions = (parent, node) => { - for (let index2 = pendingCompletions.length - 1;index2 >= 0; index2 -= 1) { - const pending = pendingCompletions[index2]; - if (pending.source.type !== "node") - continue; - if (pending.source.node !== node) - continue; - if (nsKey2(pending.source.parent) !== nsKey2(parent)) - continue; - pendingCompletions.splice(index2, 1); - } - }; - const ensureStarted = (ns3) => { - for (let length = 1;length <= ns3.length; length += 1) { - const prefix = ns3.slice(0, length); - const key = nsKey2(prefix); - if (namespaces.has(key)) - continue; - trackNamespace(prefix); - const cause = namespaceCause.get(key); - emit(prefix, "started", cause != null ? { cause } : undefined); - } - }; - const defaultTerminalStatus = () => pendingInterruptIds.size > 0 ? "interrupted" : "completed"; - const cascadeTerminalStatus = (status) => { - for (const rec of namespaces.values()) { - if (rec.namespace.length === 0) - continue; - if (rec.status !== "started") - continue; - emit(rec.namespace, status); - } - emit([], status); - log2.close(); - }; - const resolveTerminalStatusOverride = async () => { - if (getTerminalStatusOverride == null) - return defaultTerminalStatus(); - try { - return await getTerminalStatusOverride() ?? defaultTerminalStatus(); - } catch { - return defaultTerminalStatus(); } - }; - const findStartedChildForNode = (parentNamespace, node) => { - const prefix = `${node}:`; - for (const rec of namespaces.values()) { - if (rec.namespace.length !== parentNamespace.length + 1) - continue; - if (rec.status !== "started") - continue; - if (!hasPrefix3(rec.namespace, parentNamespace)) - continue; - const last = rec.namespace[rec.namespace.length - 1]; - if (last === node || last.startsWith(prefix)) - return rec.namespace; + const activeKey = this.activeByNamespaceNode.get(namespaceNodeKey); + if (!activeKey) { + const syntheticKey = `${namespaceNodeKey}::`; + this.activeByNamespaceNode.set(namespaceNodeKey, syntheticKey); + const synthetic = { + id: data.id, + namespace: [...event.params.namespace], + node: event.params.node, + blocks: [] + }; + this.activeMessages.set(syntheticKey, synthetic); + return this.consume(event); } - }; - const findStartedChildForTask = (parentNamespace, task2) => { - const namespace = [...parentNamespace, `${task2.name}:${task2.id}`]; - return namespaces.get(nsKey2(namespace))?.status === "started" ? namespace : undefined; - }; - return { - __native: true, - init() { + const message = this.activeMessages.get(activeKey); + if (!message) + throw new Error(`No active message state found for key ${activeKey}`); + if (data.event === "usage") { + message.usage = data.usage; return { - _lifecycleLog: log2, - lifecycle: filterLifecycleEntries2(log2, [], 0) + kind: "usage", + key: activeKey, + message, + event }; - }, - onRegister(handle) { - emitter = handle; - trackNamespace([]); - if (emitRootOnRegister) - emit([], initialStatus); - }, - process(event) { - const ns3 = event.params.namespace; - if (inSelfEmit > 0) - return true; - const taskCompletion = event.method === "tasks" ? extractTaskResultCompletion2(event.params.data) : undefined; - if (taskCompletion != null) - removePendingNodeCompletions(ns3, taskCompletion.name); - flushPendingCompletions(); - if (event.method === "lifecycle") { - const cause = extractCause2(event.params.data); - if (cause != null) - namespaceCause.set(nsKey2(ns3), cause); - ensureStarted(ns3); - return false; + } + switch (data.event) { + case "content-block-start": + message.blocks[data.index] = cloneBlock(data.content); + this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, data.index, data.content.type), data.index); + return { + kind: "content-block-start", + key: activeKey, + message, + index: data.index, + block: data.content, + event + }; + case "content-block-delta": { + const deltaEvent = data; + const deltaBlock = deltaEvent.content ?? (deltaEvent.delta != null ? blockFromDelta(deltaEvent.delta, message.blocks[data.index]) : undefined); + if (deltaBlock == null) + throw new Error("Received content-block-delta without content"); + const targetIndex = this.resolveBlockIndex(activeKey, message.blocks, data.index, deltaBlock.type); + const current = message.blocks[targetIndex]; + message.blocks[targetIndex] = deltaEvent.content != null ? current == null ? cloneBlock(deltaEvent.content) : applyContentDelta(current, deltaEvent.content) : applyCoreEventDelta(current, data); + return { + kind: "content-block-delta", + key: activeKey, + message, + index: targetIndex, + block: deltaBlock, + event + }; } - ensureStarted(ns3); - if (event.method === "input" && isRecord3(event.params.data) && event.params.data.event === "requested") { - const id = event.params.data.id; - if (typeof id === "string") - pendingInterruptIds.add(id); + case "content-block-finish": { + const targetIndex = this.resolveFinishBlockIndex(activeKey, data.index, data.content.type); + message.blocks[targetIndex] = cloneBlock(data.content); + return { + kind: "content-block-finish", + key: activeKey, + message, + index: targetIndex, + block: data.content, + event + }; } - if (taskCompletion != null) { - const childNamespace = findStartedChildForTask(ns3, taskCompletion); - if (childNamespace != null) - enqueueCompletion({ - namespace: childNamespace, - source: { type: "task" } - }); + case "message-finish": + message.usage = data.usage; + message.finishMetadata = data.responseMetadata; + this.activeMessages.delete(activeKey); + this.activeByNamespaceNode.delete(namespaceNodeKey); + this.clearBlockIndexAliases(activeKey); + return { + kind: "message-finish", + key: activeKey, + message: structuredClone(message), + event + }; + case "error": + message.error = { + message: data.message, + code: data.code + }; + this.activeMessages.delete(activeKey); + this.activeByNamespaceNode.delete(namespaceNodeKey); + this.clearBlockIndexAliases(activeKey); + return { + kind: "message-error", + key: activeKey, + message: structuredClone(message), + event + }; + } + } + resolveBlockIndex(activeKey, blocks2, protocolIndex, blockType) { + const current = blocks2[protocolIndex]; + if (current == null || current.type === blockType || areCompatibleBlockTypes(current.type, blockType)) { + this.blockIndexByProtocolIndexAndType.set(blockIndexKey(activeKey, protocolIndex, blockType), protocolIndex); + return protocolIndex; + } + const key = blockIndexKey(activeKey, protocolIndex, blockType); + const existing = this.blockIndexByProtocolIndexAndType.get(key); + if (existing != null) + return existing; + const nextIndex = blocks2.length; + this.blockIndexByProtocolIndexAndType.set(key, nextIndex); + return nextIndex; + } + resolveFinishBlockIndex(activeKey, protocolIndex, blockType) { + const key = blockIndexKey(activeKey, protocolIndex, blockType); + const existing = this.blockIndexByProtocolIndexAndType.get(key); + if (existing != null) + return existing; + this.blockIndexByProtocolIndexAndType.set(key, protocolIndex); + return protocolIndex; + } + clearBlockIndexAliases(activeKey) { + const prefix = `${activeKey}::`; + for (const key of this.blockIndexByProtocolIndexAndType.keys()) + if (key.startsWith(prefix)) + this.blockIndexByProtocolIndexAndType.delete(key); + } +}, StreamingMessageAssembler = class { + #assembler = new MessageAssembler; + #activeStreaming = /* @__PURE__ */ new Map; + consume(event) { + const update = this.#assembler.consume(event); + if (update == null) + return; + switch (update.kind) { + case "message-start": { + const streaming = new StreamingMessage(update.message); + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + this.#activeStreaming.set(update.key, streaming); + return streaming; } - if (event.method === "updates") { - const node = event.params.node; - if (typeof node === "string" && !node.startsWith("__")) { - const childNamespace = findStartedChildForNode(ns3, node); - if (childNamespace != null) - enqueueCompletion({ - namespace: childNamespace, - source: { - type: "node", - parent: ns3, - node - } - }); + case "content-block-start": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); } - } - return true; - }, - finalize() { - if (finalized) - return; - finalized = true; - flushPendingCompletions(); - if (getTerminalStatusOverride == null) { - cascadeTerminalStatus(defaultTerminalStatus()); + if (streaming && update.block.type === "text" && "text" in update.block && update.block.text) + streaming[PUSH_TEXT](update.block.text); + if (streaming && update.block.type === "reasoning" && "reasoning" in update.block && update.block.reasoning) + streaming[PUSH_REASONING](update.block.reasoning); return; } - return resolveTerminalStatusOverride().then(cascadeTerminalStatus).catch((err) => { - log2.fail(err); - }); - }, - fail(err) { - if (finalized) + case "content-block-delta": { + const streaming = this.#activeStreaming.get(update.key); + if (!streaming) + return; + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + if (update.block.type === "text" && "text" in update.block) + streaming[PUSH_TEXT](update.block.text); + if (update.block.type === "reasoning" && "reasoning" in update.block) + streaming[PUSH_REASONING](update.block.reasoning); return; - finalized = true; - const errorMessage = serializeError(err); - for (const rec of namespaces.values()) { - if (rec.namespace.length === 0) - continue; - if (rec.status !== "started") - continue; - emit(rec.namespace, "failed"); } - emit([], "failed", { error: errorMessage }); - log2.fail(err); - } - }; -} -var DEFAULT_ROOT_GRAPH_NAME2 = "root"; -var init_lifecycle2 = __esm(() => { - init_stream_channel2(); - init_mux2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/transformers/messages.js -function getMessageStreamKey2(data) { - const record2 = data; - if (typeof record2.run_id === "string") - return `run:${record2.run_id}`; - if (data.event === "message-start" && typeof record2.id === "string") - return `message:${record2.id}`; - return "__default__"; -} -function createMessagesTransformer2(path4, nodeFilter) { - const log2 = StreamChannel3.local(); - const active = /* @__PURE__ */ new Map; - return { - init: () => ({ messages: log2.toAsyncIterable() }), - process(event) { - if (event.method !== "messages") - return true; - if (!hasPrefix3(event.params.namespace, path4)) - return true; - if (event.params.namespace.length !== path4.length + 1) - return true; - if (nodeFilter !== undefined && event.params.node !== nodeFilter) - return true; - const data = event.params.data; - switch (data.event) { - case "message-start": { - const key = getMessageStreamKey2(data); - const source = StreamChannel3.local(); - const stream2 = Object.assign(new ChatModelStream(source.toAsyncIterable()), { - namespace: event.params.namespace, - node: event.params.node - }); - active.set(key, { - source, - stream: stream2 - }); - source.push(data); - log2.push(stream2); - break; + case "content-block-finish": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); } - case "content-block-start": - case "content-block-delta": - case "content-block-finish": - active.get(getMessageStreamKey2(data))?.source.push(data); - break; - case "message-finish": { - const key = getMessageStreamKey2(data); - const stream2 = active.get(key); - if (stream2) { - stream2.source.push(data); - stream2.source.close(); - active.delete(key); - } - break; + return; + } + case "usage": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); } - case "error": - active.get(getMessageStreamKey2(data))?.source.push(data); - break; + return; } - return true; - }, - finalize() { - for (const [key, stream2] of active) { - stream2.source.push({ event: "message-finish" }); - stream2.source.close(); - active.delete(key); + case "message-finish": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + streaming[FINISH](); + this.#activeStreaming.delete(update.key); + } + return; } - log2.close(); - }, - fail(err) { - for (const [key, stream2] of active) { - stream2.source.fail(err); - active.delete(key); + case "message-error": { + const streaming = this.#activeStreaming.get(update.key); + if (streaming) { + streaming[UPDATE_CONTEXT](update.event); + streaming[PUSH_EVENT](toChatModelStreamEvent(update.event)); + streaming[ERROR5](); + this.#activeStreaming.delete(update.key); + } + return; } - log2.fail(err); } - }; -} -var init_messages10 = __esm(() => { - init_stream_channel2(); - init_mux2(); - init_stream2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/transformers/subgraphs.js -function filterSubgraphHandles2(log2, path4, startAt = 0) { - const targetDepth = path4.length + 1; - return { [Symbol.asyncIterator]() { - const base = log2.iterate(startAt); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - const { ns: ns3, stream: stream2 } = result.value; - if (ns3.length === targetDepth && hasPrefix3(ns3, path4)) - return { - value: stream2, - done: false - }; - } - } }; - } }; -} -function createSubgraphDiscoveryTransformer2(mux, options) { - const { createStream } = options; - const seen = /* @__PURE__ */ new Set; - return { - __native: true, - init() { - return { - _discoveries: mux._discoveries, - subgraphs: filterSubgraphHandles2(mux._discoveries, [], 0) - }; - }, - process(event) { - const ns3 = event.params.namespace; - if (ns3.length === 0) - return true; - const topNs = ns3.slice(0, 1); - const topKey = nsKey2(topNs); - if (seen.has(topKey)) - return true; - seen.add(topKey); - const stream2 = createStream(topNs, mux._discoveries.size, mux._events.size); - mux.register(topNs, stream2); - mux._discoveries.push({ - ns: topNs, - stream: stream2 - }); - return true; - } - }; -} -var init_subgraphs4 = __esm(() => { - init_mux2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/transformers/values.js -function createValuesTransformer2(path4) { - const valuesLog = StreamChannel3.local(); - return { - init: () => ({ _valuesLog: valuesLog }), - process(event) { - if (event.method !== "values") - return true; - if (event.params.namespace.length !== path4.length) - return true; - if (!hasPrefix3(event.params.namespace, path4)) - return true; - valuesLog.push(event.params.data); - return true; - }, - finalize() { - valuesLog.close(); - }, - fail(err) { - valuesLog.fail(err); - } - }; -} -var init_values5 = __esm(() => { - init_stream_channel2(); - init_mux2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/types.js -function isNativeTransformer2(t) { - return "__native" in t && t.__native === true; -} -var init_types12 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/transformers/index.js -var init_transformers4 = __esm(() => { - init_lifecycle2(); - init_messages10(); - init_subgraphs4(); - init_values5(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/run-stream.js -function createGraphRunStream2(source, transformers = [], optionsOrAbortController) { - const { abortController } = optionsOrAbortController instanceof AbortController ? { abortController: optionsOrAbortController } : optionsOrAbortController ?? {}; - const mux = new StreamMux2; - const lifecycleTransformer = createLifecycleTransformer2(); - const lifecycleProjection = lifecycleTransformer.init(); - const lifecycleLog = lifecycleProjection._lifecycleLog; - const subgraphDiscoveryTransformer = createSubgraphDiscoveryTransformer2(mux, { createStream: (path4, discoveryStart, eventStart) => { - const sub = new SubgraphRunStream2(path4, mux, discoveryStart, eventStart); - sub[SET_SUBGRAPHS_ITERABLE2](filterSubgraphHandles2(mux._discoveries, path4, discoveryStart)); - sub[SET_LIFECYCLE_ITERABLE2](filterLifecycleEntries2(lifecycleLog, path4, lifecycleLog.size)); - return sub; - } }); - const subgraphsProjection = subgraphDiscoveryTransformer.init(); - mux.addTransformer(subgraphDiscoveryTransformer); - mux.addTransformer(lifecycleTransformer); - const valuesTransformer = createValuesTransformer2([]); - const messagesTransformer = createMessagesTransformer2([]); - mux.addTransformer(valuesTransformer); - mux.addTransformer(messagesTransformer); - const extensions = {}; - const nativeProjections = []; - for (const factory of transformers) { - const transformer = factory(); - mux.addTransformer(transformer); - const projection = transformer.init(); - if (isNativeTransformer2(transformer)) - nativeProjections.push(projection); - else - Object.assign(extensions, projection); - if (typeof projection === "object" && projection !== null && !isNativeTransformer2(transformer)) - mux.wireChannels(projection); } - const root = new GraphRunStream2([], mux, 0, 0, extensions, abortController); - for (const proj of nativeProjections) - Object.assign(root, proj); - const valuesProjection2 = valuesTransformer.init(); - root[SET_VALUES_LOG2](valuesProjection2._valuesLog); - const messagesProjection2 = messagesTransformer.init(); - root[SET_MESSAGES_ITERABLE2](messagesProjection2.messages); - root[SET_LIFECYCLE_ITERABLE2](lifecycleProjection.lifecycle); - root[SET_SUBGRAPHS_ITERABLE2](subgraphsProjection.subgraphs); - mux.register([], root); - pump2(source, mux).catch((err) => {}); - return root; -} -var SET_VALUES_LOG2, SET_MESSAGES_ITERABLE2, SET_LIFECYCLE_ITERABLE2, SET_SUBGRAPHS_ITERABLE2, EMPTY_ASYNC_ITERABLE2, GraphRunStream2, SubgraphRunStream2; -var init_run_stream2 = __esm(() => { - init_mux2(); - init_lifecycle2(); - init_messages10(); - init_subgraphs4(); - init_values5(); - init_transformers4(); - init_types12(); - SET_VALUES_LOG2 = Symbol("setValuesLog"); - SET_MESSAGES_ITERABLE2 = Symbol("setMessagesIterable"); - SET_LIFECYCLE_ITERABLE2 = Symbol("setLifecycleIterable"); - SET_SUBGRAPHS_ITERABLE2 = Symbol("setSubgraphsIterable"); - EMPTY_ASYNC_ITERABLE2 = { [Symbol.asyncIterator]() { - return { next: () => Promise.resolve({ - value: undefined, - done: true - }) }; - } }; - GraphRunStream2 = class { - path; - extensions; - _mux; - #eventStart; - #discoveryStart; - #abortController; - #resolveValuesFn; - #rejectValuesFn; - #valuesDone; - #valuesLog; - #messagesIterable; - #lifecycleIterable; - #subgraphsIterable; - constructor(path4, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { - this.path = path4; - this._mux = mux; - this.#discoveryStart = discoveryStart; - this.#eventStart = eventStart; - this.extensions = extensions ?? {}; - this.#abortController = abortController ?? new AbortController; - this.#valuesDone = new Promise((resolve2, reject) => { - this.#resolveValuesFn = resolve2; - this.#rejectValuesFn = reject; +}; +var init_messages8 = __esm(() => { + init_multi_cursor_buffer(); + init_messages(); + PUSH_TEXT = Symbol("pushText"); + PUSH_REASONING = Symbol("pushReasoning"); + PUSH_EVENT = Symbol("pushEvent"); + UPDATE_CONTEXT = Symbol("updateContext"); + FINISH = Symbol("finish"); + ERROR5 = Symbol("error"); + StreamingMessage = class { + id; + namespace; + node; + metadata; + assembled; + #events = new MultiCursorBuffer; + #textChunks = []; + #reasoningChunks = []; + #textWaiters = []; + #reasoningWaiters = []; + #textDone = false; + #reasoningDone = false; + #resolveText; + #resolveReasoning; + #textPromise; + #reasoningPromise; + constructor(assembled) { + this.id = assembled.id; + this.assembled = assembled; + this.namespace = assembled.namespace; + this.node = assembled.node; + this.metadata = assembled.metadata; + this.#textPromise = new Promise((r) => { + this.#resolveText = r; + }); + this.#reasoningPromise = new Promise((r) => { + this.#resolveReasoning = r; }); - this.#valuesDone.catch(() => {}); - } - [Symbol.asyncIterator]() { - return this._mux.subscribeEvents(this.path, this.#eventStart); - } - get subgraphs() { - if (this.#subgraphsIterable) - return this.#subgraphsIterable; - return filterSubgraphHandles2(this._mux._discoveries, this.path, this.#discoveryStart); } - get values() { - const log2 = this.#valuesLog; - const done = this.#valuesDone; - const mux = this._mux; - const eventStart = this.#eventStart; - const path4 = this.path; - const iterable = log2 ? log2.toAsyncIterable() : { [Symbol.asyncIterator]: () => { - const base = mux.subscribeEvents(path4, eventStart); - return { async next() { - while (true) { - const result = await base.next(); - if (result.done) - return { - value: undefined, - done: true - }; - if (result.value.method === "values" && result.value.params.namespace.length === path4.length) - return { - value: result.value.params.data, - done: false - }; - } - } }; - } }; + get text() { + const chunks = this.#textChunks; + const waiters = this.#textWaiters; + const getDone = () => this.#textDone; + let cursor = 0; return { - [Symbol.asyncIterator]: () => iterable[Symbol.asyncIterator](), - then: done.then.bind(done) + [Symbol.asyncIterator]() { + return { async next() { + while (true) { + if (cursor < chunks.length) + return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) + return { + done: true, + value: undefined + }; + await new Promise((resolve2) => { + waiters.push(resolve2); + }); + } + } }; + }, + then: this.#textPromise.then.bind(this.#textPromise), + full: { async* [Symbol.asyncIterator]() { + let accumulated = ""; + for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { + while (true) { + if (cursor < chunks.length) + return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) + return { + done: true, + value: undefined + }; + await new Promise((resolve2) => { + waiters.push(resolve2); + }); + } + } }) }) { + accumulated += chunk; + yield accumulated; + } + } } }; } - get messages() { - if (this.#messagesIterable) - return this.#messagesIterable; - const transformer = createMessagesTransformer2(this.path); - const projection = transformer.init(); - this._mux.addTransformer(transformer); - this.#messagesIterable = projection.messages; - return this.#messagesIterable; + get reasoning() { + const chunks = this.#reasoningChunks; + const waiters = this.#reasoningWaiters; + const getDone = () => this.#reasoningDone; + let cursor = 0; + return { + [Symbol.asyncIterator]() { + return { async next() { + while (true) { + if (cursor < chunks.length) + return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) + return { + done: true, + value: undefined + }; + await new Promise((resolve2) => { + waiters.push(resolve2); + }); + } + } }; + }, + then: this.#reasoningPromise.then.bind(this.#reasoningPromise), + full: { async* [Symbol.asyncIterator]() { + let accumulated = ""; + for await (const chunk of { [Symbol.asyncIterator]: () => ({ next: async () => { + while (true) { + if (cursor < chunks.length) + return { + done: false, + value: chunks[cursor++] + }; + if (getDone()) + return { + done: true, + value: undefined + }; + await new Promise((resolve2) => { + waiters.push(resolve2); + }); + } + } }) }) { + accumulated += chunk; + yield accumulated; + } + } } + }; } - get lifecycle() { - return this.#lifecycleIterable ?? EMPTY_ASYNC_ITERABLE2; + get usage() { + const promise3 = (async () => { + let usage; + for await (const snapshot of this.#usageIterator()) + usage = snapshot; + return usage; + })(); + return { + [Symbol.asyncIterator]: () => this.#usageIterator(), + then: promise3.then.bind(promise3) + }; } - messagesFrom(node) { - const transformer = createMessagesTransformer2(this.path, node); - const projection = transformer.init(); - this._mux.addTransformer(transformer); - return projection.messages; + get toolCalls() { + const events = this.#events; + const iterator = async function* () { + for await (const event of events) + if (event.event === "content-block-finish" && event.content.type === "tool_call") + yield event.content; + }; + return { + [Symbol.asyncIterator]: iterator, + then: async (onfulfilled, onrejected) => { + try { + const calls = []; + for await (const call5 of iterator()) + calls.push(call5); + return onfulfilled ? onfulfilled(calls) : calls; + } catch (err) { + if (onrejected) + return onrejected(err); + throw err; + } + }, + full: { async* [Symbol.asyncIterator]() { + const calls = []; + for await (const call5 of iterator()) { + calls.push(call5); + yield [...calls]; + } + } } + }; } get output() { - return this.#valuesDone; + return { then: (onf, onr) => this.#assembleMessage().then(onf, onr) }; } - get interrupted() { - return this._mux.interrupted; + get blocks() { + return this.assembled.blocks; } - get interrupts() { - return this._mux.interrupts; + [Symbol.asyncIterator]() { + return this.#events[Symbol.asyncIterator](); } - abort(reason) { - this.#abortController.abort(reason); + then(onfulfilled, onrejected) { + return this.#assembleMessage().then(onfulfilled, onrejected); } - get signal() { - return this.#abortController.signal; + async* #usageIterator() { + for await (const event of this.#events) + if (event.event === "message-start" && event.usage) + yield normalizeUsage2(event.usage); + else if (event.event === "message-finish" && event.usage) + yield normalizeUsage2(event.usage); } - [RESOLVE_VALUES2](values2) { - this.#resolveValuesFn?.(values2); - this.#resolveValuesFn = undefined; + async#assembleMessage() { + const contentBlocks = []; + let id; + let usage; + let metadata = {}; + let finishReason; + for await (const event of this.#events) + switch (event.event) { + case "message-start": + id = event.id ?? id; + if (event.usage) + usage = normalizeUsage2(event.usage); + break; + case "content-block-start": + contentBlocks[event.index] = event.content; + break; + case "content-block-delta": { + const current = contentBlocks[event.index]; + contentBlocks[event.index] = applyCoreEventDelta(current, event); + break; + } + case "content-block-finish": + contentBlocks[event.index] = event.content; + break; + case "message-finish": + finishReason = event.reason; + if (event.usage) + usage = normalizeUsage2(event.usage); + if (event.responseMetadata) + metadata = { + ...metadata, + ...event.responseMetadata + }; + break; + default: + break; + } + return new AIMessage({ + id, + content: contentBlocks.filter((block) => block != null), + usage_metadata: usage, + response_metadata: { + ...metadata, + ...finishReason ? { finish_reason: finishReason } : {}, + output_version: "v1" + } + }); } - [REJECT_VALUES2](err) { - this.#rejectValuesFn?.(err); - this.#rejectValuesFn = undefined; + [PUSH_EVENT](event) { + this.#events.push(event); } - [SET_VALUES_LOG2](log2) { - this.#valuesLog = log2; + [UPDATE_CONTEXT](event) { + this.node = event.params.node ?? this.node; } - [SET_MESSAGES_ITERABLE2](iterable) { - this.#messagesIterable = iterable; + [PUSH_TEXT](delta) { + this.#textChunks.push(delta); + const pending = this.#textWaiters.splice(0, this.#textWaiters.length); + for (const waiter of pending) + waiter(); } - [SET_LIFECYCLE_ITERABLE2](iterable) { - this.#lifecycleIterable = iterable; + [PUSH_REASONING](delta) { + this.#reasoningChunks.push(delta); + const pending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); + for (const waiter of pending) + waiter(); } - [SET_SUBGRAPHS_ITERABLE2](iterable) { - this.#subgraphsIterable = iterable; + [FINISH]() { + this.#textDone = true; + this.#reasoningDone = true; + this.#resolveText(this.#textChunks.join("")); + this.#resolveReasoning(this.#reasoningChunks.join("")); + const textPending = this.#textWaiters.splice(0, this.#textWaiters.length); + for (const waiter of textPending) + waiter(); + const reasoningPending = this.#reasoningWaiters.splice(0, this.#reasoningWaiters.length); + for (const waiter of reasoningPending) + waiter(); + this.#events.close(); } - }; - SubgraphRunStream2 = class extends GraphRunStream2 { - name; - index; - constructor(path4, mux, discoveryStart = 0, eventStart = 0, extensions, abortController) { - super(path4, mux, discoveryStart, eventStart, extensions, abortController); - const lastSegment = path4[path4.length - 1] ?? ""; - const colonIdx = lastSegment.lastIndexOf(":"); - if (colonIdx >= 0) { - this.name = lastSegment.slice(0, colonIdx); - const suffix = lastSegment.slice(colonIdx + 1); - this.index = /^\d+$/.test(suffix) ? Number(suffix) : 0; - } else { - this.name = lastSegment; - this.index = 0; - } + [ERROR5]() { + this[FINISH](); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/stream/index.js -var init_stream11 = __esm(() => { - init_stream_channel2(); - init_convert2(); - init_mux2(); - init_lifecycle2(); - init_messages10(); - init_subgraphs4(); - init_values5(); - init_transformers4(); - init_types12(); - init_run_stream2(); - init_stream2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/hash.js -function assert4(a) { - if (!a) - throw new Error("Assert failed"); -} -function bswap643(a) { - const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); - scratchbuf.setBigUint64(0, a, true); - return scratchbuf.getBigUint64(0, false); -} -function bswap323(input) { - let a = input; - a = (a & n3(65535)) << n3(16) | (a & n3(4294901760)) >> n3(16); - a = (a & n3(16711935)) << n3(8) | (a & n3(4278255360)) >> n3(8); - return a; -} -function XXH_mult32to643(a, b) { - return (a & mask323) * (b & mask323) & mask643; -} -function rotl323(a, b) { - return (a << b | a >> n3(32) - b) & mask323; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/media.js +function base64ToBytes(b64) { + const binary = atob(b64); + const bytes = new Uint8Array(binary.length); + for (let i = 0;i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return bytes; } -function XXH3_accumulate_5123(acc, dataView, keyView) { - for (let i = 0;i < ACC_NB3; i += 1) { - const data_val = dataView.getBigUint64(i * 8, true); - const data_key = data_val ^ keyView.getBigUint64(i * 8, true); - acc[i ^ 1] += data_val; - acc[i] += XXH_mult32to643(data_key, data_key >> n3(32)); +function concatBytes(parts, totalLength) { + const out = new Uint8Array(totalLength); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.byteLength; } - return acc; -} -function XXH3_accumulate3(acc, dataView, keyView, nbStripes) { - for (let n4 = 0;n4 < nbStripes; n4 += 1) - XXH3_accumulate_5123(acc, view2(dataView, n4 * STRIPE_LEN3), view2(keyView, n4 * 8)); - return acc; + return out; } -function XXH3_scrambleAcc3(acc, key) { - for (let i = 0;i < ACC_NB3; i += 1) { - const key64 = key.getBigUint64(i * 8, true); - let acc64 = acc[i]; - acc64 = xorshift643(acc64, n3(47)); - acc64 ^= key64; - acc64 *= PRIME32_13; - acc[i] = acc64 & mask643; +var MEDIA_BLOCK_TYPES, MediaAssemblyError, MediaHandleImpl = class { + type; + messageId; + namespace; + node; + id; + mimeType; + url; + width; + height; + filename; + monotonic = true; + error; + #parts = []; + #totalBytes = 0; + #partialSnapshot = new Uint8Array(0); + #stream; + #streamController; + #blobResolve; + #blobReject; + #blobPromise; + #transcriptParts = []; + #transcriptResolve; + #transcriptReject; + #transcriptPromise; + #cachedObjectURL; + #urlSourced = false; + #urlFetchPromise; + #lastIndex = -1; + #finished = false; + #settled = false; + #fetchImpl; + constructor(options) { + this.type = options.type; + this.messageId = options.messageId; + this.namespace = options.namespace; + this.node = options.node; + this.id = options.id; + this.mimeType = options.mimeType; + this.url = options.url; + this.#fetchImpl = options.fetch; + this.#blobPromise = new Promise((resolve2, reject) => { + this.#blobResolve = resolve2; + this.#blobReject = reject; + }); + this.#blobPromise.catch(() => { + return; + }); + this.#transcriptPromise = new Promise((resolve2, reject) => { + this.#transcriptResolve = resolve2; + this.#transcriptReject = reject; + }); + this.#transcriptPromise.catch(() => { + return; + }); } - return acc; -} -function XXH3_mix2Accs3(acc, key) { - return XXH3_mul128_fold643(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U643, true)); -} -function XXH3_mergeAccs3(acc, key, start) { - let result64 = start; - result64 += XXH3_mix2Accs3(acc.slice(0), view2(key, 0 * _U323)); - result64 += XXH3_mix2Accs3(acc.slice(2), view2(key, 4 * _U323)); - result64 += XXH3_mix2Accs3(acc.slice(4), view2(key, 8 * _U323)); - result64 += XXH3_mix2Accs3(acc.slice(6), view2(key, 12 * _U323)); - return XXH3_avalanche3(result64 & mask643); -} -function XXH3_hashLong3(input, data, secret, f_acc, f_scramble) { - let acc = input; - const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN3) / 8); - const block_len = STRIPE_LEN3 * nbStripesPerBlock; - const nb_blocks = Math.floor((data.byteLength - 1) / block_len); - for (let n4 = 0;n4 < nb_blocks; n4 += 1) { - acc = XXH3_accumulate3(acc, view2(data, n4 * block_len), secret, nbStripesPerBlock); - acc = f_scramble(acc, view2(secret, secret.byteLength - STRIPE_LEN3)); + observeIndex(index2) { + if (index2 !== this.#lastIndex + 1 && index2 !== this.#lastIndex) + this.monotonic = false; + if (index2 > this.#lastIndex) + this.#lastIndex = index2; } - { - const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN3); - acc = XXH3_accumulate3(acc, view2(data, nb_blocks * block_len), secret, nbStripes); - acc = f_acc(acc, view2(data, data.byteLength - STRIPE_LEN3), view2(secret, secret.byteLength - STRIPE_LEN3 - 7)); + absorbBlock(block) { + if (this.#urlSourced) + return; + if (block.type === "audio") + this.#absorbAudio(block); + else if (block.type === "image") + this.#absorbImage(block); + else if (block.type === "video") + this.#absorbVideo(block); + else if (block.type === "file") + this.#absorbFile(block); } - return acc; -} -function XXH3_hashLong_128b3(data, secret) { - let acc = new BigUint64Array([ - PRIME32_33, - PRIME64_13, - PRIME64_23, - PRIME64_33, - PRIME64_43, - PRIME32_23, - PRIME64_53, - PRIME32_13 - ]); - assert4(data.byteLength > 128); - acc = XXH3_hashLong3(acc, data, secret, XXH3_accumulate_5123, XXH3_scrambleAcc3); - assert4(acc.length * 8 === 64); - { - const low64 = XXH3_mergeAccs3(acc, view2(secret, 11), n3(data.byteLength) * PRIME64_13 & mask643); - return XXH3_mergeAccs3(acc, view2(secret, secret.byteLength - STRIPE_LEN3 - 11), ~(n3(data.byteLength) * PRIME64_23) & mask643) << n3(64) | low64; + enterUrlMode(url3) { + this.#urlSourced = true; + this.url = url3; } -} -function XXH3_mul128_fold643(a, b) { - const lll = a * b & mask1283; - return lll & mask643 ^ lll >> n3(64); -} -function XXH3_mix16B3(dataView, keyView, seed) { - return XXH3_mul128_fold643((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask643, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask643); -} -function XXH3_mix32B3(acc, data1, data2, key, seed) { - let accl = acc & mask643; - let acch = acc >> n3(64) & mask643; - accl += XXH3_mix16B3(data1, key, seed); - accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); - accl &= mask643; - acch += XXH3_mix16B3(data2, view2(key, 16), seed); - acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); - acch &= mask643; - return acch << n3(64) | accl; -} -function XXH3_avalanche3(input) { - let h64 = input; - h64 ^= h64 >> n3(37); - h64 *= PRIME_MX13; - h64 &= mask643; - h64 ^= h64 >> n3(32); - return h64; -} -function XXH3_avalanche643(input) { - let h64 = input; - h64 ^= h64 >> n3(33); - h64 *= PRIME64_23; - h64 &= mask643; - h64 ^= h64 >> n3(29); - h64 *= PRIME64_33; - h64 &= mask643; - h64 ^= h64 >> n3(32); - return h64; -} -function XXH3_len_1to3_128b3(data, key32, seed) { - const len = data.byteLength; - assert4(len > 0 && len <= 3); - const combined = n3(data.getUint8(len - 1)) | n3(len << 8) | n3(data.getUint8(0) << 16) | n3(data.getUint8(len >> 1) << 24); - const low = (combined ^ (n3(key32.getUint32(0, true)) ^ n3(key32.getUint32(4, true))) + seed) & mask643; - const bhigh = (n3(key32.getUint32(8, true)) ^ n3(key32.getUint32(12, true))) - seed; - return (XXH3_avalanche643((rotl323(bswap323(combined), n3(13)) ^ bhigh) & mask643) & mask643) << n3(64) | XXH3_avalanche643(low); -} -function xorshift643(b, shift) { - return b ^ b >> shift; -} -function XXH3_len_4to8_128b3(data, key32, seed) { - const len = data.byteLength; - assert4(len >= 4 && len <= 8); - { - const l1 = data.getUint32(0, true); - const l2 = data.getUint32(len - 4, true); - let m128 = ((n3(l1) | n3(l2) << n3(32)) ^ (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask643) * (PRIME64_13 + (n3(len) << n3(2))) & mask1283; - m128 += (m128 & mask643) << n3(65); - m128 &= mask1283; - m128 ^= m128 >> n3(67); - return xorshift643(xorshift643(m128 & mask643, n3(35)) * PRIME_MX23 & mask643, n3(28)) | XXH3_avalanche3(m128 >> n3(64)) << n3(64); + pushBytes(bytes) { + if (this.#finished || this.#settled) + return; + if (bytes.byteLength === 0) + return; + this.#parts.push(bytes); + this.#totalBytes += bytes.byteLength; + this.#partialSnapshot = concatBytes(this.#parts, this.#totalBytes); + if (this.#streamController != null) + try { + this.#streamController.enqueue(bytes); + } catch {} } -} -function XXH3_len_9to16_128b3(data, key64, seed) { - const len = data.byteLength; - assert4(len >= 9 && len <= 16); - { - const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask643; - const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask643; - const ll1 = data.getBigUint64(0, true); - let ll2 = data.getBigUint64(len - 8, true); - let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_13; - const m128_l = (m128 & mask643) + (n3(len - 1) << n3(54)); - m128 = m128 & (mask1283 ^ mask643) | m128_l; - ll2 ^= bitfliph; - m128 += ll2 + (ll2 & mask323) * (PRIME32_23 - n3(1)) << n3(64); - m128 &= mask1283; - m128 ^= bswap643(m128 >> n3(64)); - let h128 = (m128 & mask643) * PRIME64_23; - h128 += (m128 >> n3(64)) * PRIME64_23 << n3(64); - h128 &= mask1283; - return XXH3_avalanche3(h128 & mask643) | XXH3_avalanche3(h128 >> n3(64)) << n3(64); + pushTranscript(fragment) { + if (this.type !== "audio") + return; + if (this.#finished || this.#settled) + return; + if (fragment.length === 0) + return; + this.#transcriptParts.push(fragment); } -} -function XXH3_len_0to16_128b3(data, seed) { - const len = data.byteLength; - assert4(len <= 16); - if (len > 8) - return XXH3_len_9to16_128b3(data, kkey3, seed); - if (len >= 4) - return XXH3_len_4to8_128b3(data, kkey3, seed); - if (len > 0) - return XXH3_len_1to3_128b3(data, kkey3, seed); - return XXH3_avalanche643(seed ^ kkey3.getBigUint64(64, true) ^ kkey3.getBigUint64(72, true)) | XXH3_avalanche643(seed ^ kkey3.getBigUint64(80, true) ^ kkey3.getBigUint64(88, true)) << n3(64); -} -function inv643(x) { - return ~x + n3(1) & mask643; -} -function XXH3_len_17to128_128b3(data, secret, seed) { - let acc = n3(data.byteLength) * PRIME64_13 & mask643; - let i = n3(data.byteLength - 1) / n3(32); - while (i >= 0) { - const ni = Number(i); - acc = XXH3_mix32B3(acc, view2(data, 16 * ni), view2(data, data.byteLength - 16 * (ni + 1)), view2(secret, 32 * ni), seed); - i -= n3(1); + finish() { + if (this.#finished || this.#settled) + return; + this.#finished = true; + this.#settled = true; + const blob = new Blob([this.#partialSnapshot], { type: this.mimeType ?? "" }); + this.#blobResolve(blob); + this.#transcriptResolve(this.#transcriptParts.length === 0 ? undefined : this.#transcriptParts.join("")); + try { + this.#streamController?.close(); + } catch {} } - let h128l = acc + (acc >> n3(64)) & mask643; - h128l = XXH3_avalanche3(h128l); - let h128h = (acc & mask643) * PRIME64_13 + (acc >> n3(64)) * PRIME64_43 + (n3(data.byteLength) - seed & mask643) * PRIME64_23; - h128h &= mask643; - h128h = inv643(XXH3_avalanche3(h128h)); - return h128l | h128h << n3(64); -} -function XXH3_len_129to240_128b3(data, secret, seed) { - let acc = n3(data.byteLength) * PRIME64_13 & mask643; - for (let i = 32;i < 160; i += 32) - acc = XXH3_mix32B3(acc, view2(data, i - 32), view2(data, i - 16), view2(secret, i - 32), seed); - acc = XXH3_avalanche3(acc & mask643) | XXH3_avalanche3(acc >> n3(64)) << n3(64); - for (let i = 160;i <= data.byteLength; i += 32) - acc = XXH3_mix32B3(acc, view2(data, i - 32), view2(data, i - 16), view2(secret, 3 + i - 160), seed); - acc = XXH3_mix32B3(acc, view2(data, data.byteLength - 16), view2(data, data.byteLength - 32), view2(secret, 103), inv643(seed)); - let h128l = acc + (acc >> n3(64)) & mask643; - h128l = XXH3_avalanche3(h128l); - let h128h = (acc & mask643) * PRIME64_13 + (acc >> n3(64)) * PRIME64_43 + (n3(data.byteLength) - seed & mask643) * PRIME64_23; - h128h &= mask643; - h128h = inv643(XXH3_avalanche3(h128h)); - return h128l | h128h << n3(64); -} -function XXH32(input, seed = n3(0)) { - const encoder2 = new TextEncoder; - const data = view2(typeof input === "string" ? encoder2.encode(input) : input); - const len = data.byteLength; - const hexDigest = (data2) => data2.toString(16).padStart(32, "0"); - if (len <= 16) - return hexDigest(XXH3_len_0to16_128b3(data, seed)); - if (len <= 128) - return hexDigest(XXH3_len_17to128_128b3(data, kkey3, seed)); - if (len <= 240) - return hexDigest(XXH3_len_129to240_128b3(data, kkey3, seed)); - return hexDigest(XXH3_hashLong_128b3(data, kkey3)); -} -function isXXH32(value) { - return /^[0-9a-f]{32}$/.test(value); -} -var n3 = (n4) => BigInt(n4), view2 = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset), PRIME32_13, PRIME32_23, PRIME32_33, PRIME64_13, PRIME64_23, PRIME64_33, PRIME64_43, PRIME64_53, PRIME_MX13, PRIME_MX23, hexToUint8Array3 = (hex3) => { - const strLen = hex3.length; - if (strLen % 2 !== 0) - throw new Error("String should have an even number of characters"); - const maxLength = strLen / 2; - const bytes = new Uint8Array(maxLength); - let read = 0; - let write = 0; - while (write < maxLength) { - const slice = hex3.slice(read, read += 2); - bytes[write] = Number.parseInt(slice, 16); - write += 1; + fail(kind, reason, cause) { + if (this.#settled) + return this.error ?? new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); + this.#settled = true; + const err = new MediaAssemblyError(kind, this.messageId, this.#partialSnapshot, reason, { cause }); + this.error = err; + this.#blobReject(err); + this.#transcriptReject(err); + try { + this.#streamController?.error(err); + } catch {} + return err; } - return view2(bytes); -}, kkey3, mask1283, mask643, mask323, STRIPE_LEN3 = 64, ACC_NB3, _U643 = 8, _U323 = 4; -var init_hash4 = __esm(() => { - PRIME32_13 = n3("0x9E3779B1"); - PRIME32_23 = n3("0x85EBCA77"); - PRIME32_33 = n3("0xC2B2AE3D"); - PRIME64_13 = n3("0x9E3779B185EBCA87"); - PRIME64_23 = n3("0xC2B2AE3D27D4EB4F"); - PRIME64_33 = n3("0x165667B19E3779F9"); - PRIME64_43 = n3("0x85EBCA77C2B2AE63"); - PRIME64_53 = n3("0x27D4EB2F165667C5"); - PRIME_MX13 = n3("0x165667919E3779F9"); - PRIME_MX23 = n3("0x9FB21C651E98DF25"); - kkey3 = hexToUint8Array3("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); - mask1283 = (n3(1) << n3(128)) - n3(1); - mask643 = (n3(1) << n3(64)) - n3(1); - mask323 = (n3(1) << n3(32)) - n3(1); - ACC_NB3 = STRIPE_LEN3 / 8; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/interrupt.js -function interrupt2(value) { - const config2 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (!config2) - throw new Error("Called interrupt() outside the context of a graph."); - const conf = config2.configurable; - if (!conf) - throw new Error("No configurable found in config"); - if (!conf["__pregel_checkpointer"]) - throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const scratchpad = conf[CONFIG_KEY_SCRATCHPAD2]; - scratchpad.interruptCounter += 1; - const idx = scratchpad.interruptCounter; - if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { - conf[CONFIG_KEY_SEND2]?.([[RESUME3, scratchpad.resume]]); - return scratchpad.resume[idx]; + get partialBytes() { + return this.#partialSnapshot; } - if (scratchpad.nullResume !== undefined) { - if (scratchpad.resume.length !== idx) - throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); - const v = scratchpad.consumeNullResume(); - scratchpad.resume.push(v); - conf[CONFIG_KEY_SEND2]?.([[RESUME3, scratchpad.resume]]); - return v; + get blob() { + if (this.#urlSourced) + return this.#fetchUrlSourced().then((bytes) => new Blob([bytes], { type: this.mimeType ?? "" })); + return this.#blobPromise; } - const ns3 = conf[CONFIG_KEY_CHECKPOINT_NS2]?.split("|"); - throw new GraphInterrupt2([{ - id: ns3 ? XXH32(ns3.join("|")) : undefined, - value - }]); -} -var init_interrupt2 = __esm(() => { - init_constants8(); - init_errors10(); - init_hash4(); - init_singletons(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/utils.js -function* prefixGenerator2(generator, prefix) { - if (prefix === undefined) - yield* generator; - else - for (const value of generator) - yield [prefix, value]; -} -async function gatherIterator2(i) { - const out = []; - for await (const item of await i) - out.push(item); - return out; -} -function gatherIteratorSync2(i) { - const out = []; - for (const item of i) - out.push(item); - return out; -} -function patchConfigurable3(config2, patch) { - if (!config2) - return { configurable: patch }; - else if (!("configurable" in config2)) - return { - ...config2, - configurable: patch - }; - else - return { - ...config2, - configurable: { - ...config2.configurable, - ...patch - } - }; -} -function isAsyncGeneratorFunction2(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; -} -function isGeneratorFunction2(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; -} -var RunnableCallable3; -var init_utils17 = __esm(() => { - init_config3(); - init_singletons(); - init_runnables(); - RunnableCallable3 = class extends Runnable { - lc_namespace = ["langgraph"]; - func; - tags; - config; - trace = true; - recurse = true; - constructor(fields) { - super(); - this.name = fields.name ?? fields.func.name; - this.func = fields.func; - this.config = fields.tags ? { tags: fields.tags } : undefined; - this.trace = fields.trace ?? this.trace; - this.recurse = fields.recurse ?? this.recurse; - } - async _tracedInvoke(input, config2, runManager) { - return new Promise((resolve2, reject) => { - const childConfig = patchConfig(config2, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton2.runWithConfig(childConfig, async () => { - try { - resolve2(await this.func(input, childConfig)); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - let returnValue; - const config2 = ensureLangGraphConfig2(options); - const mergedConfig = mergeConfigs(this.config, config2); - if (this.trace) - returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); - else - returnValue = await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); - if (Runnable.isRunnable(returnValue) && this.recurse) - return await AsyncLocalStorageProviderSingleton2.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); - return returnValue; + get transcript() { + return this.#transcriptPromise; + } + get objectURL() { + if (this.#cachedObjectURL != null) { + const cached3 = this.#cachedObjectURL; + return Promise.resolve(cached3); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/write.js -function _isSkipWrite2(x) { - return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== undefined; -} -function _isPassthrough2(x) { - return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== undefined; -} -function _isChannelWriteEntry2(x) { - return x !== undefined && typeof x.channel === "string"; -} -function _isChannelWriteTupleEntry2(x) { - return x !== undefined && !_isChannelWriteEntry2(x) && Runnable.isRunnable(x.mapper); -} -var PASSTHROUGH2, IS_WRITER2, ChannelWrite3; -var init_write2 = __esm(() => { - init_constants8(); - init_errors10(); - init_utils17(); - init_runnables(); - PASSTHROUGH2 = { [Symbol.for("LG_PASSTHROUGH")]: true }; - IS_WRITER2 = Symbol("IS_WRITER"); - ChannelWrite3 = class ChannelWrite4 extends RunnableCallable3 { - writes; - constructor(writes, tags) { - const name = `ChannelWrite<${writes.map((packet) => { - if (_isSend2(packet)) - return packet.node; - else if ("channel" in packet) - return packet.channel; - return "..."; - }).join(",")}>`; - super({ - writes, - name, - tags, - trace: false, - func: async (input, config2) => { - return this._write(input, config2 ?? {}); - } - }); - this.writes = writes; - } - async _write(input, config2) { - const writes = this.writes.map((write) => { - if (_isChannelWriteTupleEntry2(write) && _isPassthrough2(write.value)) - return { - mapper: write.mapper, - value: input - }; - else if (_isChannelWriteEntry2(write) && _isPassthrough2(write.value)) - return { - channel: write.channel, - value: input, - skipNone: write.skipNone, - mapper: write.mapper - }; - else - return write; - }); - await ChannelWrite4.doWrite(config2, writes); - return input; - } - static async doWrite(config2, writes) { - for (const w of writes) { - if (_isChannelWriteEntry2(w)) { - if (w.channel === "__pregel_tasks") - throw new InvalidUpdateError2("Cannot write to the reserved channel TASKS"); - if (_isPassthrough2(w.value)) - throw new InvalidUpdateError2("PASSTHROUGH value must be replaced"); + return this.blob.then((blob) => { + if (this.#cachedObjectURL != null) + return this.#cachedObjectURL; + const url3 = URL.createObjectURL(blob); + this.#cachedObjectURL = url3; + return url3; + }); + } + revoke() { + const url3 = this.#cachedObjectURL; + if (url3 == null) + return; + this.#cachedObjectURL = undefined; + try { + URL.revokeObjectURL(url3); + } catch {} + } + get stream() { + if (this.#stream != null) + return this.#stream; + if (this.#urlSourced) + return this.#buildUrlStream(); + return this.#buildInlineStream(); + } + #absorbAudio(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) + this.mimeType = mimeType; + if (block.transcript != null && block.transcript.length > 0) + this.pushTranscript(block.transcript); + } + #absorbImage(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) + this.mimeType = mimeType; + if (this.width == null && block.width != null) + this.width = block.width; + if (this.height == null && block.height != null) + this.height = block.height; + } + #absorbVideo(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) + this.mimeType = mimeType; + } + #absorbFile(block) { + const mimeType = block.mime_type ?? block.mimeType; + if (this.mimeType == null && mimeType != null) + this.mimeType = mimeType; + if (this.filename == null && block.filename != null) + this.filename = block.filename; + } + #buildInlineStream() { + const seed = this.#partialSnapshot; + const alreadyFinished = this.#finished; + const alreadyErrored = this.error; + this.#stream = new ReadableStream({ + start: (controller) => { + this.#streamController = controller; + if (seed.byteLength > 0) + controller.enqueue(seed); + if (alreadyErrored != null) { + controller.error(alreadyErrored); + return; } - if (_isChannelWriteTupleEntry2(w)) { - if (_isPassthrough2(w.value)) - throw new InvalidUpdateError2("PASSTHROUGH value must be replaced"); + if (alreadyFinished) + controller.close(); + }, + cancel: () => { + this.#streamController = undefined; + } + }); + return this.#stream; + } + #buildUrlStream() { + const urlSourceFetch = this.#startUrlFetch(); + this.#stream = new ReadableStream({ + start: async (controller) => { + try { + const response = await urlSourceFetch; + if (response.body == null) { + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength > 0) + controller.enqueue(bytes); + controller.close(); + return; + } + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) + break; + if (value != null) + controller.enqueue(value); + } + controller.close(); + } catch (err) { + controller.error(this.fail("fetch-failed", err?.message, err)); } + }, + cancel: () => { + this.#streamController = undefined; } - const writeEntries = []; - for (const w of writes) - if (_isSend2(w)) - writeEntries.push([TASKS3, w]); - else if (_isChannelWriteTupleEntry2(w)) { - const mappedResult = await w.mapper.invoke(w.value, config2); - if (mappedResult != null && mappedResult.length > 0) - writeEntries.push(...mappedResult); - } else if (_isChannelWriteEntry2(w)) { - const mappedValue = w.mapper !== undefined ? await w.mapper.invoke(w.value, config2) : w.value; - if (_isSkipWrite2(mappedValue)) - continue; - if (w.skipNone && mappedValue === undefined) - continue; - writeEntries.push([w.channel, mappedValue]); - } else - throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); - const write = config2.configurable?.[CONFIG_KEY_SEND2]; - write(writeEntries); - } - static isWriter(runnable) { - return runnable instanceof ChannelWrite4 || IS_WRITER2 in runnable && !!runnable[IS_WRITER2]; + }); + return this.#stream; + } + #startUrlFetch() { + const url3 = this.url; + return this.#fetchImpl(url3).then((response) => { + if (!response.ok) + throw new Error(`fetch(${url3}) failed: ${response.status} ${response.statusText}`); + return response; + }); + } + #fetchUrlSourced() { + if (this.#urlFetchPromise != null) + return this.#urlFetchPromise; + this.#urlFetchPromise = (async () => { + try { + const response = await this.#startUrlFetch(); + const bytes = new Uint8Array(await response.arrayBuffer()); + this.#parts.length = 0; + this.#parts.push(bytes); + this.#totalBytes = bytes.byteLength; + this.#partialSnapshot = bytes; + this.#finished = true; + this.#settled = true; + return bytes; + } catch (err) { + throw this.fail("fetch-failed", err?.message, err); + } + })(); + return this.#urlFetchPromise; + } +}, MediaAssembler = class { + #callbacks; + #fetch; + #active = /* @__PURE__ */ new Map; + #activeByNamespaceNode = /* @__PURE__ */ new Map; + #syntheticCounter = 0; + constructor(options = {}) { + this.#callbacks = options; + if (options.fetch != null) + this.#fetch = options.fetch; + else if (typeof fetch === "function") + this.#fetch = fetch; + else + this.#fetch = () => { + throw new Error("MediaAssembler: no fetch implementation available. Pass `fetch` in options."); + }; + } + consume(event) { + const data = event.params.data; + const namespace = event.params.namespace; + const node = event.params.node; + const nsNodeKey = `${namespace.join("/")}::${node ?? ""}`; + if (data.event === "message-start") { + this.#flushSlot(nsNodeKey, "finish"); + this.#activeByNamespaceNode.set(nsNodeKey, { + messageId: data.id ?? "", + keys: /* @__PURE__ */ new Set, + indexKeys: /* @__PURE__ */ new Map + }); + return; } - static registerWriter(runnable) { - return Object.defineProperty(runnable, IS_WRITER2, { value: true }); + if (data.event === "message-finish") { + this.#flushSlot(nsNodeKey, "finish"); + this.#activeByNamespaceNode.delete(nsNodeKey); + return; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/read.js -var ChannelRead3, defaultRunnableBound2, PregelNode3; -var init_read2 = __esm(() => { - init_constants8(); - init_utils17(); - init_write2(); - init_runnables(); - ChannelRead3 = class ChannelRead4 extends RunnableCallable3 { - lc_graph_name = "ChannelRead"; - channel; - fresh = false; - mapper; - constructor(channel, mapper, fresh = false) { - super({ - trace: false, - func: (_, config2) => ChannelRead4.doRead(config2, this.channel, this.fresh, this.mapper) - }); - this.fresh = fresh; - this.mapper = mapper; - this.channel = channel; - this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; + if (data.event === "error") { + this.#flushSlot(nsNodeKey, "error", data.message); + this.#activeByNamespaceNode.delete(nsNodeKey); + return; } - static doRead(config2, channel, fresh, mapper) { - const read = config2.configurable?.[CONFIG_KEY_READ2]; - if (!read) - throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); - if (mapper) - return mapper(read(channel, fresh)); - else - return read(channel, fresh); + if (data.event !== "content-block-start" && data.event !== "content-block-delta" && data.event !== "content-block-finish") + return; + const block = data.content; + const blockIndex = data.index ?? 0; + let active = this.#activeByNamespaceNode.get(nsNodeKey); + if (active == null) { + active = { + messageId: `__synthetic_${++this.#syntheticCounter}`, + keys: /* @__PURE__ */ new Set, + indexKeys: /* @__PURE__ */ new Map + }; + this.#activeByNamespaceNode.set(nsNodeKey, active); } - }; - defaultRunnableBound2 = /* @__PURE__ */ new RunnablePassthrough; - PregelNode3 = class PregelNode4 extends RunnableBinding { - lc_graph_name = "PregelNode"; - channels; - triggers = []; - mapper; - writers = []; - bound = defaultRunnableBound2; - kwargs = {}; - metadata = {}; - tags = []; - retryPolicy; - cachePolicy; - subgraphs; - ends; - constructor(fields) { - const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; - const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; - super({ - ...fields, - bound: fields.bound ?? defaultRunnableBound2, - config: { - ...fields.config ? fields.config : {}, - tags: mergedTags + if (block == null && data.event === "content-block-delta") { + const delta = data.delta; + const deltaKey = active.indexKeys.get(blockIndex); + const deltaHandle = deltaKey != null ? this.#active.get(deltaKey) : undefined; + if (delta == null || typeof delta !== "object") + return; + const record3 = delta; + if (deltaHandle == null) { + if (record3.type !== "block-delta" || record3.fields == null || typeof record3.fields !== "object") + return; + const fields = record3.fields; + if (!MEDIA_BLOCK_TYPES.has(fields.type)) + return; + this.#consumeMediaBlock({ + active, + block: fields, + blockIndex, + dataEvent: data.event, + namespace, + node, + terminal: false, + createIfMissing: true + }); + return; + } + deltaHandle.observeIndex(blockIndex); + if (record3.type === "data-delta" && typeof record3.data === "string") { + try { + deltaHandle.pushBytes(base64ToBytes(record3.data)); + } catch (err) { + deltaHandle.fail("message-error", "invalid base64 on delta", err); } + return; + } + if (record3.type === "block-delta" && record3.fields != null && typeof record3.fields === "object") { + const fields = record3.fields; + deltaHandle.absorbBlock(fields); + if (!deltaHandle.error && fields.data != null) + try { + deltaHandle.pushBytes(base64ToBytes(fields.data)); + } catch (err) { + deltaHandle.fail("message-error", "invalid base64 on delta", err); + } + } + return; + } + if (block == null) + return; + const blockType = block.type; + if (!MEDIA_BLOCK_TYPES.has(blockType)) + return; + this.#consumeMediaBlock({ + active, + block, + blockIndex, + dataEvent: data.event, + namespace, + node, + terminal: data.event === "content-block-finish", + createIfMissing: data.event === "content-block-start" || data.event === "content-block-finish" + }); + } + #consumeMediaBlock({ active, block, blockIndex, dataEvent, namespace, node, terminal, createIfMissing }) { + const blockType = block.type; + if (!MEDIA_BLOCK_TYPES.has(blockType)) + return; + const mediaType = blockType; + const key = `${active.messageId}::${mediaType}::${blockIndex}`; + let handle = this.#active.get(key); + const isStart = dataEvent === "content-block-start"; + if (handle == null) { + const isTerminalBlock = terminal; + if (!isStart && !isTerminalBlock && !createIfMissing) + return; + const mediaBlock2 = block; + handle = new MediaHandleImpl({ + type: mediaType, + messageId: active.messageId, + namespace: [...namespace], + node, + id: mediaBlock2.id, + mimeType: mediaBlock2.mime_type ?? mediaBlock2.mimeType, + url: mediaBlock2.url != null && mediaBlock2.data == null ? mediaBlock2.url : undefined, + fetch: this.#fetch }); - this.channels = channels; - this.triggers = triggers; - this.mapper = mapper; - this.writers = writers ?? this.writers; - this.bound = bound ?? this.bound; - this.kwargs = kwargs ?? this.kwargs; - this.metadata = metadata ?? this.metadata; - this.tags = mergedTags; - this.retryPolicy = retryPolicy; - this.cachePolicy = cachePolicy; - this.subgraphs = subgraphs; - this.ends = ends; + if (mediaBlock2.url != null && mediaBlock2.data == null) + handle.enterUrlMode(mediaBlock2.url); + handle.observeIndex(blockIndex); + handle.absorbBlock(block); + if (mediaBlock2.data != null) + try { + handle.pushBytes(base64ToBytes(mediaBlock2.data)); + } catch (err) { + handle.fail("message-error", "invalid base64 on initial block", err); + } + this.#active.set(key, handle); + active.keys.add(key); + active.indexKeys.set(blockIndex, key); + this.#emit(handle); + if (isTerminalBlock) { + handle.finish(); + this.#active.delete(key); + active.keys.delete(key); + active.indexKeys.delete(blockIndex); + } + return; } - getWriters() { - const newWriters = [...this.writers]; - while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite3 && newWriters[newWriters.length - 2] instanceof ChannelWrite3) { - const endWriters = newWriters.slice(-2); - const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); - newWriters[newWriters.length - 2] = new ChannelWrite3(combinedWrites, endWriters[0].config?.tags); - newWriters.pop(); + if (terminal) + return; + const mediaBlock = block; + handle.observeIndex(blockIndex); + handle.absorbBlock(block); + if (!handle.error && mediaBlock.data != null) + try { + handle.pushBytes(base64ToBytes(mediaBlock.data)); + } catch (err) { + handle.fail("message-error", "invalid base64 on delta", err); } - return newWriters; + } + #flushSlot(nsNodeKey, mode, errorMessage) { + const active = this.#activeByNamespaceNode.get(nsNodeKey); + if (active == null) + return; + for (const key of active.keys) { + const handle = this.#active.get(key); + if (handle != null) + if (mode === "finish") + handle.finish(); + else + handle.fail("message-error", errorMessage); + this.#active.delete(key); } - getNode() { - const writers = this.getWriters(); - if (this.bound === defaultRunnableBound2 && writers.length === 0) - return; - else if (this.bound === defaultRunnableBound2 && writers.length === 1) - return writers[0]; - else if (this.bound === defaultRunnableBound2) - return new RunnableSequence({ - first: writers[0], - middle: writers.slice(1, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else if (writers.length > 0) - return new RunnableSequence({ - first: this.bound, - middle: writers.slice(0, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else - return this.bound; + active.keys.clear(); + active.indexKeys.clear(); + } + close() { + for (const handle of this.#active.values()) + handle.fail("stream-closed", "upstream event stream closed"); + this.#active.clear(); + this.#activeByNamespaceNode.clear(); + } + #emit(handle) { + switch (handle.type) { + case "audio": + this.#callbacks.onAudio?.(handle); + break; + case "image": + this.#callbacks.onImage?.(handle); + break; + case "video": + this.#callbacks.onVideo?.(handle); + break; + case "file": + this.#callbacks.onFile?.(handle); + break; } - join(channels) { - if (!Array.isArray(channels)) - throw new Error("channels must be a list"); - if (typeof this.channels !== "object") - throw new Error("all channels must be named when using .join()"); - return new PregelNode4({ - channels: { - ...this.channels, - ...Object.fromEntries(channels.map((chan) => [chan, chan])) - }, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); + this.#callbacks.onMedia?.(handle); + } +}; +var init_media = __esm(() => { + MEDIA_BLOCK_TYPES = new Set([ + "audio", + "image", + "video", + "file" + ]); + MediaAssemblyError = class extends Error { + kind; + messageId; + partialBytes; + cause; + constructor(kind, messageId, partialBytes, message, options) { + super(message ?? `media ${kind} for message ${messageId}`); + this.name = "MediaAssemblyError"; + this.kind = kind; + this.messageId = messageId; + this.partialBytes = partialBytes; + this.cause = options?.cause; } - pipe(coerceable) { - if (ChannelWrite3.isWriter(coerceable)) - return new PregelNode4({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: [...this.writers, coerceable], - bound: this.bound, - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else if (this.bound === defaultRunnableBound2) - return new PregelNode4({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: _coerceToRunnable(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else - return new PregelNode4({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound.pipe(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/error.js +var ProtocolError2; +var init_error4 = __esm(() => { + ProtocolError2 = class extends Error { + code; + response; + constructor(response) { + super(response.message); + this.name = "ProtocolError"; + this.code = response.error; + this.response = response; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js -function isRunnableSequence2(x) { - return "steps" in x && Array.isArray(x.steps); -} -function isPregelLike2(x) { - return "lg_is_pregel" in x && x.lg_is_pregel === true; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/constants.js +var init_constants6 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/headless-tools.js +function parseHeadlessToolInterruptPayload(value) { + if (typeof value !== "object" || value == null) + return null; + const v = value; + if (v.type !== "tool") + return null; + const rawTc = v.toolCall ?? v.tool_call; + if (typeof rawTc !== "object" || rawTc == null) + return null; + const tc = rawTc; + if (typeof tc.name !== "string") + return null; + return { + type: "tool", + toolCall: { + id: typeof tc.id === "string" ? tc.id : undefined, + name: tc.name, + args: tc.args + } + }; } -function findSubgraphPregel2(candidate) { - const candidates = [candidate]; - for (const candidate2 of candidates) - if (isPregelLike2(candidate2)) - return candidate2; - else if (isRunnableSequence2(candidate2)) - candidates.push(...candidate2.steps); +function isHeadlessToolInterrupt(interrupt3) { + return parseHeadlessToolInterruptPayload(interrupt3) != null; } -var init_subgraph2 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/io.js -function readChannel2(channels, chan, catchErrors = true, returnException = false) { - try { - return channels[chan].get(); - } catch (e) { - if (e.name === EmptyChannelError2.unminifiable_name) { - if (returnException) - return e; - else if (catchErrors) - return null; +function extractHeadlessToolCallIdFromResumeCommand(resume) { + if (resume == null || typeof resume !== "object" || Array.isArray(resume)) + return; + const keys = Object.keys(resume); + if (keys.length !== 1) + return; + return keys[0]; +} +function resolveInterruptTargetForHeadlessResume(resume, interrupts, resolvedInterruptIds) { + const toolCallId = extractHeadlessToolCallIdFromResumeCommand(resume); + if (toolCallId != null) + for (let i = interrupts.length - 1;i >= 0; i -= 1) { + const entry = interrupts[i]; + if (entry == null || resolvedInterruptIds.has(entry.interruptId)) + continue; + if (parseHeadlessToolInterruptPayload(entry.payload)?.toolCall.id === toolCallId) + return { + interruptId: entry.interruptId, + namespace: [...entry.namespace] + }; } - throw e; + for (let i = interrupts.length - 1;i >= 0; i -= 1) { + const entry = interrupts[i]; + if (entry == null || resolvedInterruptIds.has(entry.interruptId)) + continue; + return { + interruptId: entry.interruptId, + namespace: [...entry.namespace] + }; } + return null; } -function readChannels2(channels, select, skipEmpty = true) { - if (Array.isArray(select)) { - const values2 = {}; - for (const k of select) - try { - values2[k] = readChannel2(channels, k, !skipEmpty); - } catch (e) { - if (e.name === EmptyChannelError2.unminifiable_name) - continue; - } - return values2; - } else - return readChannel2(channels, select); +var init_headless_tools = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/subscription.js +function normalizeSegment(segment) { + const idx = segment.indexOf(":"); + return idx === -1 ? segment : segment.slice(0, idx); } -function* mapCommand2(cmd, pendingWrites) { - if (cmd.graph === Command2.PARENT) - throw new InvalidUpdateError2("There is no parent graph."); - if (cmd.goto) { - let sends; - if (Array.isArray(cmd.goto)) - sends = cmd.goto; - else - sends = [cmd.goto]; - for (const send of sends) - if (_isSend2(send)) - yield [ - NULL_TASK_ID2, - TASKS3, - send - ]; - else if (typeof send === "string") - yield [ - NULL_TASK_ID2, - `branch:to:${send}`, - "__start__" - ]; - else - throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); +function isPrefixMatch(eventNamespace, prefix) { + if (prefix.length > eventNamespace.length) + return false; + for (let i = 0;i < prefix.length; i += 1) { + const segment = prefix[i]; + const candidate = eventNamespace[i]; + if (candidate === segment) + continue; + if (segment.includes(":")) + return false; + if (normalizeSegment(candidate) === segment) + continue; + return false; } - if (cmd.resume) - if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH32)) - for (const [tid, resume] of Object.entries(cmd.resume)) { - const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === "__resume__").map((w) => w[2]).slice(0, 1) ?? []; - existing.push(resume); - yield [ - tid, - RESUME3, - existing - ]; - } - else - yield [ - NULL_TASK_ID2, - RESUME3, - cmd.resume - ]; - if (cmd.update) { - if (typeof cmd.update !== "object" || !cmd.update) - throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); - if (Array.isArray(cmd.update)) - for (const [k, v] of cmd.update) - yield [ - NULL_TASK_ID2, - k, - v - ]; - else - for (const [k, v] of Object.entries(cmd.update)) - yield [ - NULL_TASK_ID2, - k, - v - ]; + return true; +} +function namespaceMatches(eventNamespace, prefixes, depth) { + if (!prefixes || prefixes.length === 0) + return true; + return prefixes.some((prefix) => { + if (!isPrefixMatch(eventNamespace, prefix)) + return false; + if (depth === undefined) + return true; + return eventNamespace.length - prefix.length <= depth; + }); +} +function inferChannel(event) { + switch (event.method) { + case "values": + return "values"; + case "checkpoints": + return "checkpoints"; + case "updates": + return "updates"; + case "messages": + return "messages"; + case "tools": + return "tools"; + case "custom": { + const data = event.params.data; + return data?.name != null ? `custom:${data.name}` : "custom"; + } + case "lifecycle": + return "lifecycle"; + case "input.requested": + return "input"; + case "tasks": + return "tasks"; + default: + return; } } -function* mapInput2(inputChannels, chunk) { - if (chunk !== undefined && chunk !== null) - if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { - for (const k in chunk) - if (inputChannels.includes(k)) - yield [k, chunk[k]]; - } else if (Array.isArray(inputChannels)) - throw new Error(`Input chunk must be an object when "inputChannels" is an array`); - else - yield [inputChannels, chunk]; +function matchesSubscription(event, definition) { + const channel = inferChannel(event); + if (channel === undefined) + return false; + const channels = definition.channels; + if (!(channels.includes(channel) || channel.startsWith("custom:") && channels.includes("custom"))) + return false; + return namespaceMatches(event.params.namespace, definition.namespaces, definition.depth); } -function* mapOutputValues2(outputChannels, pendingWrites, channels) { - if (Array.isArray(outputChannels)) { - if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) - yield readChannels2(channels, outputChannels); - } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) - yield readChannel2(channels, outputChannels); +var init_subscription = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/ui/messages.js +function tryCoerceMessageLikeToMessage(message) { + if (message.type === "human" || message.type === "user") + return new HumanMessage(message); + if (message.type === "ai" || message.type === "assistant") + return new AIMessage(normalizeAIMessageToolCalls(message)); + if (message.type === "system") + return new SystemMessage(message); + if (message.type === "tool" && "tool_call_id" in message) + return new ToolMessage({ + ...message, + tool_call_id: message.tool_call_id + }); + if (message.type === "remove" && message.id != null) + return new RemoveMessage({ + ...message, + id: message.id + }); + return coerceMessageLikeToMessage(message); } -function* mapOutputUpdates2(outputChannels, tasks, cached2) { - const outputTasks = tasks.filter(([task2, ww]) => { - return (task2.config === undefined || !task2.config.tags?.includes("langsmith:hidden")) && ww[0][0] !== "__error__" && ww[0][0] !== "__interrupt__"; +function normalizeAIMessageToolCalls(message) { + const record3 = message; + if (Array.isArray(record3.tool_calls) && record3.tool_calls.length > 0) + return message; + const toolCalls = extractToolCallsFromContent(record3.content); + if (toolCalls.length === 0) + return message; + return { + ...message, + tool_calls: toolCalls + }; +} +function extractToolCallsFromContent(content) { + if (!Array.isArray(content)) + return []; + return content.flatMap((block) => { + if (block == null || typeof block !== "object") + return []; + const record3 = block; + if (record3.type !== "tool_call" && record3.type !== "tool_use") + return []; + return [{ + id: record3.id ?? "", + name: record3.name ?? "", + args: normalizeToolCallArgs(record3.args ?? record3.input), + type: "tool_call" + }]; }); - if (!outputTasks.length) - return; - let updated; - if (outputTasks.some(([task2]) => task2.writes.some(([chan, _]) => chan === "__return__"))) - updated = outputTasks.flatMap(([task2]) => task2.writes.filter(([chan, _]) => chan === RETURN2).map(([_, value]) => [task2.name, value])); - else if (!Array.isArray(outputChannels)) - updated = outputTasks.flatMap(([task2]) => task2.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task2.name, value])); - else - updated = outputTasks.flatMap(([task2]) => { - const { writes } = task2; - const counts = {}; - for (const [chan] of writes) - if (outputChannels.includes(chan)) - counts[chan] = (counts[chan] || 0) + 1; - if (Object.values(counts).some((count) => count > 1)) - return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task2.name, { [chan]: value }]); - else - return [[task2.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; - }); - const grouped = {}; - for (const [node, value] of updated) { - if (!(node in grouped)) - grouped[node] = []; - grouped[node].push(value); - } - const flattened = {}; - for (const node in grouped) - if (grouped[node].length === 1) { - const [write] = grouped[node]; - flattened[node] = write; - } else - flattened[node] = grouped[node]; - if (cached2) - flattened["__metadata__"] = { cached: cached2 }; - yield flattened; } -var init_io2 = __esm(() => { - init_constants8(); - init_errors10(); - init_hash4(); +function normalizeToolCallArgs(value) { + if (value != null && typeof value === "object" && !Array.isArray(value)) + return value; + if (typeof value === "string" && value.length > 0) + try { + const parsed = JSON.parse(value); + if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) + return parsed; + } catch {} + return {}; +} +function ensureMessageInstances(messages) { + return messages.map((msg) => { + if (typeof msg.getType === "function") + return msg; + return tryCoerceMessageLikeToMessage(msg); + }); +} +var init_messages9 = __esm(() => { + init_messages(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/utils/index.js -function getNullChannelVersion2(currentVersions) { - const startVersion = typeof currentVersions[START2]; - if (startVersion === "number") - return 0; - if (startVersion === "string") - return ""; - for (const key in currentVersions) { - if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) - continue; - const versionType = typeof currentVersions[key]; - if (versionType === "number") - return 0; - if (versionType === "string") - return ""; - break; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/tools.js +function toClientAssembledToolCall(handle) { + return { + name: handle.name, + callId: handle.callId, + id: handle.id, + namespace: handle.namespace, + input: handle.input, + args: handle.args, + output: handle.outputPromise + }; +} +function parseToolPayload(value) { + if (typeof value !== "string") + return value; + const trimmed = value.trim(); + if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) + return value; + try { + return JSON.parse(trimmed); + } catch { + return value; } } -function getNewChannelVersions2(previousVersions, currentVersions) { - if (Object.keys(previousVersions).length > 0) { - const nullVersion = getNullChannelVersion2(currentVersions); - return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); - } else - return currentVersions; +function shouldIgnoreScopedTaskToolEvent(scopeNamespace, event) { + const data = event.params.data; + return scopeNamespace.length > 0 && event.params.namespace.length === scopeNamespace.length && event.params.namespace.every((segment, index2) => segment === scopeNamespace[index2]) && "tool_name" in data && data.tool_name === "task"; } -function _coerceToDict4(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +function getWireMessageField(message, field) { + if (!message || typeof message !== "object" || Array.isArray(message)) + return; + const record3 = message; + if (field in record3) + return record3[field]; + const kwargs = record3.kwargs; + if (kwargs != null && field in kwargs) + return kwargs[field]; + const lcKwargs = record3.lc_kwargs; + if (lcKwargs != null && field in lcKwargs) + return lcKwargs[field]; +} +function isToolMessageLike(value) { + if (!value || typeof value !== "object") + return false; + if (value.type === "tool") + return true; + if (getWireMessageField(value, "type") === "tool") + return true; + return typeof getWireMessageField(value, "tool_call_id") === "string" && getWireMessageField(value, "content") !== undefined; } -function patchConfigurable4(config2, patch) { - if (config2 === null) - return { configurable: patch }; - else if (config2?.configurable === undefined) - return { - ...config2, - configurable: patch - }; - else - return { - ...config2, - configurable: { - ...config2.configurable, - ...patch - } - }; +function isCommandLike(value) { + return !!value && typeof value === "object" && value.lg_name === "Command"; } -function patchCheckpointMap2(config2, metadata) { - const parents = metadata?.parents ?? {}; - if (Object.keys(parents).length > 0) - return patchConfigurable4(config2, { [CONFIG_KEY_CHECKPOINT_MAP2]: { - ...parents, - [config2.configurable?.checkpoint_ns ?? ""]: config2.configurable?.checkpoint_id - } }); - else - return config2; +function textFromContentBlocks(content) { + let out = ""; + for (const block of content) { + if (!block || typeof block !== "object") + continue; + const record3 = block; + if (record3.type === "text" && typeof record3.text === "string") + out += record3.text; + } + return out; } -function combineAbortSignals2(...x) { - const signals = [...new Set(x.filter(Boolean))]; - if (signals.length === 0) - return { - signal: undefined, - dispose: undefined - }; - if (signals.length === 1) +function parseToolResultContent(content) { + if (content == null) + return null; + if (typeof content === "string") { + if (content.trim().length === 0) + return null; + return parseToolPayload(content); + } + if (Array.isArray(content)) { + const text = textFromContentBlocks(content); + if (text.length === 0) + return null; + return parseToolPayload(text); + } + if (typeof content === "object") + return content; + return null; +} +function parseToolMessageRecord(message) { + return parseToolResultContent(getWireMessageField(message, "content")); +} +function parseCommandToolOutput(command, toolCallId) { + const update = command.update; + if (update == null || typeof update !== "object" || Array.isArray(update)) + return { found: false }; + const messages = update.messages; + if (!Array.isArray(messages)) + return { found: false }; + const toolMessages = messages.filter((message) => isToolMessageLike(message)); + if (toolMessages.length === 0) + return { found: false }; + if (toolCallId != null) { + for (const message of toolMessages) { + if (getWireMessageField(message, "tool_call_id") !== toolCallId) + continue; + return { + found: true, + value: parseToolMessageRecord(message) + }; + } + return { found: false }; + } + if (toolMessages.length === 1) return { - signal: signals[0], - dispose: undefined + found: true, + value: parseToolMessageRecord(toolMessages[0]) }; - const combinedController = new AbortController; - const listener = () => { - const reason = signals.find((s) => s.aborted)?.reason; - combinedController.abort(reason); - signals.forEach((s) => s.removeEventListener("abort", listener)); - }; - signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); - const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); - if (hasAlreadyAbortedSignal) - combinedController.abort(hasAlreadyAbortedSignal.reason); + for (let i = toolMessages.length - 1;i >= 0; i -= 1) { + const parsed = parseToolMessageRecord(toolMessages[i]); + if (parsed != null) + return { + found: true, + value: parsed + }; + } return { - signal: combinedController.signal, - dispose: () => { - signals.forEach((s) => s.removeEventListener("abort", listener)); - } + found: true, + value: null }; } -var combineCallbacks2 = (callback1, callback2) => { - if (!callback1 && !callback2) - return; - if (!callback1) - return callback2; - if (!callback2) - return callback1; - if (Array.isArray(callback1) && Array.isArray(callback2)) - return [...callback1, ...callback2]; - if (Array.isArray(callback1)) - return [...callback1, callback2]; - if (Array.isArray(callback2)) - return [callback1, ...callback2]; - return [callback1, callback2]; -}; -var init_utils18 = __esm(() => { - init_constants8(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/types.js -function isCall2(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; +function parseToolOutput(value, toolCallId) { + const parsed = parseToolPayload(value); + if (isCommandLike(parsed)) { + const commandOutput = parseCommandToolOutput(parsed, toolCallId); + return commandOutput.found ? commandOutput.value : parsed; + } + if (isToolMessageLike(parsed)) + return parseToolResultContent(getWireMessageField(parsed, "content")); + return parsed ?? null; } -var Call2 = class { - func; - name; - input; - retry; - cache; - callbacks; - __lg_type = "call"; - constructor({ func, name, input, retry, cache: cache2, callbacks }) { - this.func = func; - this.name = name; - this.input = input; - this.retry = retry; - this.cache = cache2; - this.callbacks = callbacks; +var ToolCallAssembler = class { + active = /* @__PURE__ */ new Map; + consume(event) { + const data = event.params.data; + if (data.event === "tool-started") + return this.handleStarted(event, data); + if (data.event === "tool-finished") + return this.handleFinished(data); + if (data.event === "tool-error") + return this.handleError(data); } -}; -var init_types13 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/call.js -function getRunnableForFunc2(name, func) { - return new RunnableSequence({ - name, - first: new RunnableCallable3({ - func: (input) => func(...input), + failAll(reason) { + for (const entry of this.active.values()) { + entry.rejectOutput(reason); + entry.handle.status = "error"; + entry.handle.error = reason.message; + } + this.active.clear(); + } + handleStarted(event, data) { + let resolveOutput; + let rejectOutput; + const outputPromise = new Promise((resolve2, reject) => { + resolveOutput = resolve2; + rejectOutput = reject; + }); + outputPromise.catch(() => { + return; + }); + const input = parseToolPayload(data.input); + const name = data.tool_name; + const callId = data.tool_call_id; + const handle = { name, - trace: false, - recurse: false - }), - last: new ChannelWrite3([{ - channel: RETURN2, - value: PASSTHROUGH2 - }], [TAG_HIDDEN2]) - }); -} -function getRunnableForEntrypoint2(name, func) { - return new RunnableCallable3({ - func: (input, config2) => { - return func(input, config2); - }, - name, - trace: false, - recurse: false - }); -} -function call3({ func, name, cache: cache2, retry }, ...args) { - const config2 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (typeof config2.configurable?.["__pregel_call"] === "function") - return config2.configurable[CONFIG_KEY_CALL2](func, name, args, { - retry, - cache: cache2, - callbacks: config2.callbacks + callId, + id: callId, + namespace: [...event.params.namespace], + input, + args: input, + output: null, + status: "running", + error: undefined, + outputPromise + }; + this.active.set(callId, { + handle, + resolveOutput, + rejectOutput }); - throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); -} -var init_call2 = __esm(() => { - init_constants8(); - init_utils17(); - init_write2(); - init_singletons(); - init_runnables(); -}); + return handle; + } + handleFinished(data) { + const entry = this.active.get(data.tool_call_id); + if (!entry) + return; + this.active.delete(data.tool_call_id); + const value = parseToolOutput(data.output, data.tool_call_id); + entry.resolveOutput(value); + entry.handle.output = value; + entry.handle.status = "finished"; + entry.handle.error = undefined; + return entry.handle; + } + handleError(data) { + const entry = this.active.get(data.tool_call_id); + if (!entry) + return; + this.active.delete(data.tool_call_id); + entry.rejectOutput(new Error(data.message)); + entry.handle.output = null; + entry.handle.status = "error"; + entry.handle.error = data.message; + return entry.handle; + } +}; +var init_tools4 = () => {}; -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/algo.js -function triggersNextStep2(updatedChannels, triggerToNodes) { - if (triggerToNodes == null) - return false; - for (const chan of updatedChannels) - if (triggerToNodes[chan]) - return true; - return false; -} -function maxChannelMapVersion2(channelVersions) { - let maxVersion; - for (const chan in channelVersions) { - if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) - continue; - if (maxVersion == null) - maxVersion = channelVersions[chan]; - else - maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subagents.js +var exports_subagents = {}; +__export(exports_subagents, { + SubagentHandle: () => SubagentHandle, + SubagentDiscoveryHandle: () => SubagentDiscoveryHandle +}); +var SubagentHandle = class { + name; + callId; + taskInput; + output; + namespace; + #session; + #messagesIterable; + #toolCallsIterable; + #subgraphsIterable; + #mediaDispatcherStarted = false; + #audioBuffer; + #imagesBuffer; + #videoBuffer; + #filesBuffer; + constructor(name, callId, namespace, taskInput, output, session) { + this.name = name; + this.callId = callId; + this.namespace = namespace; + this.taskInput = taskInput; + this.output = output; + this.#session = session; } - return maxVersion; -} -function shouldInterrupt2(checkpoint, interruptNodes, tasks) { - const nullVersion = getNullChannelVersion2(checkpoint.channel_versions); - const seen = checkpoint.versions_seen["__interrupt__"] ?? {}; - let anyChannelUpdated = false; - if ((checkpoint.channel_versions["__start__"] ?? nullVersion) > (seen["__start__"] ?? nullVersion)) - anyChannelUpdated = true; - else - for (const chan in checkpoint.channel_versions) { - if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) - continue; - if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { - anyChannelUpdated = true; - break; - } - } - const anyTriggeredNodeInInterruptNodes = tasks.some((task2) => interruptNodes === "*" ? !task2.config?.tags?.includes(TAG_HIDDEN2) : interruptNodes.includes(task2.name)); - return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; -} -function _localRead2(checkpoint, channels, task2, select, fresh = false) { - let updated = /* @__PURE__ */ new Set; - if (!Array.isArray(select)) { - for (const [c] of task2.writes) - if (c === select) { - updated = new Set([c]); - break; - } - updated = updated || /* @__PURE__ */ new Set; - } else - updated = new Set(select.filter((c) => task2.writes.some(([key, _]) => key === c))); - let values2; - if (fresh && updated.size > 0) { - const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); - const newCheckpoint = createCheckpoint2(checkpoint, localChannels, -1); - const newChannels = emptyChannels2(localChannels, newCheckpoint); - _applyWrites2(copyCheckpoint(newCheckpoint), newChannels, [task2], undefined, undefined); - values2 = readChannels2({ - ...channels, - ...newChannels - }, select); - } else - values2 = readChannels2(channels, select); - return values2; -} -function _localWrite2(commit, processes, writes) { - for (const [chan, value] of writes) - if (["__pregel_push", "__pregel_tasks"].includes(chan) && value != null) { - if (!_isSend2(value)) - throw new InvalidUpdateError2(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); - if (!(value.node in processes)) - throw new InvalidUpdateError2(`Invalid node name "${value.node}" in Send packet`); - } - commit(writes); -} -function _applyWrites2(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { - tasks.sort((a, b) => { - const aPath = a.path?.slice(0, 3) || []; - const bPath = b.path?.slice(0, 3) || []; - for (let i = 0;i < Math.min(aPath.length, bPath.length); i += 1) { - if (aPath[i] < bPath[i]) - return -1; - if (aPath[i] > bPath[i]) - return 1; - } - return aPath.length - bPath.length; - }); - const bumpStep = tasks.some((task2) => task2.triggers.length > 0); - const onlyChannels = getOnlyChannels2(channels); - for (const task2 of tasks) { - checkpoint.versions_seen[task2.name] ??= {}; - for (const chan of task2.triggers) - if (chan in checkpoint.channel_versions) - checkpoint.versions_seen[task2.name][chan] = checkpoint.channel_versions[chan]; + get messages() { + if (this.#messagesIterable) + return this.#messagesIterable; + const buffer = new MultiCursorBuffer; + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler; + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") + return; + const msg = assembler.consume(event); + if (msg) + buffer.push(msg); + }, () => buffer.close()); + return buffer; } - let maxVersion = maxChannelMapVersion2(checkpoint.channel_versions); - const channelsToConsume = new Set(tasks.flatMap((task2) => task2.triggers).filter((chan) => !RESERVED2.includes(chan))); - let usedNewVersion = false; - for (const chan of channelsToConsume) - if (chan in onlyChannels && onlyChannels[chan].consume()) { - if (getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - usedNewVersion = true; - } - } - const pendingWritesByChannel = {}; - for (const task2 of tasks) - for (const [chan, val] of task2.writes) - if (IGNORE2.has(chan)) {} else if (chan in onlyChannels) { - pendingWritesByChannel[chan] ??= []; - pendingWritesByChannel[chan].push(val); - } - if (maxVersion != null && getNextVersion != null) - maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; - const updatedChannels = /* @__PURE__ */ new Set; - for (const [chan, vals] of Object.entries(pendingWritesByChannel)) - if (chan in onlyChannels) { - const channel = onlyChannels[chan]; - let updated; - try { - updated = channel.update(vals); - } catch (e) { - if (e.name === InvalidUpdateError2.unminifiable_name) { - const wrappedError = new InvalidUpdateError2(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); - wrappedError.lc_error_code = e.lc_error_code; - throw wrappedError; - } else - throw e; - } - if (updated && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); - } - } - if (bumpStep) - for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) - continue; - const channel = onlyChannels[chan]; - if (channel.isAvailable() && !updatedChannels.has(chan)) { - if (channel.update([]) && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); - } - } - } - if (bumpStep && !triggersNextStep2(updatedChannels, triggerToNodes)) - for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) - continue; - const channel = onlyChannels[chan]; - if (channel.finish() && getNextVersion !== undefined) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) - updatedChannels.add(chan); - } - } - return updatedChannels; -} -function* candidateNodes2(checkpoint, processes, extra) { - if (extra.updatedChannels != null && extra.triggerToNodes != null) { - const triggeredNodes = /* @__PURE__ */ new Set; - for (const channel of extra.updatedChannels) { - const nodeIds = extra.triggerToNodes[channel]; - for (const id of nodeIds ?? []) - triggeredNodes.add(id); - } - yield* [...triggeredNodes].sort(); - return; + get toolCalls() { + if (this.#toolCallsIterable) + return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer; + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler; + this.#startProjection(["tools"], (event) => { + if (event.method !== "tools") + return; + const toolsEvent = event; + if (shouldIgnoreScopedTaskToolEvent(this.namespace, toolsEvent)) + return; + const tc = assembler.consume(toolsEvent); + if (tc) + buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; } - if ((() => { - for (const chan in checkpoint.channel_versions) - if (checkpoint.channel_versions[chan] !== null) - return false; - return true; - })()) - return; - for (const name in processes) { - if (!Object.prototype.hasOwnProperty.call(processes, name)) - continue; - yield name; + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; } -} -function _prepareNextTasks2(checkpoint, pendingWrites, processes, channels, config2, forExecution, extra) { - const tasks = {}; - const tasksChannel = channels[TASKS3]; - if (tasksChannel?.isAvailable()) { - const len = tasksChannel.get().length; - for (let i = 0;i < len; i += 1) { - const task2 = _prepareSingleTask2([PUSH2, i], checkpoint, pendingWrites, processes, channels, config2, forExecution, extra); - if (task2 !== undefined) - tasks[task2.id] = task2; - } + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; } - for (const name of candidateNodes2(checkpoint, processes, extra)) { - const task2 = _prepareSingleTask2([PULL2, name], checkpoint, pendingWrites, processes, channels, config2, forExecution, extra); - if (task2 !== undefined) - tasks[task2.id] = task2; + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; } - return tasks; -} -function _prepareSingleTask2(taskPath, checkpoint, pendingWrites, processes, channels, config2, forExecution, extra) { - const { step, checkpointer, manager } = extra; - const configurable = config2.configurable ?? {}; - const parentNamespace = configurable.checkpoint_ns ?? ""; - if (taskPath[0] === "__pregel_push" && isCall2(taskPath[taskPath.length - 1])) { - const call4 = taskPath[taskPath.length - 1]; - const proc = getRunnableForFunc2(call4.name, call4.func); - const triggers = [PUSH2]; - const checkpointNamespace = parentNamespace === "" ? call4.name : `${parentNamespace}|${call4.name}`; - const id = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - call4.name, - PUSH2, - taskPath[1], - taskPath[2] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${id}`; - const outputTaskPath = [...taskPath.slice(0, 3), true]; - const metadata = { - langgraph_step: step, - langgraph_node: call4.name, - langgraph_triggers: triggers, - langgraph_path: outputTaskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId: id, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; - return { - name: call4.name, - input: call4.input, - proc, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - store: extra.store ?? config2.store - }), { - runName: call4.name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID2]: id, - [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { - name: call4.name, - writes, - triggers, - path: outputTaskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP2]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ - pendingWrites: pendingWrites ?? [], - taskId: id, - currentTaskInput: call4.input, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP2], - namespaceHash: XXH32(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace - } - }), - executionInfo - }, - triggers, - retry_policy: call4.retry, - cache_key: call4.cache ? { - key: XXH32((call4.cache.keyFunc ?? JSON.stringify)([call4.input])), - ns: [CACHE_NS_WRITES2, call4.name ?? "__dynamic__"], - ttl: call4.cache.ttl - } : undefined, - id, - path: outputTaskPath, - writers: [] - }; - } else - return { - id, - name: call4.name, - interrupts: [], - path: outputTaskPath - }; - } else if (taskPath[0] === "__pregel_push") { - const index2 = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); - if (!channels["__pregel_tasks"]?.isAvailable()) - return; - const sends = channels[TASKS3].get(); - if (index2 < 0 || index2 >= sends.length) - return; - const packet = _isSendInterface2(sends[index2]) && !_isSend2(sends[index2]) ? new Send2(sends[index2].node, sends[index2].args) : sends[index2]; - if (!_isSendInterface2(packet)) { - console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) return; + this.#mediaDispatcherStarted = true; + const audio = new MultiCursorBuffer; + const images = new MultiCursorBuffer; + const video = new MultiCursorBuffer; + const files = new MultiCursorBuffer; + this.#audioBuffer = audio; + this.#imagesBuffer = images; + this.#videoBuffer = video; + this.#filesBuffer = files; + const assembler = new MediaAssembler({ + onAudio: (m) => audio.push(m), + onImage: (m) => images.push(m), + onVideo: (m) => video.push(m), + onFile: (m) => files.push(m) + }); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") + return; + assembler.consume(event); + }, () => { + assembler.close(); + audio.close(); + images.close(); + video.close(); + files.close(); + }); + } + get subgraphs() { + if (this.#subgraphsIterable) + return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer; + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ + channels: ["lifecycle"], + namespaces: [this.namespace] + }), this.#session, this.namespace); + for await (const sub of discovery) + buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + subscribe(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) + return this.#session.subscribe({ + ...paramsOrChannels, + namespaces: paramsOrChannels.namespaces ?? [this.namespace] + }); + return this.#session.subscribe(paramsOrChannels, { + ...options, + namespaces: options.namespaces ?? [this.namespace] + }); + } + async#startProjection(channels, onEvent, onDone) { + try { + const rawHandle = await this.#session.subscribe({ + channels, + namespaces: [this.namespace] + }); + for await (const event of rawHandle) + onEvent(event); + } finally { + onDone(); } - if (!(packet.node in processes)) { - console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); - return; + } +}, SubagentDiscoveryHandle; +var init_subagents = __esm(() => { + init_multi_cursor_buffer(); + init_tools4(); + init_messages8(); + init_media(); + init_subgraphs3(); + SubagentDiscoveryHandle = class { + #source; + #session; + #queue = []; + #waiters = []; + #pending = /* @__PURE__ */ new Map; + #sourcePump; + #closed = false; + constructor(source, session) { + this.#source = source; + this.#session = session; } - const triggers = [PUSH2]; - const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}|${packet.node}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - packet.node, - PUSH2, - index2.toString() - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: packet.node, - langgraph_triggers: triggers, - langgraph_path: taskPath.slice(0, 3), - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const proc = processes[packet.node]; - const node = proc.getNode(); - if (node !== undefined) { - if (proc.metadata !== undefined) - metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; - return { - name: packet.node, - input: packet.args, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - tags: proc.tags, - store: extra.store ?? config2.store - }), { - runName: packet.node, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID2]: taskId, - [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { - name: packet.node, - writes, - triggers, - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP2]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: packet.args, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP2], - namespaceHash: XXH32(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace - } - }), - executionInfo - }, - triggers, - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH32((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), - ns: [ - CACHE_NS_WRITES2, - proc.name ?? "__dynamic__", - packet.node - ], - ttl: proc.cachePolicy.ttl - } : undefined, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else - return { - id: taskId, - name: packet.node, - interrupts: [], - path: taskPath - }; - } else if (taskPath[0] === "__pregel_pull") { - const name = taskPath[1].toString(); - const proc = processes[name]; - if (proc === undefined) - return; - if (pendingWrites?.length) { - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL2, - name - ]), checkpoint.id); - if (pendingWrites.some((w) => w[0] === taskId && w[1] !== "__error__")) + #processEvent(event) { + if (event.method !== "tools") return; + const tools = event; + const data = tools.params.data; + const toolCallId = data.tool_call_id; + if (data.tool_name === "task" && data.event === "tool-started") { + const rawInput = data.input; + const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {}; + const name = input.subagent_type ?? "unknown"; + const description = input.description ?? ""; + let resolveTaskInput; + let resolveOutput; + let rejectOutput; + const taskInput = new Promise((r) => { + resolveTaskInput = r; + }); + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; + }); + resolveTaskInput(description); + this.#pending.set(toolCallId, { + resolveOutput, + rejectOutput + }); + return new SubagentHandle(name, toolCallId, [...tools.params.namespace], taskInput, output, this.#session); + } + if (toolCallId) { + const pending = this.#pending.get(toolCallId); + if (pending) { + if (data.event === "tool-finished") { + pending.resolveOutput(data.output); + this.#pending.delete(toolCallId); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + pending.rejectOutput(new Error(message)); + this.#pending.delete(toolCallId); + } + } + } } - const nullVersion = getNullChannelVersion2(checkpoint.channel_versions); - if (nullVersion === undefined) - return; - const seen = checkpoint.versions_seen[name] ?? {}; - const trigger = proc.triggers.find((chan) => { - if (!channels[chan].isAvailable()) - return false; - return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); - }); - if (trigger !== undefined) { - const val = _procInput2(proc, channels, forExecution); - if (val === undefined) + #start() { + if (this.#sourcePump) return; - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}|${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL2, - [trigger] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}:${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: name, - langgraph_triggers: [trigger], - langgraph_path: taskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace, - checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const node = proc.getNode(); - if (node !== undefined) { - if (proc.metadata !== undefined) - metadata = { - ...metadata, - ...proc.metadata + this.#sourcePump = (async () => { + for await (const event of this.#source) { + const handle = this.#processEvent(event); + if (!handle) + continue; + const waiter = this.#waiters.shift(); + if (waiter) + waiter({ + done: false, + value: handle + }); + else + this.#queue.push(handle); + } + this.#closed = true; + for (const pending of this.#pending.values()) + pending.resolveOutput(undefined); + this.#pending.clear(); + while (this.#waiters.length > 0) + this.#waiters.shift()?.({ + done: true, + value: undefined + }); + })(); + } + async close() { + this.#closed = true; + await this.#source.unsubscribe(); + } + [Symbol.asyncIterator]() { + this.#start(); + return { + next: async () => { + if (this.#queue.length > 0) + return { + done: false, + value: this.#queue.shift() }; - const writes = []; - const executionInfo = { - checkpointId: checkpoint.id, - checkpointNs: taskCheckpointNamespace, - taskId, - threadId: configurable.thread_id, - runId: config2.runId != null ? String(config2.runId) : undefined, - nodeAttempt: 1 - }; + if (this.#closed) + return { + done: true, + value: undefined + }; + return await new Promise((resolve2) => { + this.#waiters.push(resolve2); + }); + }, + return: async () => { + await this.close(); return { - name, - input: val, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: { - ...patchConfig(mergeConfigs(config2, { - metadata, - tags: proc.tags, - store: extra.store ?? config2.store - }), { - runName: name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID2]: taskId, - [CONFIG_KEY_SEND2]: (writes_) => _localWrite2((items) => { - writes.push(...items); - }, processes, writes_), - [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, { - name, - writes, - triggers: [trigger], - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER2]: checkpointer ?? configurable["__pregel_checkpointer"], - [CONFIG_KEY_CHECKPOINT_MAP2]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP2], - [parentNamespace]: checkpoint.id - }, - [CONFIG_KEY_SCRATCHPAD2]: _scratchpad2({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: val, - resumeMap: config2.configurable?.[CONFIG_KEY_RESUME_MAP2], - namespaceHash: XXH32(taskCheckpointNamespace) - }), - [CONFIG_KEY_PREVIOUS_STATE2]: checkpoint.channel_values[PREVIOUS2], - checkpoint_id: undefined, - checkpoint_ns: taskCheckpointNamespace - } - }), - executionInfo - }, - triggers: [trigger], - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH32((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), - ns: [ - CACHE_NS_WRITES2, - proc.name ?? "__dynamic__", - name - ], - ttl: proc.cachePolicy.ttl - } : undefined, - id: taskId, - path: taskPath, - writers: proc.getWriters() + done: true, + value: undefined }; } - } else - return { - id: taskId, - name, - interrupts: [], - path: taskPath - }; - } - } -} -function _procInput2(proc, channels, forExecution) { - let val; - if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { - val = {}; - for (const [k, chan] of Object.entries(proc.channels)) - if (proc.triggers.includes(chan)) - try { - val[k] = readChannel2(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError2.unminifiable_name) - return; - else - throw e; - } - else if (chan in channels) - try { - val[k] = readChannel2(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError2.unminifiable_name) - continue; - else - throw e; - } - } else if (Array.isArray(proc.channels)) { - let successfulRead = false; - for (const chan of proc.channels) - try { - val = readChannel2(channels, chan, false); - successfulRead = true; - break; - } catch (e) { - if (e.name === EmptyChannelError2.unminifiable_name) - continue; - else - throw e; - } - if (!successfulRead) - return; - } else - throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); - if (forExecution && proc.mapper !== undefined) - val = proc.mapper(val); - return val; -} -function sanitizeUntrackedValuesInSend2(packet, channels) { - if (typeof packet.args !== "object" || packet.args === null) - return packet; - const sanitizedArg = {}; - for (const [key, value] of Object.entries(packet.args)) { - const channel = channels[key]; - if (!channel || channel.lc_graph_name !== "UntrackedValue") - sanitizedArg[key] = value; - } - return new Send2(packet.node, sanitizedArg); -} -function _scratchpad2({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { - const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__")?.[2]; - const scratchpad = { - callCounter: 0, - interruptCounter: -1, - resume: (() => { - const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === "__resume__").flatMap(([_writeTaskId, _chan, resume]) => resume); - if (resumeMap != null && namespaceHash in resumeMap) { - const mappedResume = resumeMap[namespaceHash]; - result.push(mappedResume); - } - return result; - })(), - nullResume, - subgraphCounter: 0, - currentTaskInput, - consumeNullResume: () => { - if (scratchpad.nullResume) { - delete scratchpad.nullResume; - pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === "00000000-0000-0000-0000-000000000000" && chan === "__resume__"), 1); - return nullResume; - } + }; } }; - return scratchpad; -} -var increment2 = (current) => { - return current !== undefined ? current + 1 : 1; -}, IGNORE2; -var init_algo2 = __esm(() => { - init_constants8(); - init_errors10(); - init_base17(); - init_hash4(); - init_io2(); - init_types13(); - init_utils18(); - init_call2(); - init_dist3(); - init_runnables(); - IGNORE2 = new Set([ - NO_WRITES2, - PUSH2, - RESUME3, - INTERRUPT3, - RETURN2, - ERROR5 - ]); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/debug.js -function* mapDebugTasks2(tasks) { - for (const { id, name, input, config: config2, triggers, writes } of tasks) { - if (config2?.tags?.includes("langsmith:hidden")) - continue; - yield { - id, - name, - input, - triggers, - interrupts: writes.filter(([writeId, n4]) => { - return writeId === id && n4 === "__interrupt__"; - }).map(([, v]) => { - return v; - }) - }; - } -} -function isMultipleChannelWrite2(value) { - if (typeof value !== "object" || value === null) - return false; - return "$writes" in value && Array.isArray(value.$writes); -} -function mapTaskResultWrites2(writes) { - const result = {}; - for (const [channel, value] of writes) { - const strChannel = String(channel); - if (strChannel in result) { - const channelWrites = isMultipleChannelWrite2(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; - channelWrites.push(value); - result[strChannel] = { $writes: channelWrites }; - } else - result[strChannel] = value; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/subgraphs.js +var SubgraphHandle = class { + name; + index; + namespace; + cause; + graphName; + toolStartedEvent; + #session; + #messagesIterable; + #valuesProjection; + #toolCallsIterable; + #subgraphsIterable; + #subagentsIterable; + #outputPromise; + #mediaDispatcherStarted = false; + #audioBuffer; + #imagesBuffer; + #videoBuffer; + #filesBuffer; + constructor(name, index2, namespace, session, options) { + this.name = name; + this.index = index2; + this.namespace = namespace; + this.cause = options?.cause; + this.graphName = options?.graphName; + this.toolStartedEvent = options?.toolStartedEvent; + this.#session = session; } - return result; -} -function* mapDebugTaskResults2(tasks, streamChannels) { - for (const [{ id, name, config: config2 }, writes] of tasks) { - if (config2?.tags?.includes("langsmith:hidden")) - continue; - yield { - id, - name, - result: mapTaskResultWrites2(writes.filter(([channel]) => { - return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; - })), - interrupts: writes.filter((w) => w[0] === INTERRUPT3).map((w) => w[1]) - }; + get messages() { + if (this.#messagesIterable) + return this.#messagesIterable; + const buffer = new MultiCursorBuffer; + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler; + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") + return; + const msg = assembler.consume(event); + if (msg) + buffer.push(msg); + }, () => buffer.close()); + return buffer; } -} -function* mapDebugCheckpoint2(config2, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { - function formatConfig(config3) { - const pyConfig = {}; - if (config3.callbacks != null) - pyConfig.callbacks = config3.callbacks; - if (config3.configurable != null) - pyConfig.configurable = config3.configurable; - if (config3.maxConcurrency != null) - pyConfig.max_concurrency = config3.maxConcurrency; - if (config3.metadata != null) - pyConfig.metadata = config3.metadata; - if (config3.recursionLimit != null) - pyConfig.recursion_limit = config3.recursionLimit; - if (config3.runId != null) - pyConfig.run_id = config3.runId; - if (config3.runName != null) - pyConfig.run_name = config3.runName; - if (config3.tags != null) - pyConfig.tags = config3.tags; - return pyConfig; + get values() { + if (this.#valuesProjection) + return this.#valuesProjection; + const buffer = new MultiCursorBuffer; + let lastValue; + let resolveOutput; + const outputPromise = new Promise((resolve2) => { + resolveOutput = resolve2; + }); + this.#outputPromise = outputPromise; + const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); + this.#valuesProjection = projection; + this.#startProjection(["values"], (event) => { + if (event.method !== "values") + return; + const data = event.params.data; + lastValue = data; + buffer.push(data); + }, () => { + resolveOutput(lastValue); + buffer.close(); + }); + return projection; } - const parentNs = config2.configurable?.checkpoint_ns; - const taskStates = {}; - for (const task2 of tasks) { - if (!((task2.subgraphs?.length) ? task2.subgraphs : [task2.proc]).find(findSubgraphPregel2)) - continue; - let taskNs = `${task2.name}:${task2.id}`; - if (parentNs) - taskNs = `${parentNs}|${taskNs}`; - taskStates[task2.id] = { configurable: { - thread_id: config2.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - } - yield { - config: formatConfig(config2), - values: readChannels2(channels, streamChannels), - metadata, - next: tasks.map((task2) => task2.name), - tasks: tasksWithWrites2(tasks, pendingWrites, taskStates, outputKeys), - parentConfig: parentConfig ? formatConfig(parentConfig) : undefined - }; -} -function tasksWithWrites2(tasks, pendingWrites, states, outputKeys) { - return tasks.map((task2) => { - const error52 = pendingWrites.find(([id, n4]) => id === task2.id && n4 === "__error__")?.[2]; - const interrupts = pendingWrites.filter(([id, n4]) => id === task2.id && n4 === "__interrupt__").map(([, , v]) => v); - const result = (() => { - if (error52 || interrupts.length || !pendingWrites.length) + get toolCalls() { + if (this.#toolCallsIterable) + return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer; + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler; + this.#startProjection(["tools"], (event) => { + if (event.method !== "tools") return; - const idx = pendingWrites.findIndex(([tid, n4]) => tid === task2.id && n4 === "__return__"); - if (idx >= 0) - return pendingWrites[idx][2]; - if (typeof outputKeys === "string") - return pendingWrites.find(([tid, n4]) => tid === task2.id && n4 === outputKeys)?.[2]; - if (Array.isArray(outputKeys)) { - const results = pendingWrites.filter(([tid, n4]) => tid === task2.id && outputKeys.includes(n4)).map(([, n4, v]) => [n4, v]); - if (!results.length) - return; - return mapTaskResultWrites2(results); - } + const tc = assembler.consume(event); + if (tc) + buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; + } + get subgraphs() { + if (this.#subgraphsIterable) + return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer; + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#session.subscribe({ + channels: ["lifecycle", "tools"], + namespaces: [this.namespace] + }), this.#session, this.namespace); + for await (const sub of discovery) + buffer.push(sub); + buffer.close(); })(); - if (error52) - return { - id: task2.id, - name: task2.name, - path: task2.path, - error: error52, - interrupts, - result - }; - const taskState = states?.[task2.id]; - return { - id: task2.id, - name: task2.name, - path: task2.path, - interrupts, - ...taskState !== undefined ? { state: taskState } : {}, - result - }; - }); -} -function printStepCheckpoint2(step, channels, whitelist) { - console.log([ - `${wrap3(COLORS_MAP2.blue, `[${step}:checkpoint]`)}`, - `\x1B[1m State at the end of step ${step}:\x1B[0m -`, - JSON.stringify(readChannels2(channels, whitelist), null, 2) - ].join("")); -} -function printStepTasks2(step, nextTasks) { - const nTasks = nextTasks.length; - console.log([ - `${wrap3(COLORS_MAP2.blue, `[${step}:tasks]`)}`, - `\x1B[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1B[0m -`, - nextTasks.map((task2) => `- ${wrap3(COLORS_MAP2.green, String(task2.name))} -> ${JSON.stringify(task2.input, null, 2)}`).join(` -`) - ].join("")); -} -function printStepWrites2(step, writes, whitelist) { - const byChannel = {}; - for (const [channel, value] of writes) - if (whitelist.includes(channel)) { - if (!byChannel[channel]) - byChannel[channel] = []; - byChannel[channel].push(value); - } - console.log([ - `${wrap3(COLORS_MAP2.blue, `[${step}:writes]`)}`, - `\x1B[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1B[0m -`, - Object.entries(byChannel).map(([name, vals]) => `- ${wrap3(COLORS_MAP2.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join(` -`) - ].join("")); -} -var COLORS_MAP2, wrap3 = (color2, text) => `${color2.start}${text}${color2.end}`; -var init_debug2 = __esm(() => { - init_constants8(); - init_io2(); - init_subgraph2(); - COLORS_MAP2 = { - blue: { - start: "\x1B[34m", - end: "\x1B[0m" - }, - green: { - start: "\x1B[32m", - end: "\x1B[0m" - }, - yellow: { - start: "\x1B[33;1m", - end: "\x1B[0m" - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/stream.js -function _stringifyAsDict2(obj) { - return JSON.stringify(obj, function(key, value) { - const rawValue2 = this[key]; - if (rawValue2 != null && typeof rawValue2 === "object" && "toDict" in rawValue2 && typeof rawValue2.toDict === "function") { - const { type, data } = rawValue2.toDict(); - return { - ...data, - type - }; - } - return value; - }); -} -function _serializeError2(error52) { - if (error52 instanceof Error) - return { - error: error52.name, - message: error52.message - }; - return { - error: "Error", - message: JSON.stringify(error52) - }; -} -function _isRunnableConfig2(config2) { - if (typeof config2 !== "object" || config2 == null) - return false; - return "configurable" in config2 && typeof config2.configurable === "object" && config2.configurable != null; -} -function _extractCheckpointFromConfig2(config2) { - if (!_isRunnableConfig2(config2) || !config2.configurable.thread_id) - return null; - return { - thread_id: config2.configurable.thread_id, - checkpoint_ns: config2.configurable.checkpoint_ns || "", - checkpoint_id: config2.configurable.checkpoint_id || null, - checkpoint_map: config2.configurable.checkpoint_map || null - }; -} -function _serializeConfig2(config2) { - if (_isRunnableConfig2(config2)) { - const configurable = Object.fromEntries(Object.entries(config2.configurable).filter(([key]) => !key.startsWith("__"))); - const newConfig = { - ...config2, - configurable - }; - delete newConfig.callbacks; - return newConfig; + return buffer; } - return config2; -} -function _serializeCheckpoint2(payload) { - const result = { - ...payload, - checkpoint: _extractCheckpointFromConfig2(payload.config), - parent_checkpoint: _extractCheckpointFromConfig2(payload.parentConfig), - config: _serializeConfig2(payload.config), - parent_config: _serializeConfig2(payload.parentConfig), - tasks: payload.tasks.map((task2) => { - if (_isRunnableConfig2(task2.state)) { - const checkpoint = _extractCheckpointFromConfig2(task2.state); - if (checkpoint != null) { - const cloneTask = { - ...task2, - checkpoint - }; - delete cloneTask.state; - return cloneTask; - } - } - return task2; - }) - }; - delete result.parentConfig; - return result; -} -function toEventStream2(stream2) { - const encoder2 = new TextEncoder; - return new ReadableStream({ async start(controller) { - const enqueueChunk = (sse) => { - controller.enqueue(encoder2.encode(`event: ${sse.event} -data: ${_stringifyAsDict2(sse.data)} - -`)); - }; - try { - for await (const payload of stream2) { - const [ns3, mode, chunk] = payload; - let data = chunk; - if (mode === "debug") { - const debugChunk = chunk; - if (debugChunk.type === "checkpoint") - data = { - ...debugChunk, - payload: _serializeCheckpoint2(debugChunk.payload) - }; - } - if (mode === "checkpoints") - data = _serializeCheckpoint2(chunk); - enqueueChunk({ - event: ns3?.length ? `${mode}|${ns3.join("|")}` : mode, - data - }); - } - } catch (error52) { - enqueueChunk({ - event: "error", - data: _serializeError2(error52) + get subagents() { + if (this.#subagentsIterable) + return this.#subagentsIterable; + const buffer = new MultiCursorBuffer; + this.#subagentsIterable = buffer; + (async () => { + const rawHandle = await this.#session.subscribe({ + channels: ["tools", "lifecycle"], + namespaces: [this.namespace] }); - } - controller.close(); - } }); -} -var IterableReadableStreamWithAbortSignal2, IterableReadableWritableStream2, StreamToolsHandler2; -var init_stream12 = __esm(() => { - init_constants8(); - init_stream(); - init_base2(); - IterableReadableStreamWithAbortSignal2 = class extends IterableReadableStream { - _abortController; - _innerReader; - constructor(readableStream, abortController) { - const reader = readableStream.getReader(); - const ac = abortController ?? new AbortController; - super({ start(controller) { - return pump3(); - function pump3() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump3(); - }); - } - } }); - this._abortController = ac; - this._innerReader = reader; - } - async cancel(reason) { - this._abortController.abort(reason); - this._innerReader.releaseLock(); - } - get signal() { - return this._abortController.signal; - } - }; - IterableReadableWritableStream2 = class extends IterableReadableStream { - modes; - controller; - passthroughFn; - _closed = false; - get closed() { - return this._closed; - } - constructor(params) { - let streamControllerPromiseResolver; - const streamControllerPromise = new Promise((resolve2) => { - streamControllerPromiseResolver = resolve2; + const { SubagentDiscoveryHandle: Discovery } = await Promise.resolve().then(() => (init_subagents(), exports_subagents)); + const discovery = new Discovery(rawHandle, this.#session); + for await (const sub of discovery) + buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; + } + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; + } + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; + } + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + get output() { + this.values; + return this.#outputPromise; + } + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) + return; + this.#mediaDispatcherStarted = true; + const audio = new MultiCursorBuffer; + const images = new MultiCursorBuffer; + const video = new MultiCursorBuffer; + const files = new MultiCursorBuffer; + this.#audioBuffer = audio; + this.#imagesBuffer = images; + this.#videoBuffer = video; + this.#filesBuffer = files; + const assembler = new MediaAssembler({ + onAudio: (m) => audio.push(m), + onImage: (m) => images.push(m), + onVideo: (m) => video.push(m), + onFile: (m) => files.push(m) + }); + this.#startProjection(["messages"], (event) => { + if (event.method !== "messages") + return; + assembler.consume(event); + }, () => { + assembler.close(); + audio.close(); + images.close(); + video.close(); + files.close(); + }); + } + subscribe(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) + return this.#session.subscribe({ + ...paramsOrChannels, + namespaces: paramsOrChannels.namespaces ?? [this.namespace] }); - super({ start: (controller) => { - streamControllerPromiseResolver(controller); - } }); - streamControllerPromise.then((controller) => { - this.controller = controller; + return this.#session.subscribe(paramsOrChannels, { + ...options, + namespaces: options.namespaces ?? [this.namespace] + }); + } + async#startProjection(channels, onEvent, onDone) { + try { + const rawHandle = await this.#session.subscribe({ + channels, + namespaces: [this.namespace] }); - this.passthroughFn = params.passthroughFn; - this.modes = params.modes; - } - push(chunk) { - this.passthroughFn?.(chunk); - this.controller.enqueue(chunk); + for await (const event of rawHandle) + onEvent(event); + } finally { + onDone(); } - close() { - try { - this.controller.close(); - } catch {} finally { - this._closed = true; - } + } +}, SubgraphDiscoveryHandle; +var init_subgraphs3 = __esm(() => { + init_multi_cursor_buffer(); + init_tools4(); + init_messages8(); + init_media(); + SubgraphDiscoveryHandle = class { + #source; + #session; + #parentNamespace; + #discovered = /* @__PURE__ */ new Set; + #pendingToolStarts = /* @__PURE__ */ new Map; + #pendingToolCallHandles = /* @__PURE__ */ new Map; + #queue = []; + #waiters = []; + #sourcePump; + #closed = false; + constructor(source, session, parentNamespace = []) { + this.#source = source; + this.#session = session; + this.#parentNamespace = parentNamespace; } - error(e) { - this.controller.error(e); + #emit(handle) { + const waiter = this.#waiters.shift(); + if (waiter) + waiter({ + done: false, + value: handle + }); + else + this.#queue.push(handle); } - }; - StreamToolsHandler2 = class extends BaseCallbackHandler { - name = "StreamToolsHandler"; - streamFn; - runs = {}; - constructor(streamFn) { - super(); - this.streamFn = streamFn; + #processToolEvent(event) { + if (event.method !== "tools") + return false; + const tools = event; + const data = tools.params.data; + if (data.event !== "tool-started") + return true; + const toolCallId = data.tool_call_id; + if (!toolCallId) + return true; + const pendingHandle = this.#pendingToolCallHandles.get(toolCallId); + if (pendingHandle) { + pendingHandle.toolStartedEvent = tools; + this.#pendingToolCallHandles.delete(toolCallId); + return true; + } + this.#pendingToolStarts.set(toolCallId, tools); + return true; } - handleToolStart(_tool, input, runId, _parentRunId, tags, metadata, runName, toolCallId) { - if (!metadata || tags && tags.includes("langsmith:hidden")) + #processEvent(event) { + if (this.#processToolEvent(event)) return; - const ns3 = metadata.langgraph_checkpoint_ns?.split("|") ?? []; - const info = { - ns: ns3, - toolCallId, - toolName: runName ?? "unknown", - input - }; - this.runs[runId] = info; - this.streamFn([ - ns3, - "tools", - { - event: "on_tool_start", - toolCallId: info.toolCallId, - name: info.toolName, - input - } - ]); - } - handleToolEvent(chunk, runId) { - const info = this.runs[runId]; - if (!info) + if (event.method !== "lifecycle") return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_event", - toolCallId: info.toolCallId, - name: info.toolName, - data: chunk + const lifecycle = event; + if (lifecycle.params.data.event !== "started") + return; + const ns3 = event.params.namespace; + if (ns3.length !== this.#parentNamespace.length + 1) + return; + if (!this.#parentNamespace.every((seg, i) => ns3[i] === seg)) + return; + const nsKey3 = ns3.join("/"); + if (this.#discovered.has(nsKey3)) + return; + this.#discovered.add(nsKey3); + const lastSegment = ns3[ns3.length - 1] ?? ""; + const colonIdx = lastSegment.lastIndexOf(":"); + let name; + let index2; + if (colonIdx >= 0) { + name = lastSegment.slice(0, colonIdx); + const suffix = lastSegment.slice(colonIdx + 1); + index2 = /^\d+$/.test(suffix) ? Number(suffix) : 0; + } else { + name = lastSegment; + index2 = 0; + } + const data = lifecycle.params.data; + const cause = data.cause && typeof data.cause === "object" ? data.cause : undefined; + let toolStartedEvent; + if (cause?.type === "toolCall") { + const toolCallId = cause.tool_call_id; + if (toolCallId) { + toolStartedEvent = this.#pendingToolStarts.get(toolCallId); + this.#pendingToolStarts.delete(toolCallId); } - ]); + } + const handle = new SubgraphHandle(name, index2, [...ns3], this.#session, { + cause, + graphName: data.graph_name, + toolStartedEvent + }); + if (cause?.type === "toolCall" && toolStartedEvent == null) { + const toolCallId = cause.tool_call_id; + if (toolCallId) + this.#pendingToolCallHandles.set(toolCallId, handle); + } + return handle; } - handleToolEnd(output, runId) { - const info = this.runs[runId]; - delete this.runs[runId]; - if (!info) + #start() { + if (this.#sourcePump) return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_end", - toolCallId: info.toolCallId, - name: info.toolName, - output + this.#sourcePump = (async () => { + for await (const event of this.#source) { + const handle = this.#processEvent(event); + if (!handle) + continue; + this.#emit(handle); } - ]); + this.#pendingToolStarts.clear(); + this.#pendingToolCallHandles.clear(); + this.#closed = true; + while (this.#waiters.length > 0) + this.#waiters.shift()?.({ + done: true, + value: undefined + }); + })(); } - handleToolError(err, runId) { - const info = this.runs[runId]; - delete this.runs[runId]; - if (!info) - return; - this.streamFn([ - info.ns, - "tools", - { - event: "on_tool_error", - toolCallId: info.toolCallId, - name: info.toolName, - error: err + async close() { + this.#closed = true; + await this.#source.unsubscribe(); + } + [Symbol.asyncIterator]() { + this.#start(); + return { + next: async () => { + if (this.#queue.length > 0) + return { + done: false, + value: this.#queue.shift() + }; + if (this.#closed) + return { + done: true, + value: undefined + }; + return await new Promise((resolve2) => { + this.#waiters.push(resolve2); + }); + }, + return: async () => { + await this.close(); + return { + done: true, + value: undefined + }; } - ]); + }; } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/loop.js -function createDuplexStream2(...streams) { - return new IterableReadableWritableStream2({ - passthroughFn: (value) => { - for (const stream2 of streams) - if (stream2.modes.has(value[1])) - stream2.push(value); - }, - modes: new Set(streams.flatMap((s) => Array.from(s.modes))) - }); +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/handles/index.js +var init_handles = __esm(() => { + init_tools4(); + init_subgraphs3(); + init_subagents(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/index.js +function coerceStateMessages(value) { + if (value == null || typeof value !== "object" || Array.isArray(value)) + return value; + const state = value; + const messages = state.messages; + if (!Array.isArray(messages) || messages.length === 0) + return value; + if (!messages.some((msg) => { + if (msg == null || typeof msg !== "object") + return false; + if (typeof msg.getType === "function") + return false; + const type = msg.type; + return typeof type === "string" && MESSAGE_LIKE_TYPES.has(type); + })) + return value; + return { + ...state, + messages: ensureMessageInstances(messages) + }; } -var INPUT_DONE2, INPUT_RESUMING2, DEFAULT_LOOP_LIMIT2 = 25, AsyncBatchedCache2, PregelLoop3 = class PregelLoop4 { - input; - output; - config; - checkpointer; - checkpointerGetNextVersion; - channels; - checkpoint; - checkpointIdSaved; - checkpointConfig; - checkpointMetadata; - checkpointNamespace; - checkpointPendingWrites = []; - checkpointPreviousVersions; - step; - stop; - durability; - outputKeys; - streamKeys; - nodes; - skipDoneTasks; - prevCheckpointConfig; - updatedChannels; - status = "pending"; - tasks = {}; - stream; - checkpointerPromises = /* @__PURE__ */ new Set; - isNested; - _checkpointerChainedPromise = Promise.resolve(); - _trackCheckpointerPromise(promise2) { - const tracked = promise2.then((value) => { - this.checkpointerPromises.delete(tracked); - return value; - }, (error52) => { - throw error52; - }); - this.checkpointerPromises.add(tracked); - } - store; - cache; - manager; - interruptAfter; - interruptBefore; - toInterrupt = []; - debug = false; - triggerToNodes; - get isResuming() { - let hasChannelVersions = false; - if ("__start__" in this.checkpoint.channel_versions) - hasChannelVersions = true; - else - for (const chan in this.checkpoint.channel_versions) - if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { - hasChannelVersions = true; - break; - } - const configIsResuming = this.config.configurable?.["__pregel_resuming"] !== undefined && this.config.configurable?.["__pregel_resuming"]; - const inputIsNullOrUndefined = this.input === null || this.input === undefined; - const inputIsCommandResuming = isCommand2(this.input) && this.input.resume != null; - const inputIsResuming = this.input === INPUT_RESUMING2; - const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== undefined && this.checkpointMetadata?.run_id !== undefined && this.config.metadata.run_id === this.checkpointMetadata?.run_id; - return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); - } - constructor(params) { - this.input = params.input; - this.checkpointer = params.checkpointer; - if (this.checkpointer !== undefined) - this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); - else - this.checkpointerGetNextVersion = increment2; - this.checkpoint = params.checkpoint; - this.checkpointMetadata = params.checkpointMetadata; - this.checkpointPreviousVersions = params.checkpointPreviousVersions; - this.channels = params.channels; - this.checkpointPendingWrites = params.checkpointPendingWrites; - this.step = params.step; - this.stop = params.stop; - this.config = params.config; - this.checkpointConfig = params.checkpointConfig; - this.isNested = params.isNested; - this.manager = params.manager; - this.outputKeys = params.outputKeys; - this.streamKeys = params.streamKeys; - this.nodes = params.nodes; - this.skipDoneTasks = params.skipDoneTasks; - this.store = params.store; - this.cache = params.cache ? new AsyncBatchedCache2(params.cache) : undefined; - this.stream = params.stream; - this.checkpointNamespace = params.checkpointNamespace; - this.prevCheckpointConfig = params.prevCheckpointConfig; - this.interruptAfter = params.interruptAfter; - this.interruptBefore = params.interruptBefore; - this.durability = params.durability; - this.debug = params.debug; - this.triggerToNodes = params.triggerToNodes; +function namespaceKey(ns3) { + return ns3.join("\x00"); +} +function maxSeq(current, next) { + if (next == null) + return current; + if (current == null) + return next; + return Math.max(current, next); +} +function isRootTerminalLifecycle(event) { + if (event.method !== "lifecycle") + return false; + if (event.params.namespace.length !== 0) + return false; + const data = event.params.data; + return data?.event != null && ROOT_TERMINAL_LIFECYCLE_EVENTS.has(data.event); +} +function namespaceListsEqual(a, b) { + if (a === b) + return true; + if (a === undefined || b === undefined) + return false; + if (a.length !== b.length) + return false; + const aKeys = /* @__PURE__ */ new Set; + for (const ns3 of a) + aKeys.add(namespaceKey(ns3)); + for (const ns3 of b) + if (!aKeys.has(namespaceKey(ns3))) + return false; + return true; +} +function filterEqual(a, b) { + if (a === b) + return true; + if (a == null || b == null) + return false; + if (a.channels.length !== b.channels.length) + return false; + const aChannels = new Set(a.channels); + for (const ch of b.channels) + if (!aChannels.has(ch)) + return false; + if (!namespaceListsEqual(a.namespaces, b.namespaces)) + return false; + if ((a.depth ?? null) !== (b.depth ?? null)) + return false; + return true; +} +function isPrefix(prefix, candidate) { + if (prefix.length > candidate.length) + return false; + for (let i = 0;i < prefix.length; i += 1) + if (prefix[i] !== candidate[i]) + return false; + return true; +} +function filterCovers(coverer, target) { + const covererChannels = new Set(coverer.channels); + for (const ch of target.channels) + if (!covererChannels.has(ch)) + return false; + const covererDepth = coverer.depth; + const targetDepth = target.depth; + if (coverer.namespaces == null) { + if (covererDepth == null) + return true; + if (targetDepth == null) + return false; + return targetDepth <= covererDepth; } - static async initialize(params) { - let { config: config2, stream: stream2 } = params; - if (stream2 !== undefined && config2.configurable?.["__pregel_stream"] !== undefined) - stream2 = createDuplexStream2(stream2, config2.configurable[CONFIG_KEY_STREAM2]); - const skipDoneTasks = config2.configurable ? !("checkpoint_id" in config2.configurable) : true; - const scratchpad = config2.configurable?.[CONFIG_KEY_SCRATCHPAD2]; - if (config2.configurable && scratchpad) { - if (scratchpad.subgraphCounter > 0) - config2 = patchConfigurable4(config2, { [CONFIG_KEY_CHECKPOINT_NS2]: [config2.configurable[CONFIG_KEY_CHECKPOINT_NS2], scratchpad.subgraphCounter.toString()].join("|") }); - scratchpad.subgraphCounter += 1; + if (target.namespaces == null) + return false; + for (const tp of target.namespaces) + if (!coverer.namespaces.some((cp) => { + if (!isPrefix(cp, tp)) + return false; + if (covererDepth == null) + return true; + if (targetDepth == null) + return false; + return tp.length - cp.length + targetDepth <= covererDepth; + })) + return false; + return true; +} +function normalizeSubscribeParams(paramsOrChannels, options = {}) { + if (typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels) + return paramsOrChannels; + const channels = Array.isArray(paramsOrChannels) ? [...paramsOrChannels] : [paramsOrChannels]; + return { + ...options, + channels + }; +} +function foldForkFromIntoConfig(params) { + const { forkFrom, ...rest } = params; + if (typeof forkFrom !== "string" || forkFrom.length === 0) + return rest; + const config3 = rest.config != null && typeof rest.config === "object" ? rest.config : {}; + const configurable = config3.configurable != null && typeof config3.configurable === "object" ? config3.configurable : {}; + return { + ...rest, + config: { + ...config3, + configurable: { + ...configurable, + checkpoint_id: forkFrom + } } - const isNested = CONFIG_KEY_READ2 in (config2.configurable ?? {}); - if (!isNested && config2.configurable?.checkpoint_ns !== undefined && config2.configurable?.checkpoint_ns !== "") - config2 = patchConfigurable4(config2, { - checkpoint_ns: "", - checkpoint_id: undefined + }; +} +var MESSAGE_LIKE_TYPES, ROOT_TERMINAL_LIFECYCLE_EVENTS, SubscriptionHandle, ThreadStream = class { + threadId; + ordering = {}; + run; + agent; + input; + state; + interrupted = false; + interrupts = []; + assistantId; + #nextCommandId; + #transportAdapter; + #pending = /* @__PURE__ */ new Map; + #subscriptions = /* @__PURE__ */ new Map; + #seenEventIds = /* @__PURE__ */ new Set; + #headlessInterruptsAwaitingTerminal = /* @__PURE__ */ new Set; + #closed = false; + #opened = false; + #openPromise; + #sharedStream = null; + #sharedStreamFilter = null; + #rotationState = "idle"; + #pendingSubResolves = []; + #terminalPauseTimer; + #terminalPauseSeq; + #lifecycleSubId = null; + #lifecycleStartPromise; + #runStartReady = null; + #lifecycleWatcherHandle = null; + #lifecycleWatcherStartPromise; + #onEventListeners = /* @__PURE__ */ new Set; + #messagesIterable; + #valuesProjection; + #toolCallsIterable; + #subgraphsIterable; + #subagentsIterable; + #outputPromise; + #extensionsProxy; + #extensionsCache = /* @__PURE__ */ new Map; + #extensionsDispatcherStarted = false; + #extensionsEnded = false; + #extensionsEvents = []; + #extensionsEventListeners = []; + #extensionsEndListeners = []; + #mediaDispatcherStarted = false; + #mediaAssembler; + #mediaHandles = /* @__PURE__ */ new Set; + #audioBuffer = new MultiCursorBuffer; + #imagesBuffer = new MultiCursorBuffer; + #videoBuffer = new MultiCursorBuffer; + #filesBuffer = new MultiCursorBuffer; + #fetchOption; + constructor(transportAdapter, options) { + if (!options?.assistantId) + throw new Error("ThreadStream requires an assistantId option."); + this.#transportAdapter = transportAdapter; + this.threadId = transportAdapter.threadId; + this.assistantId = options.assistantId; + this.#nextCommandId = options.startingCommandId ?? 1; + this.#fetchOption = options.fetch; + this.run = { start: async (params) => { + this.#prepareForNextRun(); + return await this.#withRunStartGate(() => { + this.#ensureLifecycleTracking(); + this.values; + return this.#send("run.start", { + ...foldForkFromIntoConfig(params), + assistant_id: this.assistantId + }); }); - let checkpointConfig = config2; - if (config2.configurable?.["checkpoint_map"] !== undefined && config2.configurable?.["checkpoint_map"]?.[config2.configurable?.checkpoint_ns]) - checkpointConfig = patchConfigurable4(config2, { checkpoint_id: config2.configurable[CONFIG_KEY_CHECKPOINT_MAP2][config2.configurable?.checkpoint_ns] }); - const checkpointNamespace = config2.configurable?.checkpoint_ns?.split("|") ?? []; - const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { - config: config2, - checkpoint: emptyCheckpoint(), - metadata: { - source: "input", - step: -2, - parents: {} + } }; + this.agent = { getTree: async (params = {}) => await this.#send("agent.getTree", params) }; + this.input = { + respond: async (params) => { + this.#prepareForNextRun(); + this.#ensureLifecycleTracking(); + this.values; + await this.#send("input.respond", params); }, - pendingWrites: [] - }; - checkpointConfig = { - ...config2, - ...saved.config, - configurable: { - checkpoint_ns: "", - ...config2.configurable, - ...saved.config.configurable + inject: async (params) => { + await this.#send("input.inject", params); } }; - const prevCheckpointConfig = saved.parentConfig; - const checkpoint = copyCheckpoint(saved.checkpoint); - const checkpointMetadata = { ...saved.metadata }; - const checkpointPendingWrites = saved.pendingWrites ?? []; - const channels = emptyChannels2(params.channelSpecs, checkpoint); - const step = (checkpointMetadata.step ?? 0) + 1; - const stop = step + (config2.recursionLimit ?? DEFAULT_LOOP_LIMIT2) + 1; - const checkpointPreviousVersions = { ...checkpoint.channel_versions }; - const store = params.store ? new AsyncBatchedStore(params.store) : undefined; - if (store) - await store.start(); - return new PregelLoop4({ - input: params.input, - config: config2, - checkpointer: params.checkpointer, - checkpoint, - checkpointMetadata, - checkpointConfig, - prevCheckpointConfig, - checkpointNamespace, - channels, - isNested, - manager: params.manager, - skipDoneTasks, - step, - stop, - checkpointPreviousVersions, - checkpointPendingWrites, - outputKeys: params.outputKeys ?? [], - streamKeys: params.streamKeys ?? [], - nodes: params.nodes, - stream: stream2, - store, - cache: params.cache, - interruptAfter: params.interruptAfter, - interruptBefore: params.interruptBefore, - durability: params.durability, - debug: params.debug, - triggerToNodes: params.triggerToNodes - }); - } - _checkpointerPutAfterPrevious(input) { - this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { - return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); - }); - this._trackCheckpointerPromise(this._checkpointerChainedPromise); + this.state = { + get: async (params) => await this.#send("state.get", params), + listCheckpoints: async (params) => await this.#send("state.listCheckpoints", params), + fork: async (params) => await this.#send("state.fork", params) + }; + if (this.#transportAdapter.openEventStream == null) + this.#consumeEvents(); } - putWrites(taskId, writes) { - let writesCopy = writes; - if (writesCopy.length === 0) + async#ensureOpen() { + if (this.#opened) return; - if (writesCopy.every(([key]) => (key in WRITES_IDX_MAP))) - writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); - let hasUntrackedChannels = false; - for (const key in this.channels) - if (Object.prototype.hasOwnProperty.call(this.channels, key)) { - if (this.channels[key].lc_graph_name === "UntrackedValue") { - hasUntrackedChannels = true; - break; - } - } - let writesToSave = writesCopy; - if (hasUntrackedChannels) - writesToSave = writesCopy.filter(([c]) => { - const channel = this.channels[c]; - return !channel || channel.lc_graph_name !== "UntrackedValue"; - }).map(([c, v]) => { - if (c === "__pregel_tasks" && _isSend2(v)) - return [c, sanitizeUntrackedValuesInSend2(v, this.channels)]; - return [c, v]; + if (this.#openPromise == null) + this.#openPromise = this.#transportAdapter.open().then(() => { + this.#opened = true; }); - this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); - for (const [c, v] of writesToSave) - this.checkpointPendingWrites.push([ - taskId, - c, - v - ]); - const config2 = patchConfigurable4(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID2]: this.checkpoint.id - }); - if (this.durability !== "exit" && this.checkpointer != null) - this._trackCheckpointerPromise(this.checkpointer.putWrites(config2, writesToSave, taskId)); - if (this.tasks) - this._outputWrites(taskId, writesCopy); - if (!writes.length || !this.cache || !this.tasks) + await this.#openPromise; + } + #lifecycleChannels() { + return ["lifecycle", "input"]; + } + #ensureLifecycleTracking() { + if (this.#lifecycleStartPromise != null) return; - const task2 = this.tasks[taskId]; - if (task2 == null || task2.cache_key == null) + this.#lifecycleStartPromise = (async () => { + this.#lifecycleSubId = (await this.#subscribeRaw({ channels: this.#lifecycleChannels() })).subscriptionId; + })().catch(() => { return; - if (writes[0][0] === "__error__" || writes[0][0] === "__interrupt__") + }); + } + async#withRunStartGate(operation) { + let resolveGate; + let rejectGate; + const gate = new Promise((resolve2, reject) => { + resolveGate = resolve2; + rejectGate = reject; + }); + this.#runStartReady = gate; + gate.catch(() => { return; - this.cache.set([{ - key: [task2.cache_key.ns, task2.cache_key.key], - value: task2.writes, - ttl: task2.cache_key.ttl - }]); + }); + try { + const result = await operation(); + resolveGate(); + return result; + } catch (err) { + rejectGate(err); + throw err; + } finally { + if (this.#runStartReady === gate) + this.#runStartReady = null; + } } - _outputWrites(taskId, writes, cached2 = false) { - const task2 = this.tasks[taskId]; - if (task2 !== undefined) { - if (task2.config !== undefined && (task2.config.tags ?? []).includes("langsmith:hidden")) - return; - if (writes.length > 0) { - if (writes[0][0] === "__interrupt__") { - if (task2.path?.[0] === "__pregel_push" && task2.path?.[task2.path.length - 1] === true) - return; - const interruptWrites = writes.filter((w) => w[0] === INTERRUPT3).flatMap((w) => w[1]); - this._emit([["updates", { [INTERRUPT3]: interruptWrites }], ["values", { [INTERRUPT3]: interruptWrites }]]); - } else if (writes[0][0] !== "__error__") - this._emit(gatherIteratorSync2(prefixGenerator2(mapOutputUpdates2(this.outputKeys, [[task2, writes]], cached2), "updates"))); - } - if (!cached2) - this._emit(gatherIteratorSync2(prefixGenerator2(mapDebugTaskResults2([[task2, writes]], this.streamKeys), "tasks"))); + #prepareForNextRun(respondedInterruptId) { + this.interrupted = false; + if (respondedInterruptId != null) { + const respondedIds = new Set(Array.isArray(respondedInterruptId) ? respondedInterruptId : [respondedInterruptId]); + for (let index2 = this.interrupts.length - 1;index2 >= 0; index2 -= 1) + if (respondedIds.has(this.interrupts[index2].interruptId)) + this.interrupts.splice(index2, 1); + } else + this.interrupts.length = 0; + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = undefined; } + this.#terminalPauseSeq = undefined; + for (const [id, subscription] of this.#subscriptions) + if (id !== this.#lifecycleSubId) + subscription.resume(); } - async _matchCachedWrites() { - if (!this.cache) - return []; - const matched = []; - const serializeKey = ([ns3, key]) => { - return `ns:${ns3.join(",")}|key:${key}`; - }; - const keys = []; - const keyMap = {}; - for (const task2 of Object.values(this.tasks)) - if (task2.cache_key != null && !task2.writes.length) { - keys.push([task2.cache_key.ns, task2.cache_key.key]); - keyMap[serializeKey([task2.cache_key.ns, task2.cache_key.key])] = task2; - } - if (keys.length === 0) - return []; - const cache2 = await this.cache.get(keys); - for (const { key, value } of cache2) { - const task2 = keyMap[serializeKey(key)]; - if (task2 != null) { - task2.writes.push(...value); - matched.push({ - task: task2, - result: value - }); - } - } - return matched; + get messages() { + if (this.#messagesIterable) + return this.#messagesIterable; + const buffer = new MultiCursorBuffer; + this.#messagesIterable = buffer; + const assembler = new StreamingMessageAssembler; + this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "messages") + return; + const msg = assembler.consume(event); + if (msg) + buffer.push(toStreamingMessageHandle(msg)); + }, () => buffer.close()); + return buffer; } - async tick(params) { - if (this.store && !this.store.isRunning) - await this.store?.start(); - const { inputKeys = [] } = params; - if (this.status !== "pending") - throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); - if (![INPUT_DONE2, INPUT_RESUMING2].includes(this.input)) - await this._first(inputKeys); - else if (this.toInterrupt.length > 0) { - this.status = "interrupt_before"; - throw new GraphInterrupt2; - } else if (Object.values(this.tasks).every((task2) => task2.writes.length > 0)) { - const writes = Object.values(this.tasks).flatMap((t) => t.writes); - this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - const valuesOutput = await gatherIterator2(prefixGenerator2(mapOutputValues2(this.outputKeys, writes, this.channels), "values")); - this.checkpointPendingWrites = []; - await this._putCheckpoint({ source: "loop" }); - this._emitValuesWithCheckpointMeta(valuesOutput); - if (shouldInterrupt2(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { - this.status = "interrupt_after"; - throw new GraphInterrupt2; - } - if (this.config.configurable?.["__pregel_resuming"] !== undefined) - delete this.config.configurable?.[CONFIG_KEY_RESUMING2]; - } else - return false; - if (this.step > this.stop) { - this.status = "out_of_steps"; - return false; - } - this.tasks = _prepareNextTasks2(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { - step: this.step, - checkpointer: this.checkpointer, - isResuming: this.isResuming, - manager: this.manager, - store: this.store, - stream: this.stream, - triggerToNodes: this.triggerToNodes, - updatedChannels: this.updatedChannels + get values() { + if (this.#valuesProjection) + return this.#valuesProjection; + const buffer = new MultiCursorBuffer; + let lastValue; + let resolveOutput; + const outputPromise = new Promise((resolve2) => { + resolveOutput = resolve2; }); - if (this.checkpointer) - this._emit(await gatherIterator2(prefixGenerator2(mapDebugCheckpoint2(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); - if (Object.values(this.tasks).length === 0) { - this.status = "done"; - return false; - } - if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === "__error__" || k === "__interrupt__" || k === "__resume__") - continue; - const task2 = Object.values(this.tasks).find((t) => t.id === tid); - if (task2) - task2.writes.push([k, v]); + this.#outputPromise = outputPromise; + const projection = Object.assign(buffer, { then: (onfulfilled, onrejected) => outputPromise.then(onfulfilled, onrejected) }); + this.#valuesProjection = projection; + this.#startProjection(["values", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "values") + return; + const data = coerceStateMessages(event.params.data); + lastValue = data; + buffer.push(data); + }, () => { + resolveOutput(lastValue); + buffer.close(); + }); + return projection; + } + get toolCalls() { + if (this.#toolCallsIterable) + return this.#toolCallsIterable; + const buffer = new MultiCursorBuffer; + this.#toolCallsIterable = buffer; + const assembler = new ToolCallAssembler; + this.#startProjection(["tools", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "tools") + return; + const tc = assembler.consume(event); + if (tc) + buffer.push(toClientAssembledToolCall(tc)); + }, () => buffer.close()); + return buffer; + } + get subgraphs() { + if (this.#subgraphsIterable) + return this.#subgraphsIterable; + const buffer = new MultiCursorBuffer; + this.#subgraphsIterable = buffer; + (async () => { + const discovery = new SubgraphDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this, []); + for await (const sub of discovery) + buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + get subagents() { + if (this.#subagentsIterable) + return this.#subagentsIterable; + const buffer = new MultiCursorBuffer; + this.#subagentsIterable = buffer; + (async () => { + const discovery = new SubagentDiscoveryHandle(await this.#subscribeRaw({ channels: ["tools", ...this.#lifecycleChannels()] }), this); + for await (const sub of discovery) + buffer.push(sub); + buffer.close(); + })(); + return buffer; + } + get audio() { + this.#ensureMediaDispatcher(); + return this.#audioBuffer; + } + get images() { + this.#ensureMediaDispatcher(); + return this.#imagesBuffer; + } + get video() { + this.#ensureMediaDispatcher(); + return this.#videoBuffer; + } + get files() { + this.#ensureMediaDispatcher(); + return this.#filesBuffer; + } + get output() { + this.values; + return this.#outputPromise; + } + get extensions() { + if (this.#extensionsProxy) + return this.#extensionsProxy; + const cache2 = this.#extensionsCache; + const createExtension = (name) => this.#createExtension(name); + this.#extensionsProxy = new Proxy(Object.create(null), { + get: (_target, prop) => { + if (typeof prop !== "string") + return; + const cached3 = cache2.get(prop); + if (cached3) + return cached3; + const extension = createExtension(prop); + cache2.set(prop, extension); + return extension; + }, + has: (_target, prop) => typeof prop === "string" + }); + return this.#extensionsProxy; + } + #ensureExtensionsDispatcher() { + if (this.#extensionsDispatcherStarted) + return; + this.#extensionsDispatcherStarted = true; + this.#startProjection(["custom", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "custom") + return; + this.#extensionsEvents.push(event); + for (const listener of this.#extensionsEventListeners) + listener(event); + }, () => { + this.#extensionsEnded = true; + const listeners = this.#extensionsEndListeners.splice(0); + for (const listener of listeners) + listener(); + }, { endOnRootTerminal: true }); + } + #ensureMediaDispatcher() { + if (this.#mediaDispatcherStarted) + return; + this.#mediaDispatcherStarted = true; + const assembler = new MediaAssembler({ + fetch: this.#fetchOption, + onAudio: (m) => { + this.#mediaHandles.add(m); + this.#audioBuffer.push(m); + }, + onImage: (m) => { + this.#mediaHandles.add(m); + this.#imagesBuffer.push(m); + }, + onVideo: (m) => { + this.#mediaHandles.add(m); + this.#videoBuffer.push(m); + }, + onFile: (m) => { + this.#mediaHandles.add(m); + this.#filesBuffer.push(m); } - for (const task2 of Object.values(this.tasks)) - if (task2.writes.length > 0) - this._outputWrites(task2.id, task2.writes, true); - } - if (Object.values(this.tasks).every((task2) => task2.writes.length > 0)) - return this.tick({ inputKeys }); - if (shouldInterrupt2(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { - this.status = "interrupt_before"; - throw new GraphInterrupt2; - } - const debugOutput = await gatherIterator2(prefixGenerator2(mapDebugTasks2(Object.values(this.tasks)), "tasks")); - this._emit(debugOutput); - return true; + }); + this.#mediaAssembler = assembler; + this.#startProjection(["messages", ...this.#lifecycleChannels()], (event) => { + if (event.method !== "messages") + return; + assembler.consume(event); + }, () => { + assembler.close(); + this.#audioBuffer.close(); + this.#imagesBuffer.close(); + this.#videoBuffer.close(); + this.#filesBuffer.close(); + }); } - async finishAndHandleError(error52) { - if (this.durability === "exit" && (!this.isNested || typeof error52 !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(":")))) { - this._putCheckpoint(this.checkpointMetadata); - this._flushPendingWrites(); - } - const suppress = this._suppressInterrupt(error52); - if (suppress || error52 === undefined) - this.output = readChannels2(this.channels, this.outputKeys); - if (suppress) { - if (this.tasks !== undefined && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task2) => task2.writes.length > 0)) { - this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - this._emitValuesWithCheckpointMeta(gatherIteratorSync2(prefixGenerator2(mapOutputValues2(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); + #createExtension(name) { + this.#ensureExtensionsDispatcher(); + const buffer = new MultiCursorBuffer; + let lastValue; + let resolveFinal; + const finalPromise = new Promise((resolve2) => { + resolveFinal = resolve2; + }); + const handleEvent = (event) => { + const data = event.params.data; + if (data?.name !== name) + return; + lastValue = data.payload; + buffer.push(data.payload); + }; + for (const event of this.#extensionsEvents) + handleEvent(event); + this.#extensionsEventListeners.push(handleEvent); + const settle = () => { + resolveFinal(lastValue); + buffer.close(); + }; + if (this.#extensionsEnded) + settle(); + else + this.#extensionsEndListeners.push(settle); + return Object.assign(buffer, { then: (onfulfilled, onrejected) => finalPromise.then(onfulfilled, onrejected) }); + } + async#startProjection(channels, onEvent, onDone, options = {}) { + let endTimer; + let rawHandle; + try { + rawHandle = await this.#subscribeRaw({ channels }); + const handle = rawHandle; + for await (const event of handle) { + onEvent(event); + if (options.endOnRootTerminal && endTimer == null && isRootTerminalLifecycle(event)) + endTimer = setTimeout(() => { + endTimer = undefined; + handle.unsubscribe().catch(() => { + return; + }); + }, 0); } - if (isGraphInterrupt2(error52) && !error52.interrupts.length) - this._emit([["updates", { [INTERRUPT3]: [] }], ["values", { [INTERRUPT3]: [] }]]); + } catch {} finally { + if (endTimer != null) + clearTimeout(endTimer); + onDone(); } - return suppress; } - async acceptPush(task2, writeIdx, call4) { - if (this.interruptAfter?.length > 0 && shouldInterrupt2(this.checkpoint, this.interruptAfter, [task2])) { - this.toInterrupt.push(task2); - return; - } - const pushed = _prepareSingleTask2([ - PUSH2, - task2.path ?? [], - writeIdx, - task2.id, - call4 - ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task2.config ?? {}, true, { - step: this.step, - checkpointer: this.checkpointer, - manager: this.manager, - store: this.store, - stream: this.stream + async submitRun(params) { + this.#prepareForNextRun(); + return await this.#withRunStartGate(() => { + this.#startLifecycleWatcher(); + return this.#send("run.start", { + ...foldForkFromIntoConfig(params), + assistant_id: this.assistantId + }); }); - if (!pushed) + } + async respondInput(params) { + const respondedIds = "responses" in params ? params.responses.map((entry) => entry.interrupt_id) : params.interrupt_id; + this.#prepareForNextRun(respondedIds); + this.#startLifecycleWatcher(); + await this.#send("input.respond", params); + } + onEvent(listener) { + this.#onEventListeners.add(listener); + return () => { + this.#onEventListeners.delete(listener); + }; + } + #startLifecycleWatcher() { + if (this.#lifecycleWatcherStartPromise != null) return; - if (this.interruptBefore?.length > 0 && shouldInterrupt2(this.checkpoint, this.interruptBefore, [pushed])) { - this.toInterrupt.push(pushed); + if (this.#transportAdapter.openEventStream != null) { + this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherSse(); return; } - this._emit(gatherIteratorSync2(prefixGenerator2(mapDebugTasks2([pushed]), "tasks"))); - if (this.debug) - printStepTasks2(this.step, [pushed]); - this.tasks[pushed.id] = pushed; - if (this.skipDoneTasks) - this._matchWrites({ [pushed.id]: pushed }); - const tasks = await this._matchCachedWrites(); - for (const { task: task3 } of tasks) - this._outputWrites(task3.id, task3.writes, true); - return pushed; + this.#lifecycleWatcherStartPromise = this.#startLifecycleWatcherWebSocket(); } - _suppressInterrupt(e) { - return isGraphInterrupt2(e) && !this.isNested; + startLifecycleWatcher() { + this.#startLifecycleWatcher(); } - async _first(inputKeys) { - const { configurable } = this.config; - const scratchpad = configurable?.[CONFIG_KEY_SCRATCHPAD2]; - if (scratchpad && scratchpad.nullResume !== undefined) - this.putWrites(NULL_TASK_ID2, [[RESUME3, scratchpad.nullResume]]); - if (isCommand2(this.input)) { - const hasResume = this.input.resume != null; - if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH32)) { - this.config.configurable ??= {}; - this.config.configurable[CONFIG_KEY_RESUME_MAP2] = this.input.resume; - } - if (hasResume && this.checkpointer == null) - throw new Error("Cannot use Command(resume=...) without checkpointer"); - const writes = {}; - for (const [tid, key, value] of mapCommand2(this.input, this.checkpointPendingWrites)) { - writes[tid] ??= []; - writes[tid].push([key, value]); + async#startLifecycleWatcherSse() { + if (this.#runStartReady != null) + try { + await this.#runStartReady; + } catch { + return; } - if (Object.keys(writes).length === 0) - throw new EmptyInputError2("Received empty Command input"); - for (const [tid, ws] of Object.entries(writes)) - this.putWrites(tid, ws); + const filter = { channels: ["lifecycle", "input"] }; + let handle; + try { + handle = this.#transportAdapter.openEventStream(filter); + } catch { + return; } - const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites2(this.checkpoint, this.channels, [{ - name: INPUT2, - writes: nullWrites, - triggers: [] - }], this.checkpointerGetNextVersion, this.triggerToNodes); - const isCommandUpdateOrGoto = isCommand2(this.input) && nullWrites.length > 0; - if (this.isResuming || isCommandUpdateOrGoto) { - for (const channelName in this.channels) { - if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) - continue; - if (this.checkpoint.channel_versions[channelName] !== undefined) { - const version4 = this.checkpoint.channel_versions[channelName]; - this.checkpoint.versions_seen[INTERRUPT3] = { - ...this.checkpoint.versions_seen[INTERRUPT3], - [channelName]: version4 - }; - } - } - const valuesOutput = await gatherIterator2(prefixGenerator2(mapOutputValues2(this.outputKeys, true, this.channels), "values")); - if (this.isResuming) - this.input = INPUT_RESUMING2; - else if (isCommandUpdateOrGoto) { - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE2; - } - this._emitValuesWithCheckpointMeta(valuesOutput); - } else { - const inputWrites = await gatherIterator2(mapInput2(inputKeys, this.input)); - if (inputWrites.length > 0) { - const discardTasks = _prepareNextTasks2(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); - this.updatedChannels = _applyWrites2(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ - name: INPUT2, - writes: inputWrites, - triggers: [] - }]), this.checkpointerGetNextVersion, this.triggerToNodes); - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE2; - } else if (!("__pregel_resuming" in (this.config.configurable ?? {}))) - throw new EmptyInputError2(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); - else - this.input = INPUT_DONE2; + try { + await handle.ready; + } catch { + try { + handle.close(); + } catch {} + return; } - if (!this.isNested) - this.config = patchConfigurable4(this.config, { [CONFIG_KEY_RESUMING2]: this.isResuming }); - } - _emit(values2) { - for (const entry of values2) { - const [mode, payload, meta3] = entry; - if (this.stream.modes.has(mode)) - this.stream.push([ - this.checkpointNamespace, - mode, - payload, - meta3 - ]); - if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { - const step = mode === "checkpoints" ? this.step - 1 : this.step; - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const type = (() => { - if (mode === "checkpoints") - return "checkpoint"; - else if (typeof payload === "object" && payload != null && "result" in payload) - return "task_result"; - else - return "task"; - })(); - this.stream.push([ - this.checkpointNamespace, - "debug", - { - step, - type, - timestamp, - payload - } - ]); - } + if (this.#closed) { + try { + handle.close(); + } catch {} + return; } + this.#lifecycleWatcherHandle = handle; + try { + for await (const message of handle.events) { + if (this.#closed) + break; + this.#handleLifecycleWatcherMessage(message); + } + } catch {} } - _currentCheckpointMeta() { - if (!this.checkpointMetadata || !this.checkpoint?.id) + async#startLifecycleWatcherWebSocket() { + let handle; + try { + handle = await this.#subscribeRaw({ channels: ["lifecycle", "input"] }); + } catch { return; - const parent_id = this.prevCheckpointConfig?.configurable?.checkpoint_id; - return { checkpoint: { - id: this.checkpoint.id, - ...parent_id ? { parent_id } : {}, - step: this.checkpointMetadata.step, - source: this.checkpointMetadata.source - } }; - } - _emitValuesWithCheckpointMeta(entries) { - const meta3 = this._currentCheckpointMeta(); - if (!meta3) { - this._emit(entries); + } + if (this.#closed) { + try { + handle.close(); + } catch {} return; } - this._emit(entries.map(([mode, payload]) => mode === "values" ? [ - mode, - payload, - meta3 - ] : [mode, payload])); - } - _putCheckpoint(inputMetadata) { - const exiting = this.checkpointMetadata === inputMetadata; - const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); - const storeCheckpoint = (checkpoint) => { - this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : undefined; - this.checkpointConfig = patchConfigurable4(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "" }); - const channelVersions = { ...this.checkpoint.channel_versions }; - const newVersions = getNewChannelVersions2(this.checkpointPreviousVersions, channelVersions); - this.checkpointPreviousVersions = channelVersions; - this._checkpointerPutAfterPrevious({ - config: { ...this.checkpointConfig }, - checkpoint: copyCheckpoint(checkpoint), - metadata: { ...this.checkpointMetadata }, - newVersions - }); - this.checkpointConfig = { - ...this.checkpointConfig, - configurable: { - ...this.checkpointConfig.configurable, - checkpoint_id: this.checkpoint.id - } - }; - }; - if (!exiting) - this.checkpointMetadata = { - ...inputMetadata, - step: this.step, - parents: this.config.configurable?.["checkpoint_map"] ?? {} - }; - this.checkpoint = createCheckpoint2(this.checkpoint, doCheckpoint ? this.channels : undefined, this.step, exiting ? { id: this.checkpoint.id } : undefined); - if (doCheckpoint) - storeCheckpoint(this.checkpoint); - if (!exiting) - this.step += 1; + try { + for await (const _event of handle) + if (this.#closed) + break; + } catch {} } - _flushPendingWrites() { - if (this.checkpointer == null) + #handleLifecycleWatcherMessage(message) { + if (message.type !== "event") return; - if (this.checkpointPendingWrites.length === 0) + if (typeof message.seq === "number") + this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); + if (message.event_id) + this.ordering.lastEventId = message.event_id; + const eventId = message.event_id ?? undefined; + const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); + if (eventId != null) + this.#seenEventIds.add(eventId); + if (globallyProcessed) return; - const config2 = patchConfigurable4(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS2]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID2]: this.checkpoint.id - }); - const byTask = {}; - for (const [tid, key, value] of this.checkpointPendingWrites) { - byTask[tid] ??= []; - byTask[tid].push([key, value]); - } - for (const [tid, ws] of Object.entries(byTask)) - this._trackCheckpointerPromise(this.checkpointer.putWrites(config2, ws, tid)); - } - _matchWrites(tasks) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === "__error__" || k === "__interrupt__" || k === "__resume__") - continue; - const task2 = Object.values(tasks).find((t) => t.id === tid); - if (task2) - task2.writes.push([k, v]); - } - for (const task2 of Object.values(tasks)) - if (task2.writes.length > 0) - this._outputWrites(task2.id, task2.writes, true); + this.#applyThreadLevelEffects(message); + this.#fireOnEvent(message); } -}; -var init_loop2 = __esm(() => { - init_constants8(); - init_errors10(); - init_base17(); - init_utils17(); - init_hash4(); - init_io2(); - init_utils18(); - init_algo2(); - init_debug2(); - init_stream12(); - init_dist3(); - INPUT_DONE2 = Symbol.for("INPUT_DONE"); - INPUT_RESUMING2 = Symbol.for("INPUT_RESUMING"); - AsyncBatchedCache2 = class extends BaseCache2 { - cache; - queue = Promise.resolve(); - constructor(cache2) { - super(); - this.cache = cache2; + #applyThreadLevelEffects(event) { + if (event.method === "lifecycle") { + if (event.params.data.event === "interrupted") + this.interrupted = true; } - async get(keys) { - return this.enqueueOperation("get", keys); + if (event.method === "input.requested") { + const data = event.params.data; + const interruptId = data.interrupt_id ?? `interrupt_${this.interrupts.length}`; + this.interrupts.push({ + interruptId, + payload: data.payload, + namespace: [...event.params.namespace] + }); + if (isHeadlessToolInterrupt(data.payload)) + this.#headlessInterruptsAwaitingTerminal.add(interruptId); } - async set(pairs) { - return this.enqueueOperation("set", pairs); + } + #fireOnEvent(event) { + if (this.#onEventListeners.size === 0) + return; + for (const listener of this.#onEventListeners) + try { + listener(event); + } catch {} + } + async close() { + if (this.#closed) + return; + this.#closed = true; + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = undefined; } - async clear(namespaces) { - return this.enqueueOperation("clear", namespaces); + this.#terminalPauseSeq = undefined; + for (const pending of this.#pendingSubResolves) + pending.reject(/* @__PURE__ */ new Error("ThreadStream closed")); + this.#pendingSubResolves.length = 0; + if (this.#sharedStream != null) { + try { + this.#sharedStream.close(); + } catch {} + this.#sharedStream = null; + this.#sharedStreamFilter = null; } - async stop() { - await this.queue; + if (this.#lifecycleWatcherHandle != null) { + try { + this.#lifecycleWatcherHandle.close(); + } catch {} + this.#lifecycleWatcherHandle = null; } - enqueueOperation(type, ...args) { - const newPromise = this.queue.then(() => { - return this.cache[type](...args); - }); - this.queue = newPromise.then(() => { - return; - }, () => { - return; + const lifecycleWatcherStartPromise = this.#lifecycleWatcherStartPromise; + this.#lifecycleWatcherStartPromise = undefined; + this.#onEventListeners.clear(); + for (const subscription of this.#subscriptions.values()) + subscription.close(); + this.#subscriptions.clear(); + try { + await lifecycleWatcherStartPromise; + } catch {} + for (const handle of this.#mediaHandles) + try { + handle.revoke(); + } catch {} + this.#mediaHandles.clear(); + this.#mediaAssembler?.close(); + this.#audioBuffer.close(); + this.#imagesBuffer.close(); + this.#videoBuffer.close(); + this.#filesBuffer.close(); + await this.#transportAdapter.close(); + } + async subscribe(paramsOrChannels, options = {}) { + const isParamsObject = typeof paramsOrChannels === "object" && !Array.isArray(paramsOrChannels) && "channels" in paramsOrChannels; + const params = normalizeSubscribeParams(paramsOrChannels, options); + return await this.#subscribeRaw(params, { unwrapNamedCustom: !isParamsObject }); + } + async#subscribeRaw(params, options = {}) { + await this.#ensureOpen(); + const { unwrapNamedCustom = true } = options; + const hasOnlyNamedCustom = params.channels.length > 0 && params.channels.every((ch) => ch.startsWith("custom:")); + const transform3 = unwrapNamedCustom && hasOnlyNamedCustom ? (event) => event.params.data?.payload ?? event : undefined; + if (this.#transportAdapter.openEventStream != null) + return this.#subscribeViaSharedStream(params, transform3); + return this.#subscribeViaCommand(params, transform3); + } + async#subscribeViaSharedStream(params, transform3) { + const subscriptionId = `sse-${this.#nextCommandId++}`; + const handle = new SubscriptionHandle(subscriptionId, params, async (id) => { + this.#subscriptions.delete(id); + this.#scheduleReconcile(); + }, transform3); + const subscription = Object.assign(handle, { + filter: params, + registeredAfterSeq: this.ordering.lastSeenSeq, + seenEventIds: /* @__PURE__ */ new Set + }); + this.#subscriptions.set(subscriptionId, subscription); + const covered = new Promise((resolve2, reject) => { + this.#pendingSubResolves.push({ + filter: params, + resolve: resolve2, + reject }); - return newPromise; + }); + this.#scheduleReconcile(); + try { + await covered; + } catch (err) { + this.#subscriptions.delete(subscriptionId); + throw err; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/messages.js -function isChatGenerationChunk3(x) { - return isBaseMessage(x?.message); -} -function normalizeStreamMetadata2(metadata, tags, name) { - if (!metadata) - return; - const streamNamespace = metadata.langgraph_checkpoint_ns; - const checkpointNs = metadata.checkpoint_ns; - const namespace = streamNamespace ?? checkpointNs; - if (!namespace) - return; - return [namespace.split("|"), { - tags, - name, - ...metadata - }]; -} -var StreamMessagesHandler2; -var init_messages11 = __esm(() => { - init_constants8(); - init_base2(); - init_messages(); - StreamMessagesHandler2 = class extends BaseCallbackHandler { - name = "StreamMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - emittedChatModelRunIds = {}; - stableMessageIdMap = {}; - lc_prefer_streaming = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; + return handle; + } + #computeUnionFilter() { + if (this.#subscriptions.size === 0) + return null; + const channels = /* @__PURE__ */ new Set; + let wildcardNamespaces = false; + const namespaceMap = /* @__PURE__ */ new Map; + let unboundedDepth = false; + let maxDepth = 0; + for (const sub of this.#subscriptions.values()) { + for (const ch of sub.filter.channels) + channels.add(ch); + if (sub.filter.namespaces == null) + wildcardNamespaces = true; + else if (!wildcardNamespaces) + for (const ns3 of sub.filter.namespaces) + namespaceMap.set(namespaceKey(ns3), ns3); + if (sub.filter.depth == null) + unboundedDepth = true; + else if (!unboundedDepth && sub.filter.depth > maxDepth) + maxDepth = sub.filter.depth; } - _emit(meta3, message, runId, dedupe = false) { - if (dedupe && message.id !== undefined && this.seen[message.id] !== undefined) + const result = { channels: [...channels] }; + if (!wildcardNamespaces) + result.namespaces = [...namespaceMap.values()]; + if (!unboundedDepth) + result.depth = maxDepth; + return result; + } + #scheduleReconcile() { + if (this.#closed) + return; + if (this.#rotationState !== "idle") + return; + this.#rotationState = "scheduled"; + queueMicrotask(() => { + if (this.#closed) { + this.#rotationState = "idle"; return; - let messageId = message.id; - if (runId != null) - if (isToolMessage(message)) - messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) - messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; - } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; } - if (message.id != null) - this.seen[message.id] = message; - this.streamFn([ - meta3[0], - "messages", - [message, meta3[1]] - ]); - } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) - this.metadatas[runId] = normalizeStreamMetadata2(metadata, tags, name); - } - handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { - const chunk = fields?.chunk; - this.emittedChatModelRunIds[runId] = true; - if (this.metadatas[runId] !== undefined) - if (isChatGenerationChunk3(chunk)) - this._emit(this.metadatas[runId], chunk.message, runId); - else - this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); - } - handleLLMEnd(output, runId) { - if (this.metadatas[runId] === undefined) + this.#rotationState = "idle"; + this.#reconcileStream().catch(() => { + this.#rotationState = "idle"; + }); + }); + } + async#reconcileStream() { + if (this.#closed) + return; + if (this.#rotationState === "rotating") + return; + const desired = this.#computeUnionFilter(); + if (desired == null) + return; + if (this.#runStartReady != null) { + try { + await this.#runStartReady; + } catch (err) { + const normalized = err instanceof Error ? err : /* @__PURE__ */ new Error("run.start failed"); + this.#rejectUncoveredPending(normalized); return; - if (!this.emittedChatModelRunIds[runId]) { - const chatGeneration = output.generations?.[0]?.[0]; - if (isBaseMessage(chatGeneration?.message)) - this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); - delete this.emittedChatModelRunIds[runId]; } - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + if (this.#closed) + return; + if (this.#rotationState === "rotating") + return; } - handleLLMError(_err, runId) { - delete this.metadatas[runId]; + if (this.#sharedStreamFilter != null && filterEqual(desired, this.#sharedStreamFilter) && this.#pendingSubResolves.length === 0) { + this.#resolvePending(); + return; } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { - this.metadatas[runId] = normalizeStreamMetadata2(metadata, tags, name); - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) - if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) - this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) - if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) - this.seen[item.id] = item; - } - } - } + this.#rotationState = "rotating"; + let newHandle; + try { + newHandle = this.#transportAdapter.openEventStream(desired); + } catch (err) { + this.#rotationState = "idle"; + this.#rejectUncoveredPending(err); + return; } - handleChainEnd(outputs, runId) { - const metadata = this.metadatas[runId]; - delete this.metadatas[runId]; - if (metadata !== undefined) { - if (isBaseMessage(outputs)) - this._emit(metadata, outputs, runId, true); - else if (Array.isArray(outputs)) { - for (const value of outputs) - if (isBaseMessage(value)) - this._emit(metadata, value, runId, true); - } else if (outputs != null && typeof outputs === "object") { - for (const value of Object.values(outputs)) - if (isBaseMessage(value)) - this._emit(metadata, value, runId, true); - else if (Array.isArray(value)) { - for (const item of value) - if (isBaseMessage(item)) - this._emit(metadata, item, runId, true); - } - } - } + try { + await newHandle.ready; + } catch (err) { + this.#rotationState = "idle"; + try { + newHandle.close(); + } catch {} + this.#rejectUncoveredPending(err); + return; } - handleChainError(_err, runId) { - delete this.metadatas[runId]; + if (this.#closed) { + try { + newHandle.close(); + } catch {} + this.#rotationState = "idle"; + return; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/messages-v2.js -function getResponseMetadata2(message) { - if ("response_metadata" in message && typeof message.response_metadata === "object" && message.response_metadata != null) - return message.response_metadata; -} -function getUsageMetadata2(message) { - if ("usage_metadata" in message && typeof message.usage_metadata === "object" && message.usage_metadata != null) - return message.usage_metadata; -} -function startBlockFor2(block) { - switch (block.type) { - case "text": - return { - type: "text", - text: "" - }; - case "reasoning": - return { - type: "reasoning", - reasoning: "" - }; - case "tool_call": - case "tool_call_chunk": - return { - type: "tool_call_chunk", - ...block.id != null ? { id: block.id } : {}, - ...block.name != null ? { name: block.name } : {}, - args: "" - }; - default: - return block; + this.#pumpStream(newHandle); + const oldHandle = this.#sharedStream; + this.#sharedStream = newHandle; + this.#sharedStreamFilter = desired; + if (oldHandle != null) + try { + oldHandle.close(); + } catch {} + this.#rotationState = "idle"; + this.#resolvePending(); + const next = this.#computeUnionFilter(); + if (next != null && !filterEqual(next, this.#sharedStreamFilter)) + this.#scheduleReconcile(); } -} -function deltaFor2(block) { - switch (block.type) { - case "text": { - const text = typeof block.text === "string" ? block.text : ""; - return text.length > 0 ? { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "text-delta", - text - } - } : undefined; + async#pumpStream(handle) { + try { + for await (const message of handle.events) { + if (this.#closed) + break; + this.#handleIncoming(message); + } + } catch (err) { + if (handle === this.#sharedStream && !this.#closed) + this.#failThreadWithError(err); } - case "reasoning": { - const reasoning = typeof block.reasoning === "string" ? block.reasoning : ""; - return reasoning.length > 0 ? { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "reasoning-delta", - reasoning - } - } : undefined; - } - case "tool_call_chunk": - return { - event: "content-block-delta", - index: typeof block.index === "number" ? block.index : 0, - delta: { - type: "block-delta", - fields: { - ...block, - type: "tool_call_chunk" - } - } - }; - default: + } + #resolvePending() { + if (this.#sharedStreamFilter == null) + return; + const current = this.#sharedStreamFilter; + if (this.#pendingSubResolves.length === 0) + return; + const stillPending = []; + for (const pending of this.#pendingSubResolves) + if (filterCovers(current, pending.filter)) + pending.resolve(); + else + stillPending.push(pending); + this.#pendingSubResolves.length = 0; + this.#pendingSubResolves.push(...stillPending); + } + #rejectUncoveredPending(err) { + if (this.#pendingSubResolves.length === 0) return; + const current = this.#sharedStreamFilter; + const stillPending = []; + for (const pending of this.#pendingSubResolves) + if (current != null && filterCovers(current, pending.filter)) + pending.resolve(); + else + stillPending.push(pending); + this.#pendingSubResolves.length = 0; + for (const pending of stillPending) + pending.reject(err); } -} -var StreamProtocolMessagesHandler2; -var init_messages_v22 = __esm(() => { - init_constants8(); - init_base2(); - init_messages(); - StreamProtocolMessagesHandler2 = class extends BaseCallbackHandler { - name = "StreamProtocolMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - streamedRunIds = /* @__PURE__ */ new Set; - stableMessageIdMap = {}; - lc_prefer_chat_model_stream_events = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; + #failThreadWithError(err) { + const normalized = err instanceof Error ? err : new Error(String(err)); + for (const pending of this.#pending.values()) + pending.reject(normalized); + this.#pending.clear(); + for (const pending of this.#pendingSubResolves) + pending.reject(normalized); + this.#pendingSubResolves.length = 0; + for (const subscription of this.#subscriptions.values()) + subscription.close(); + } + async#subscribeViaCommand(params, transform3) { + const placeholderId = `pending:${this.#nextCommandId}:${Math.random().toString(36).slice(2, 10)}`; + let resolvedId = placeholderId; + const handle = new SubscriptionHandle(placeholderId, params, async () => { + this.#subscriptions.delete(resolvedId); + if (!this.#closed && resolvedId !== placeholderId) + await this.#send("subscription.unsubscribe", { subscription_id: resolvedId }).catch((err) => { + if (err instanceof ProtocolError2 && err.code === "no_such_subscription") + return; + throw err; + }); + }, transform3); + const subscription = Object.assign(handle, { + filter: params, + registeredAfterSeq: this.ordering.lastSeenSeq, + seenEventIds: /* @__PURE__ */ new Set + }); + this.#subscriptions.set(placeholderId, subscription); + if (this.#runStartReady != null) + try { + await this.#runStartReady; + } catch (err) { + this.#subscriptions.delete(placeholderId); + throw err; + } + let result; + try { + result = await this.#send("subscription.subscribe", params); + } catch (err) { + this.#subscriptions.delete(placeholderId); + throw err; } - normalizeMessageId(message, runId) { - let messageId = message.id; - if (runId != null) - if (isToolMessage(message)) - messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) - messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; + this.#subscriptions.delete(placeholderId); + resolvedId = result.subscription_id; + handle.subscriptionId = resolvedId; + this.#subscriptions.set(resolvedId, subscription); + return handle; + } + async#consumeEvents() { + try { + for await (const message of this.#transportAdapter.events()) + this.#handleIncoming(message); + for (const subscription of this.#subscriptions.values()) + subscription.close(); + } catch (error90) { + const normalized = error90 instanceof Error ? error90 : new Error(String(error90)); + for (const pending of this.#pending.values()) + pending.reject(normalized); + for (const subscription of this.#subscriptions.values()) + subscription.close(); + this.#pending.clear(); + } + } + #scheduleTerminalPause(terminalSeq) { + if (this.#terminalPauseTimer != null) + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseSeq = terminalSeq ?? null; + this.#terminalPauseTimer = setTimeout(() => { + this.#terminalPauseTimer = undefined; + if (this.#closed) + return; + for (const [id, subscription] of this.#subscriptions) { + if (id === this.#lifecycleSubId) + continue; + if (terminalSeq != null && subscription.registeredAfterSeq != null && subscription.registeredAfterSeq >= terminalSeq) + continue; + subscription.pause(); + } + }, 0); + } + #handleIncoming(message) { + if (message.type === "event") { + if (typeof message.seq === "number") + this.ordering.lastSeenSeq = maxSeq(this.ordering.lastSeenSeq, message.seq); + if (message.event_id) + this.ordering.lastEventId = message.event_id; + const eventId = message.event_id ?? undefined; + const globallyProcessed = eventId != null && this.#seenEventIds.has(eventId); + if (eventId != null) + this.#seenEventIds.add(eventId); + const TERMINAL_LIFECYCLE_EVENTS = new Set([ + "interrupted", + "completed", + "failed" + ]); + if (!globallyProcessed) { + this.#applyThreadLevelEffects(message); + this.#fireOnEvent(message); + } + let fannedToAny = false; + for (const subscription of this.#subscriptions.values()) { + if (!matchesSubscription(message, subscription.filter)) + continue; + if (eventId != null) { + if (subscription.seenEventIds.has(eventId)) + continue; + subscription.seenEventIds.add(eventId); } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; + subscription.push(message); + fannedToAny = true; } - if (message.id != null) - this.seen[message.id] = message; - return message.id; + if (fannedToAny && this.#terminalPauseSeq !== undefined && !(message.method === "lifecycle" && message.params.namespace.length === 0)) { + const eventSeq = typeof message.seq === "number" ? message.seq : undefined; + const terminalSeq = this.#terminalPauseSeq; + if (terminalSeq === null || eventSeq == null || eventSeq > terminalSeq) { + if (this.#terminalPauseTimer != null) { + clearTimeout(this.#terminalPauseTimer); + this.#terminalPauseTimer = undefined; + } + for (const [id, subscription] of this.#subscriptions) + if (id !== this.#lifecycleSubId) + subscription.resume(); + this.#scheduleTerminalPause(terminalSeq === null ? undefined : terminalSeq); + } + } + if (fannedToAny && message.method === "lifecycle" && message.params.namespace.length === 0 && TERMINAL_LIFECYCLE_EVENTS.has(message.params.data.event)) { + if (message.params.data.event === "interrupted" && this.#headlessInterruptsAwaitingTerminal.size > 0) { + this.#headlessInterruptsAwaitingTerminal.clear(); + return; + } + this.#scheduleTerminalPause(typeof message.seq === "number" ? message.seq : undefined); + } + return; } - emit(meta3, data, runId) { - const metadata = runId != null ? { - ...meta3[1], - run_id: runId - } : meta3[1]; - this.streamFn([ - meta3[0], - "messages", - [data, metadata] - ]); + const messageId = typeof message.id === "number" ? message.id : undefined; + const pending = messageId === undefined ? undefined : this.#pending.get(messageId); + if (!pending) + return; + if (messageId !== undefined) + this.#pending.delete(messageId); + if (message.type === "error") { + pending.reject(new ProtocolError2(message)); + return; } - emitFinalMessage(meta3, message, runId, dedupe = false) { - const existingId = message.id ?? (runId != null ? this.stableMessageIdMap[runId] : undefined); - if (dedupe && existingId != null && this.seen[existingId] !== undefined) - return; - const messageId = this.normalizeMessageId(message, runId); - const role = message.type === "human" ? "human" : message.type === "system" ? "system" : message.type === "tool" ? "tool" : "ai"; - const toolCallId = role === "tool" && isToolMessage(message) ? message.tool_call_id : undefined; - this.emit(meta3, { - event: "message-start", - ...messageId != null ? { id: messageId } : {}, - ...role !== "ai" ? { role } : {}, - ...typeof toolCallId === "string" ? { tool_call_id: toolCallId } : {} - }, runId); - (Array.isArray(message.content) ? message.content : typeof message.content === "string" && message.content.length > 0 ? [{ - type: "text", - text: message.content - }] : []).forEach((block, offset) => { - const index2 = typeof block.index === "number" ? block.index : offset; - this.emit(meta3, { - event: "content-block-start", - index: index2, - content: startBlockFor2(block) - }, runId); - const delta = deltaFor2({ - ...block, - index: index2 - }); - if (delta != null) - this.emit(meta3, delta, runId); - this.emit(meta3, { - event: "content-block-finish", - index: index2, - content: block - }, runId); + if (typeof message.meta?.applied_through_seq === "number") + this.ordering.lastAppliedThroughSeq = message.meta.applied_through_seq; + pending.resolve(message); + } + async#send(method, params) { + await this.#ensureOpen(); + const id = this.#nextCommandId++; + const command = { + id, + method, + params + }; + const responsePromise = new Promise((resolve2, reject) => { + this.#pending.set(id, { + resolve: resolve2, + reject }); - this.emit(meta3, { - event: "message-finish", - ...getUsageMetadata2(message) != null ? { usage: getUsageMetadata2(message) } : {}, - ...getResponseMetadata2(message) != null ? { responseMetadata: getResponseMetadata2(message) } : {} - }, runId); + }); + const immediate = await this.#transportAdapter.send(command); + if (immediate) { + this.#pending.delete(id); + if (immediate.type === "error") + throw new ProtocolError2(immediate); + if (typeof immediate.meta?.applied_through_seq === "number") + this.ordering.lastAppliedThroughSeq = immediate.meta.applied_through_seq; + return immediate.result; } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes("langsmith:nostream") && !tags.includes("nostream"))) - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; + return (await responsePromise).result; + } +}; +var init_stream10 = __esm(() => { + init_subscription(); + init_multi_cursor_buffer(); + init_messages9(); + init_tools4(); + init_messages8(); + init_media(); + init_subgraphs3(); + init_subagents(); + init_handles(); + init_error4(); + init_constants6(); + init_headless_tools(); + MESSAGE_LIKE_TYPES = new Set([ + "human", + "user", + "ai", + "assistant", + "tool", + "system", + "function", + "remove" + ]); + ROOT_TERMINAL_LIFECYCLE_EVENTS = new Set([ + "completed", + "failed", + "interrupted" + ]); + SubscriptionHandle = class { + subscriptionId; + params; + queue = []; + waiters = []; + closed = false; + paused = false; + resumeResolve; + onUnsubscribe; + transform; + constructor(subscriptionId, params, onUnsubscribe, transform3) { + this.subscriptionId = subscriptionId; + this.params = params; + this.onUnsubscribe = onUnsubscribe; + this.transform = transform3 ?? ((event) => event); } - handleLLMNewToken() {} - handleChatModelStreamEvent(event, runId) { - const meta3 = this.metadatas[runId]; - if (meta3 === undefined) + push(event) { + if (this.closed) + return; + const value = this.transform(event); + const waiter = this.waiters.shift(); + if (waiter) { + waiter({ + done: false, + value + }); return; - let forwarded = event; - if (event.event === "message-start") { - this.streamedRunIds.add(runId); - const id = event.id ?? `run-${runId}`; - this.seen[id] = true; - this.stableMessageIdMap[runId] ??= id; - if (event.id == null) - forwarded = { - ...event, - id - }; } - this.emit(meta3, forwarded, runId); + this.queue.push(value); } - handleLLMEnd(output, runId) { - const meta3 = this.metadatas[runId]; - if (meta3 === undefined) + pause() { + if (this.closed) return; - const chatGeneration = output.generations?.[0]?.[0]; - const message = isBaseMessage(chatGeneration?.message) ? chatGeneration.message : undefined; - if (message != null) - if (this.streamedRunIds.has(runId)) { - const messageId = this.normalizeMessageId(message, runId); - if (messageId != null) - this.seen[messageId] = message; - } else - this.emitFinalMessage(meta3, message, runId, true); - this.streamedRunIds.delete(runId); - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + this.paused = true; + while (this.waiters.length > 0) + this.waiters.shift()?.({ + done: true, + value: undefined + }); } - handleLLMError(_err, runId) { - this.streamedRunIds.delete(runId); - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + resume() { + this.paused = false; + this.resumeResolve?.(); + this.resumeResolve = undefined; } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== undefined && name === metadata.langgraph_node && (tags === undefined || !tags.includes("langsmith:hidden"))) { - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) - if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== undefined) - this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) - if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== undefined) - this.seen[item.id] = item; - } - } - } + waitForResume() { + if (!this.paused) + return Promise.resolve(); + return new Promise((resolve2) => { + this.resumeResolve = resolve2; + }); } - handleChainEnd(outputs, runId) { - const meta3 = this.metadatas[runId]; - delete this.metadatas[runId]; - if (meta3 === undefined) - return; - const emitMessage = (value) => { - if (isBaseMessage(value)) - this.emitFinalMessage(meta3, value, runId, true); - }; - if (isBaseMessage(outputs)) - emitMessage(outputs); - else if (Array.isArray(outputs)) - for (const value of outputs) - emitMessage(value); - else if (outputs != null && typeof outputs === "object") - for (const value of Object.values(outputs)) - if (Array.isArray(value)) - for (const item of value) - emitMessage(item); - else - emitMessage(value); - delete this.stableMessageIdMap[runId]; + get isPaused() { + return this.paused; } - handleChainError(_err, runId) { - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; + close() { + this.closed = true; + this.paused = false; + while (this.waiters.length > 0) + this.waiters.shift()?.({ + done: true, + value: undefined + }); + this.resumeResolve?.(); + this.resumeResolve = undefined; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/retry.js -async function _runWithRetry2(pregelTask, retryPolicy, configurable, signal) { - const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; - let interval = resolvedRetryPolicy !== undefined ? resolvedRetryPolicy.initialInterval ?? 500 : 0; - let attempts = 0; - let error52; - let result; - let config2 = pregelTask.config ?? {}; - if (configurable) - config2 = patchConfigurable4(config2, configurable); - config2 = { - ...config2, - signal - }; - const firstAttemptTime = Date.now(); - if (config2.executionInfo != null) - config2.executionInfo = { - ...config2.executionInfo, - nodeFirstAttemptTime: firstAttemptTime - }; - while (true) { - if (signal?.aborted) - break; - pregelTask.writes.splice(0, pregelTask.writes.length); - error52 = undefined; - try { - result = await pregelTask.proc.invoke(pregelTask.input, config2); - break; - } catch (e) { - error52 = e; - error52.pregelTaskId = pregelTask.id; - if (isParentCommand2(error52)) { - const ns3 = config2?.configurable?.checkpoint_ns; - const cmd = error52.command; - if (cmd.graph === ns3) { - for (const writer2 of pregelTask.writers) - await writer2.invoke(cmd, config2); - error52 = undefined; - break; - } else if (cmd.graph === Command2.PARENT) { - const parentNs = getParentCheckpointNamespace2(ns3); - error52.command = new Command2({ - ...error52.command, - graph: parentNs + async unsubscribe() { + if (this.closed) + return; + this.close(); + await this.onUnsubscribe(this.subscriptionId); + } + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.queue.length > 0) + return { + done: false, + value: this.queue.shift() + }; + if (this.closed || this.paused) + return { + done: true, + value: undefined + }; + return await new Promise((resolve2) => { + this.waiters.push(resolve2); }); + }, + return: async () => { + this.close(); + return { + done: true, + value: undefined + }; } - } - if (isGraphBubbleUp2(error52)) - break; - if (resolvedRetryPolicy === undefined) - break; - attempts += 1; - if (attempts >= (resolvedRetryPolicy.maxAttempts ?? 3)) - break; - if (!(resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER2)(error52)) - break; - interval = Math.min(resolvedRetryPolicy.maxInterval ?? 128000, interval * (resolvedRetryPolicy.backoffFactor ?? 2)); - const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1000) : interval; - await new Promise((resolve2) => setTimeout(resolve2, intervalWithJitter)); - const errorName = error52.name ?? error52.constructor.unminifiable_name ?? error52.constructor.name; - if (resolvedRetryPolicy?.logWarning ?? true) - console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error52}`); - config2 = patchConfigurable4(config2, { [CONFIG_KEY_RESUMING2]: true }); - if (config2.executionInfo != null) - config2.executionInfo = { - ...config2.executionInfo, - nodeAttempt: attempts + 1, - nodeFirstAttemptTime: firstAttemptTime - }; + }; } - } - return { - task: pregelTask, - result, - error: error52, - signalAborted: signal?.aborted }; -} -var DEFAULT_STATUS_NO_RETRY2, DEFAULT_RETRY_ON_HANDLER2 = (error52) => { - if (error52.message.startsWith("Cancel") || error52.message.startsWith("AbortError") || error52.name === "AbortError") - return false; - if (error52.name === "GraphValueError") - return false; - if (error52?.code === "ECONNABORTED") - return false; - const status = error52?.response?.status ?? error52?.status; - if (status && DEFAULT_STATUS_NO_RETRY2.includes(+status)) - return false; - if (error52?.error?.code === "insufficient_quota") - return false; - return true; -}; -var init_retry2 = __esm(() => { - init_constants8(); - init_errors10(); - init_config3(); - init_utils18(); - DEFAULT_STATUS_NO_RETRY2 = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 - ]; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/runner.js -function createPromiseBarrier2() { - const barrier = { - next: () => { +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/queue.js +var AsyncQueue = class { + values = []; + waiters = []; + rejecters = []; + closed = false; + error = null; + push(value) { + if (this.closed) + return; + const waiter = this.waiters.shift(); + this.rejecters.shift(); + if (waiter) { + waiter({ + done: false, + value + }); return; - }, - wait: Promise.resolve(PROMISE_ADDED_SYMBOL2) - }; - function waitHandler(resolve2) { - barrier.next = () => { - barrier.wait = new Promise(waitHandler); - resolve2(PROMISE_ADDED_SYMBOL2); - }; - } - barrier.wait = new Promise(waitHandler); - return barrier; -} -async function call4(runner, task2, func, name, input, options = {}) { - const scratchpad = task2.config?.configurable?.[CONFIG_KEY_SCRATCHPAD2]; - if (!scratchpad) - throw new Error(`BUG: No scratchpad found on task ${task2.name}__${task2.id}`); - const cnt = scratchpad.callCounter; - scratchpad.callCounter += 1; - const wcall = new Call2({ - func, - name, - input, - cache: options.cache, - retry: options.retry, - callbacks: options.callbacks - }); - const nextTask = await this.scheduleTask(task2, cnt, wcall); - if (!nextTask) - return; - const existingPromise = this.executingTasksMap[nextTask.id]; - if (existingPromise !== undefined) - return existingPromise; - if (nextTask.writes.length > 0) { - const returns = nextTask.writes.filter(([c]) => c === RETURN2); - const errors4 = nextTask.writes.filter(([c]) => c === ERROR5); - if (returns.length > 0) { - if (returns.length === 1) - return Promise.resolve(returns[0][1]); - throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); - } - if (errors4.length > 0) { - if (errors4.length === 1) { - const errorValue = errors4[0][1]; - const error52 = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); - return Promise.reject(error52); - } - throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); } - return; - } else { - const prom = _runWithRetry2(nextTask, options.retry, { [CONFIG_KEY_CALL2]: call4.bind(this, runner, nextTask) }); - this.executingTasksMap[nextTask.id] = prom; - this.barrier.next(); - return prom.then(({ result, error: error52 }) => { - if (error52) - return Promise.reject(error52); - return result; - }); - } -} -var PROMISE_ADDED_SYMBOL2, PregelRunner2 = class { - nodeFinished; - loop; - constructor({ loop, nodeFinished }) { - this.loop = loop; - this.nodeFinished = nodeFinished; + this.values.push(value); } - async tick(options = {}) { - const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; - const nodeErrors = /* @__PURE__ */ new Set; - let graphBubbleUp; - const exceptionSignalController = new AbortController; - const exceptionSignal = exceptionSignalController.signal; - const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : undefined; - const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); - const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ - exceptionSignal, - stepTimeoutSignal, - signal: options.signal - }); - const taskStream = this._executeTasksWithRetry(pendingTasks, { - signals, - retryPolicy, - maxConcurrency - }); - for await (const { task: task2, error: error52, signalAborted } of taskStream) { - this._commit(task2, error52); - if (isGraphInterrupt2(error52)) - graphBubbleUp = error52; - else if (isGraphBubbleUp2(error52) && !isGraphInterrupt2(graphBubbleUp)) - graphBubbleUp = error52; - else if (error52 && (nodeErrors.size === 0 || !signalAborted)) { - exceptionSignalController.abort(); - nodeErrors.add(error52); - } + close(error90) { + if (this.closed) + return; + this.closed = true; + this.error = error90 == null ? null : error90 instanceof Error ? error90 : new Error(String(error90)); + if (this.error) { + for (const rejecter of this.rejecters.splice(0)) + rejecter(this.error); + this.waiters.length = 0; + return; } - disposeCombinedSignal?.(); - onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task2) => task2.writes).flat()); - if (nodeErrors.size === 1) - throw Array.from(nodeErrors)[0]; - else if (nodeErrors.size > 1) - throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); - if (isGraphInterrupt2(graphBubbleUp)) - throw graphBubbleUp; - if (isGraphBubbleUp2(graphBubbleUp) && this.loop.isNested) - throw graphBubbleUp; + for (const waiter of this.waiters.splice(0)) + waiter({ + done: true, + value: undefined + }); + this.rejecters.length = 0; } - _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { - const previousSignals = this.loop.config.configurable?.["__pregel_abort_signals"] ?? {}; - const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; - const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; - const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals2(externalAbortSignal, timeoutAbortSignal, exceptionSignal); - const signals = { - externalAbortSignal, - timeoutAbortSignal, - composedAbortSignal - }; - this.loop.config = patchConfigurable4(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS2]: signals }); - return { - signals, - disposeCombinedSignal - }; + async shift() { + if (this.values.length > 0) + return { + done: false, + value: this.values.shift() + }; + if (this.error) + throw this.error; + if (this.closed) + return { + done: true, + value: undefined + }; + return await new Promise((resolve2, reject) => { + this.waiters.push(resolve2); + this.rejecters.push(reject); + }); } - async* _executeTasksWithRetry(tasks, options) { - const { retryPolicy, maxConcurrency, signals } = options ?? {}; - const barrier = createPromiseBarrier2(); - const executingTasksMap = {}; - const thisCall = { - executingTasksMap, - barrier, - retryPolicy, - scheduleTask: async (task2, writeIdx, call4) => this.loop.acceptPush(task2, writeIdx, call4) - }; - if (signals?.composedAbortSignal?.aborted) - throw new Error("Abort"); - let startedTasksCount = 0; - let listener; - const timeoutOrCancelSignal = combineAbortSignals2(signals?.externalAbortSignal, signals?.timeoutAbortSignal); - const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { - listener = () => reject(/* @__PURE__ */ new Error("Abort")); - timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); - }) : undefined; - while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { - for (;Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { - const task2 = tasks[startedTasksCount]; - executingTasksMap[task2.id] = _runWithRetry2(task2, retryPolicy, { [CONFIG_KEY_CALL2]: call4?.bind(thisCall, this, task2) }, signals?.composedAbortSignal).catch((error52) => { - return { - task: task2, - error: error52, - signalAborted: signals?.composedAbortSignal?.aborted - }; - }); - } - const settledTask = await Promise.race([ - ...Object.values(executingTasksMap), - ...abortPromise ? [abortPromise] : [], - barrier.wait - ]); - if (settledTask === PROMISE_ADDED_SYMBOL2) - continue; - yield settledTask; - if (listener != null) { - timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); - timeoutOrCancelSignal.dispose?.(); - } - delete executingTasksMap[settledTask.task.id]; +}; +var init_queue = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/utils.js +function mergeHeaders2(...headerGroups) { + const merged = new Headers; + for (const group of headerGroups) { + if (!group) + continue; + if (group instanceof Headers) { + group.forEach((value, key) => { + merged.set(key, value); + }); + continue; } - } - _commit(task2, error52) { - if (error52 !== undefined) - if (isGraphInterrupt2(error52)) { - if (error52.interrupts.length) { - const interrupts = error52.interrupts.map((interrupt3) => [INTERRUPT3, interrupt3]); - const resumes = task2.writes.filter((w) => w[0] === RESUME3); - if (resumes.length) - interrupts.push(...resumes); - this.loop.putWrites(task2.id, interrupts); - } - } else if (isGraphBubbleUp2(error52) && task2.writes.length) - this.loop.putWrites(task2.id, task2.writes); - else - this.loop.putWrites(task2.id, [[ERROR5, { - message: error52.message, - name: error52.name - }]]); - else { - if (this.nodeFinished && (task2.config?.tags == null || !task2.config.tags.includes("langsmith:hidden"))) - this.nodeFinished(String(task2.name)); - if (task2.writes.length === 0) - task2.writes.push([NO_WRITES2, null]); - this.loop.putWrites(task2.id, task2.writes); + if (Array.isArray(group)) { + for (const [key, value] of group) + if (value == null) + merged.delete(key); + else + merged.set(key, value); + continue; } + for (const [key, value] of Object.entries(group)) + if (value == null) + merged.delete(key); + else + merged.set(key, value); } -}; -var init_runner2 = __esm(() => { - init_constants8(); - init_errors10(); - init_types13(); - init_utils18(); - init_retry2(); - PROMISE_ADDED_SYMBOL2 = Symbol.for("promiseAdded"); + return merged; +} +function isProtocolResponse(value) { + return isRecord3(value) && typeof value.type === "string" && (value.type === "success" || value.type === "error"); +} +var isRecord3 = (value) => typeof value === "object" && value !== null, toAbsoluteUrl = (apiUrl, path2) => new URL(`${apiUrl.replace(/\/$/, "")}${path2}`), toError = (error90) => error90 instanceof Error ? error90 : new Error(String(error90)), toWebSocketUrl = (apiUrl) => { + const url3 = new URL(apiUrl); + url3.protocol = url3.protocol === "https:" ? "wss:" : "ws:"; + url3.search = ""; + url3.hash = ""; + return url3.toString(); +}, hasHeaders = (headers) => Object.values(headers ?? {}).some((value) => value != null); +var init_utils16 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/constants.js +var TRAILING_NEWLINE2; +var init_constants7 = __esm(() => { + TRAILING_NEWLINE2 = [13, 10]; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/validate.js -function validateGraph2({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { - if (!channels) - throw new GraphValidationError2("Channels not provided"); - const subscribedChannels = /* @__PURE__ */ new Set; - const allOutputChannels = /* @__PURE__ */ new Set; - for (const [name, node] of Object.entries(nodes)) { - if (name === "__interrupt__") - throw new GraphValidationError2(`"Node name ${INTERRUPT3} is reserved"`); - if (node.constructor === PregelNode3) - node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); - else - throw new GraphValidationError2(`Invalid node type ${typeof node}, expected PregelNode`); - } - for (const chan of subscribedChannels) - if (!(chan in channels)) - throw new GraphValidationError2(`Subscribed channel '${String(chan)}' not in channels`); - if (!Array.isArray(inputChannels)) { - if (!subscribedChannels.has(inputChannels)) - throw new GraphValidationError2(`Input channel ${String(inputChannels)} is not subscribed to by any node`); - } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) - throw new GraphValidationError2(`None of the input channels ${inputChannels} are subscribed to by any node`); - if (!Array.isArray(outputChannels)) - allOutputChannels.add(outputChannels); - else - outputChannels.forEach((chan) => allOutputChannels.add(chan)); - if (streamChannels && !Array.isArray(streamChannels)) - allOutputChannels.add(streamChannels); - else if (Array.isArray(streamChannels)) - streamChannels.forEach((chan) => allOutputChannels.add(chan)); - for (const chan of allOutputChannels) - if (!(chan in channels)) - throw new GraphValidationError2(`Output channel '${String(chan)}' not in channels`); - if (interruptAfterNodes && interruptAfterNodes !== "*") { - for (const node of interruptAfterNodes) - if (!(node in nodes)) - throw new GraphValidationError2(`Node ${String(node)} not in nodes`); - } - if (interruptBeforeNodes && interruptBeforeNodes !== "*") { - for (const node of interruptBeforeNodes) - if (!(node in nodes)) - throw new GraphValidationError2(`Node ${String(node)} not in nodes`); +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/decoder.js +function joinArrays2(data) { + const totalLength = data.reduce((acc, curr) => acc + curr.length, 0); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of data) { + merged.set(chunk, offset); + offset += chunk.length; } + return merged; } -function validateKeys2(keys, channels) { - if (Array.isArray(keys)) { - for (const key of keys) - if (!(key in channels)) - throw new Error(`Key ${String(key)} not found in channels`); - } else if (!(keys in channels)) - throw new Error(`Key ${String(keys)} not found in channels`); +function decodeArraysToJson2(decoder, data) { + return JSON.parse(decoder.decode(joinArrays2(data))); } -var GraphValidationError2; -var init_validate5 = __esm(() => { - init_constants8(); - init_read2(); - GraphValidationError2 = class extends Error { - constructor(message) { - super(message); - this.name = "GraphValidationError"; - } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/topic.js -var Topic3; -var init_topic2 = __esm(() => { - init_errors10(); - init_base17(); - Topic3 = class Topic4 extends BaseChannel2 { - lc_graph_name = "Topic"; - unique = false; - accumulate = false; - seen; - values; - constructor(fields) { - super(); - this.unique = fields?.unique ?? this.unique; - this.accumulate = fields?.accumulate ?? this.accumulate; - this.seen = /* @__PURE__ */ new Set; - this.values = []; - } - fromCheckpoint(checkpoint) { - const empty = new Topic4({ - unique: this.unique, - accumulate: this.accumulate - }); - if (typeof checkpoint !== "undefined") { - empty.seen = new Set(checkpoint[0]); - empty.values = checkpoint[1]; +function BytesLineDecoder2() { + let buffer = []; + let trailingCr = false; + return new TransformStream({ + start() { + buffer = []; + trailingCr = false; + }, + transform(chunk, controller) { + let text = chunk; + if (trailingCr) { + text = joinArrays2([[13], text]); + trailingCr = false; } - return empty; - } - update(values2) { - let updated = false; - if (!this.accumulate) { - updated = this.values.length > 0; - this.values = []; + if (text.length > 0 && text.at(-1) === 13) { + trailingCr = true; + text = text.subarray(0, -1); } - const flatValues = values2.flat(); - if (flatValues.length > 0) - if (this.unique) { - for (const value of flatValues) - if (!this.seen.has(value)) { - updated = true; - this.seen.add(value); - this.values.push(value); - } - } else { - updated = true; - this.values.push(...flatValues); + if (!text.length) + return; + const trailingNewline = TRAILING_NEWLINE2.includes(text.at(-1)); + const lastIdx = text.length - 1; + const { lines } = text.reduce((acc, cur, idx) => { + if (acc.from > idx) + return acc; + if (cur === 13 || cur === 10) { + acc.lines.push(text.subarray(acc.from, idx)); + if (cur === 13 && text[idx + 1] === 10) + acc.from = idx + 2; + else + acc.from = idx + 1; } - return updated; - } - get() { - if (this.values.length === 0) - throw new EmptyChannelError2; - return this.values; - } - checkpoint() { - return [[...this.seen], this.values]; + if (idx === lastIdx && acc.from <= lastIdx) + acc.lines.push(text.subarray(acc.from)); + return acc; + }, { + lines: [], + from: 0 + }); + if (lines.length === 1 && !trailingNewline) { + buffer.push(lines[0]); + return; + } + if (buffer.length) { + buffer.push(lines[0]); + lines[0] = joinArrays2(buffer); + buffer = []; + } + if (!trailingNewline && lines.length) + buffer = [lines.pop()]; + for (const line of lines) + controller.enqueue(line); + }, + flush(controller) { + if (buffer.length) + controller.enqueue(joinArrays2(buffer)); } - isAvailable() { - return this.values.length !== 0; + }); +} +function SSEDecoder2() { + let event = ""; + let data = []; + let lastEventId = ""; + let retry = null; + const decoder = new TextDecoder; + return new TransformStream({ + transform(chunk, controller) { + if (!chunk.length) { + if (!event && !data.length && !lastEventId && retry == null) + return; + controller.enqueue({ + id: lastEventId || undefined, + event, + data: data.length ? decodeArraysToJson2(decoder, data) : null + }); + event = ""; + data = []; + retry = null; + return; + } + if (chunk[0] === 58) + return; + const sepIdx = chunk.indexOf(58); + if (sepIdx === -1) + return; + const fieldName = decoder.decode(chunk.subarray(0, sepIdx)); + let value = chunk.subarray(sepIdx + 1); + if (value[0] === 32) + value = value.subarray(1); + if (fieldName === "event") + event = decoder.decode(value); + else if (fieldName === "data") + data.push(value); + else if (fieldName === "id") { + if (value.indexOf(0) === -1) + lastEventId = decoder.decode(value); + } else if (fieldName === "retry") { + const retryNum = Number.parseInt(decoder.decode(value), 10); + if (!Number.isNaN(retryNum)) + retry = retryNum; + } + }, + flush(controller) { + if (event) + controller.enqueue({ + id: lastEventId || undefined, + event, + data: data.length ? decodeArraysToJson2(decoder, data) : null + }); } - }; + }); +} +var init_decoder = __esm(() => { + init_constants7(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/pregel/index.js -function protocolEventsToEventStream2(run2) { - const encoder2 = new TextEncoder; - return new ReadableStream({ async start(controller) { - try { - for await (const event of run2) { - const namespace = event.params.namespace; - const eventName = namespace.length ? `${event.method}|${namespace.join("|")}` : event.method; - controller.enqueue(encoder2.encode(`event: ${eventName} -data: ${JSON.stringify(event.params.data ?? {})} - -`)); +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/stream.js +var IterableReadableStream3; +var init_stream11 = __esm(() => { + IterableReadableStream3 = class IterableReadableStream4 extends ReadableStream { + reader; + ensureReader() { + if (!this.reader) + this.reader = this.getReader(); + } + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) { + this.reader.releaseLock(); + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: result.value + }; + } catch (error90) { + this.reader.releaseLock(); + throw error90; } - } catch (error52) { - controller.enqueue(encoder2.encode(`event: error -data: ${JSON.stringify({ message: String(error52) })} - -`)); - } finally { - controller.close(); } - } }); -} -function _buildServerInfo2(config2) { - const metadata = config2.metadata ?? {}; - const configurable = config2.configurable ?? {}; - const assistantId = metadata.assistant_id; - const graphId = metadata.graph_id; - const authUserData = configurable.langgraph_auth_user; - let user; - if (authUserData != null && typeof authUserData === "object" && "identity" in authUserData) - user = authUserData; - if (assistantId != null || graphId != null || user != null) + async return() { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + return { + done: true, + value: undefined + }; + } + async throw(error90) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + throw error90; + } + async[Symbol.asyncDispose]() { + await this.return(); + } + [Symbol.asyncIterator]() { + return this; + } + static fromReadableStream(stream2) { + const reader = stream2.getReader(); + return new IterableReadableStream4({ + start(controller) { + return pump3(); + function pump3() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump3(); + }); + } + }, + cancel() { + reader.releaseLock(); + } + }); + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/http.js +var ProtocolSseTransportAdapter = class { + threadId; + queue = new AsyncQueue; + fetchImpl; + apiUrl; + defaultHeaders; + onRequest; + fetchFactory; + commandsUrl; + streamUrl; + sessionAbortController = new AbortController; + eventStreams = /* @__PURE__ */ new Set; + closed = false; + constructor(options) { + this.fetchImpl = options.fetch ?? fetch; + this.apiUrl = options.apiUrl; + this.defaultHeaders = options.defaultHeaders ?? {}; + this.onRequest = options.onRequest; + this.fetchFactory = options.fetchFactory; + this.threadId = options.threadId; + this.commandsUrl = options.paths?.commands ?? `/threads/${this.threadId}/commands`; + this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; + } + async resolveFetch() { + if (this.fetchFactory) + return await this.fetchFactory(); + return this.fetchImpl; + } + async open() {} + async send(command) { + const response = await this.request(this.commandsUrl, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(command), + signal: this.sessionAbortController.signal + }); + if (response.status === 202 || response.status === 204) + return; + const payload = await response.json(); + if (!isProtocolResponse(payload)) + throw new Error("Protocol command did not return a valid response."); + return payload; + } + events() { + const queue2 = this.queue; + return { [Symbol.asyncIterator]: () => ({ + next: async () => await queue2.shift(), + return: async () => { + queue2.close(); + return { + done: true, + value: undefined + }; + } + }) }; + } + openEventStream(params) { + if (this.closed) + throw new Error("Protocol transport is closed."); + const ac = new AbortController; + this.eventStreams.add(ac); + const streamQueue = new AsyncQueue; + const streamUrl = this.streamUrl; + let resolveReady; + let rejectReady; + const ready = new Promise((resolve2, reject) => { + resolveReady = resolve2; + rejectReady = reject; + }); + const since = params.since; + const startStream = async () => { + try { + const response = await this.request(streamUrl, { + method: "POST", + headers: { + "content-type": "application/json", + accept: "text/event-stream" + }, + body: JSON.stringify({ + channels: params.channels, + ...params.namespaces ? { namespaces: params.namespaces } : {}, + ...params.depth != null ? { depth: params.depth } : {}, + ...typeof since === "number" ? { since } : {} + }), + signal: ac.signal + }); + resolveReady(); + const stream2 = (response.body ?? new ReadableStream({ start(controller) { + controller.close(); + } })).pipeThrough(BytesLineDecoder2()).pipeThrough(SSEDecoder2()); + const iterable = IterableReadableStream3.fromReadableStream(stream2); + for await (const event of iterable) { + if (ac.signal.aborted || this.closed) + break; + if (isRecord3(event.data)) { + const msg = event.data; + streamQueue.push(msg); + } + } + streamQueue.close(); + } catch (error90) { + rejectReady(error90); + if (ac.signal.aborted || this.closed) { + streamQueue.close(); + return; + } + streamQueue.close(error90); + } + }; + startStream(); + const cleanup = () => { + this.eventStreams.delete(ac); + ac.abort(); + streamQueue.close(); + }; return { - assistantId: assistantId != null ? String(assistantId) : "", - graphId: graphId != null ? String(graphId) : "", - user + events: { [Symbol.asyncIterator]: () => ({ + next: async () => await streamQueue.shift(), + return: async () => { + cleanup(); + return { + done: true, + value: undefined + }; + } + }) }, + ready, + close: cleanup }; -} -function _excludeAsMetadata2(key, value) { - const keyLower = key.toLowerCase(); - let hasOmittedSubstring = false; - for (const substr of OMITTED_KEYS2) - if (keyLower.includes(substr)) { - hasOmittedSubstring = true; - break; - } - return key.startsWith("__") || !(typeof value === "string" || typeof value === "number" || typeof value === "boolean") || hasOmittedSubstring; -} -function _getTracingMetadataDefaults2(config2) { - const configurable = config2.configurable; - if (!configurable) - return; - const metadata = {}; - for (const [key, value] of Object.entries(configurable)) { - if (_excludeAsMetadata2(key, value)) - continue; - metadata[key] = value; } - return Object.keys(metadata).length > 0 ? metadata : undefined; -} -var Channel2 = class { - static subscribeTo(channels, options) { - const { key, tags } = { - key: undefined, - tags: undefined, - ...options ?? {} + async close() { + if (this.closed) + return; + this.closed = true; + this.sessionAbortController.abort(); + for (const ac of this.eventStreams) + ac.abort(); + this.eventStreams.clear(); + this.queue.close(); + } + async request(path2, init) { + const url3 = toAbsoluteUrl(this.apiUrl, path2); + let requestInit = { + ...init, + headers: mergeHeaders2(this.defaultHeaders, init.headers) }; - if (Array.isArray(channels) && key !== undefined) - throw new Error("Can't specify a key when subscribing to multiple channels"); - let channelMappingOrArray; - if (typeof channels === "string") - if (key) - channelMappingOrArray = { [key]: channels }; + if (this.onRequest) + requestInit = await this.onRequest(url3, requestInit); + try { + const response = await (await this.resolveFetch())(url3.toString(), requestInit); + if (!response.ok) { + let detail = ""; + try { + const body = await response.text(); + const parsed = JSON.parse(body); + if (typeof parsed === "object" && parsed != null) + detail = parsed.message ?? parsed.error ?? ""; + if (!detail) + detail = body; + } catch {} + const message = detail ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}` : `Protocol request failed: ${response.status} ${response.statusText}`; + throw new Error(message); + } + return response; + } catch (error90) { + throw toError(error90); + } + } +}; +var init_http = __esm(() => { + init_queue(); + init_utils16(); + init_decoder(); + init_stream11(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/websocket.js +var ProtocolWebSocketTransportAdapter = class { + threadId; + queue = new AsyncQueue; + apiUrl; + defaultHeaders; + onRequest; + webSocketFactory; + streamUrl; + pending = /* @__PURE__ */ new Map; + socket = null; + closed = false; + intentionalClose = false; + constructor(options) { + this.apiUrl = options.apiUrl; + this.threadId = options.threadId; + this.defaultHeaders = options.defaultHeaders; + this.onRequest = options.onRequest; + this.webSocketFactory = options.webSocketFactory ?? ((url3) => new WebSocket(url3)); + this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; + } + async open() { + if (this.socket != null) + return; + this.assertBrowserSafeTransportConfig(); + const wsUrl = toWebSocketUrl(toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()); + const socket = this.webSocketFactory(wsUrl); + this.socket = socket; + this.closed = false; + this.intentionalClose = false; + socket.addEventListener("message", this.handleMessage); + socket.addEventListener("close", this.handleClose); + socket.addEventListener("error", this.handleSocketError); + await new Promise((resolve2, reject) => { + const onOpen = () => { + cleanup(); + resolve2(); + }; + const onError2 = () => { + cleanup(); + reject(/* @__PURE__ */ new Error("Failed to open protocol WebSocket.")); + }; + const cleanup = () => { + socket.removeEventListener("open", onOpen); + socket.removeEventListener("error", onError2); + }; + socket.addEventListener("open", onOpen, { once: true }); + socket.addEventListener("error", onError2, { once: true }); + }); + } + async send(command) { + return await this.sendCommand(command); + } + events() { + const queue2 = this.queue; + return { [Symbol.asyncIterator]: () => ({ + next: async () => await queue2.shift(), + return: async () => { + queue2.close(); + return { + done: true, + value: undefined + }; + } + }) }; + } + async close() { + if (this.closed) + return; + this.closed = true; + this.intentionalClose = true; + for (const { reject } of this.pending.values()) + reject(/* @__PURE__ */ new Error("Protocol WebSocket connection closed.")); + this.pending.clear(); + this.queue.close(); + const socket = this.socket; + this.socket = null; + if (!socket) + return; + await new Promise((resolve2) => { + if (socket.readyState === WebSocket.CLOSED) { + resolve2(); + return; + } + const onClose = () => { + socket.removeEventListener("close", onClose); + resolve2(); + }; + socket.addEventListener("close", onClose, { once: true }); + if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) + socket.close(); else - channelMappingOrArray = [channels]; - else - channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); - return new PregelNode3({ - channels: channelMappingOrArray, - triggers: Array.isArray(channels) ? channels : [channels], - tags + resolve2(); }); } - static writeTo(channels, writes) { - const channelWriteEntries = []; - for (const channel of channels) - channelWriteEntries.push({ - channel, - value: PASSTHROUGH2, - skipNone: false + assertBrowserSafeTransportConfig() { + if (hasHeaders(this.defaultHeaders) || this.onRequest != null) + throw new Error("Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup."); + } + async sendCommand(command) { + const socket = this.socket; + if (socket == null || socket.readyState !== WebSocket.OPEN) + throw new Error("Protocol WebSocket is not open."); + return await new Promise((resolve2, reject) => { + this.pending.set(command.id, { + resolve: resolve2, + reject }); - for (const [key, value] of Object.entries(writes ?? {})) - if (Runnable.isRunnable(value) || typeof value === "function") - channelWriteEntries.push({ - channel: key, - value: PASSTHROUGH2, - skipNone: true, - mapper: _coerceToRunnable(value) - }); - else - channelWriteEntries.push({ - channel: key, - value, - skipNone: false - }); - return new ChannelWrite3(channelWriteEntries); + try { + socket.send(JSON.stringify(command)); + } catch (error90) { + this.pending.delete(command.id); + reject(toError(error90)); + } + }); } -}, PartialRunnable2, Pregel2, OMITTED_KEYS2; -var init_pregel2 = __esm(() => { - init_constants8(); - init_errors10(); - init_base17(); - init_config3(); - init_utils17(); - init_write2(); - init_read2(); - init_io2(); - init_utils18(); - init_algo2(); - init_subgraph2(); - init_debug2(); - init_stream12(); - init_loop2(); - init_messages11(); - init_messages_v22(); - init_runner2(); - init_convert2(); - init_run_stream2(); - init_stream11(); - init_validate5(); - init_topic2(); - init_interrupt2(); - init_dist3(); - init_runnables(); - init_manager(); - PartialRunnable2 = class extends Runnable { - lc_namespace = ["langgraph", "pregel"]; - invoke(_input, _options) { - throw new Error("Not implemented"); + handleMessage = (event) => { + let payload; + try { + payload = JSON.parse(String(event.data)); + } catch { + return; } - withConfig(_config) { - return super.withConfig(_config); + if (isRecord3(payload) && typeof payload.id === "number" && (payload.type === "success" || payload.type === "error")) { + const pending = this.pending.get(payload.id); + if (pending) { + this.pending.delete(payload.id); + pending.resolve(payload); + } + return; } - stream(input, options) { - return super.stream(input, options); + if (isRecord3(payload) && payload.type === "event") + this.queue.push(payload); + }; + handleClose = () => { + this.socket = null; + if (this.intentionalClose || this.closed) { + this.queue.close(); + return; } + const error90 = /* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly."); + for (const { reject } of this.pending.values()) + reject(error90); + this.pending.clear(); + this.queue.close(error90); }; - Pregel2 = class extends PartialRunnable2 { - static lc_name() { - return "LangGraph"; + handleSocketError = () => { + if (this.closed || this.intentionalClose) + return; + const error90 = /* @__PURE__ */ new Error("Protocol WebSocket encountered an error."); + for (const { reject } of this.pending.values()) + reject(error90); + this.pending.clear(); + this.queue.close(error90); + }; +}; +var init_websocket = __esm(() => { + init_queue(); + init_utils16(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/agent-server.js +var HttpAgentServerAdapter = class { + threadId; + #delegate; + constructor(options) { + this.threadId = options.threadId; + this.#delegate = options.webSocketFactory != null ? new ProtocolWebSocketTransportAdapter({ + apiUrl: options.apiUrl, + threadId: options.threadId, + defaultHeaders: options.defaultHeaders, + onRequest: options.onRequest, + paths: options.paths, + webSocketFactory: options.webSocketFactory + }) : new ProtocolSseTransportAdapter({ + apiUrl: options.apiUrl, + threadId: options.threadId, + defaultHeaders: options.defaultHeaders, + onRequest: options.onRequest, + fetch: options.fetch, + paths: options.paths + }); + } + open() { + return this.#delegate.open(); + } + send(command) { + return this.#delegate.send(command); + } + events() { + return this.#delegate.events(); + } + openEventStream(params) { + if (this.#delegate.openEventStream == null) + throw new Error("HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path)."); + return this.#delegate.openEventStream(params); + } + close() { + return this.#delegate.close(); + } +}; +var init_agent_server = __esm(() => { + init_http(); + init_websocket(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/assistants/index.js +var AssistantsClient; +var init_assistants = __esm(() => { + init_base17(); + AssistantsClient = class extends BaseClient { + async get(assistantId, options) { + return this.fetch(`/assistants/${assistantId}`, { signal: options?.signal }); } - lc_namespace = ["langgraph", "pregel"]; - lg_is_pregel = true; - nodes; - channels; - inputChannels; - outputChannels; - autoValidate = true; - streamMode = ["values"]; - streamChannels; - interruptAfter; - interruptBefore; - stepTimeout; - debug = false; - checkpointer; - retryPolicy; - config; - store; - cache; - userInterrupt; - streamTransformers; - triggerToNodes = {}; - constructor(fields) { - super(fields); - let { streamMode } = fields; - if (streamMode != null && !Array.isArray(streamMode)) - streamMode = [streamMode]; - this.nodes = fields.nodes; - this.channels = fields.channels; - if ("__pregel_tasks" in this.channels && "lc_graph_name" in this.channels["__pregel_tasks"] && this.channels["__pregel_tasks"].lc_graph_name !== "Topic") - throw new Error(`Channel '${TASKS3}' is reserved and cannot be used in the graph.`); - else - this.channels[TASKS3] = new Topic3({ accumulate: false }); - this.autoValidate = fields.autoValidate ?? this.autoValidate; - this.streamMode = streamMode ?? this.streamMode; - this.inputChannels = fields.inputChannels; - this.outputChannels = fields.outputChannels; - this.streamChannels = fields.streamChannels ?? this.streamChannels; - this.interruptAfter = fields.interruptAfter; - this.interruptBefore = fields.interruptBefore; - this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; - this.debug = fields.debug ?? this.debug; - this.checkpointer = fields.checkpointer; - this.retryPolicy = fields.retryPolicy; - this.config = fields.config; - this.store = fields.store; - this.cache = fields.cache; - this.name = fields.name; - this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; - this.userInterrupt = fields.userInterrupt; - this.streamTransformers = fields.streamTransformers ?? []; - if (this.autoValidate) - this.validate(); + async getGraph(assistantId, options) { + return this.fetch(`/assistants/${assistantId}/graph`, { + params: { xray: options?.xray }, + signal: options?.signal + }); } - withConfig(config2) { - const { streamTransformers, ...restConfig } = config2; - const mergedConfig = mergeConfigs(this.config, restConfig); - const mergedStreamTransformers = [...this.streamTransformers, ...streamTransformers ?? []]; - return new this.constructor({ - ...this, - config: mergedConfig, - streamTransformers: mergedStreamTransformers + async getSchemas(assistantId, options) { + return this.fetch(`/assistants/${assistantId}/schemas`, { signal: options?.signal }); + } + async getSubgraphs(assistantId, options) { + if (options?.namespace) + return this.fetch(`/assistants/${assistantId}/subgraphs/${options.namespace}`, { + params: { recurse: options?.recurse }, + signal: options?.signal + }); + return this.fetch(`/assistants/${assistantId}/subgraphs`, { + params: { recurse: options?.recurse }, + signal: options?.signal }); } - validate() { - validateGraph2({ - nodes: this.nodes, - channels: this.channels, - outputChannels: this.outputChannels, - inputChannels: this.inputChannels, - streamChannels: this.streamChannels, - interruptAfterNodes: this.interruptAfter, - interruptBeforeNodes: this.interruptBefore + async create(payload) { + return this.fetch("/assistants", { + method: "POST", + json: { + graph_id: payload.graphId, + config: payload.config, + context: payload.context, + metadata: payload.metadata, + assistant_id: payload.assistantId, + if_exists: payload.ifExists, + name: payload.name, + description: payload.description + }, + signal: payload.signal }); - for (const [name, node] of Object.entries(this.nodes)) - for (const trigger of node.triggers) { - this.triggerToNodes[trigger] ??= []; - this.triggerToNodes[trigger].push(name); - } - return this; } - get streamChannelsList() { - if (Array.isArray(this.streamChannels)) - return this.streamChannels; - else if (this.streamChannels) - return [this.streamChannels]; - else - return Object.keys(this.channels); + async update(assistantId, payload) { + return this.fetch(`/assistants/${assistantId}`, { + method: "PATCH", + json: { + graph_id: payload.graphId, + config: payload.config, + context: payload.context, + metadata: payload.metadata, + name: payload.name, + description: payload.description + }, + signal: payload.signal + }); } - get streamChannelsAsIs() { - if (this.streamChannels) - return this.streamChannels; - else - return Object.keys(this.channels); + async delete(assistantId, options) { + return this.fetch(`/assistants/${assistantId}?delete_threads=${options?.deleteThreads ?? false}`, { + method: "DELETE", + signal: options?.signal + }); } - async getGraphAsync(config2) { - return this.getGraph(config2); + async search(query3) { + const json3 = { + graph_id: query3?.graphId ?? undefined, + name: query3?.name ?? undefined, + metadata: query3?.metadata ?? undefined, + limit: query3?.limit ?? 10, + offset: query3?.offset ?? 0, + sort_by: query3?.sortBy ?? undefined, + sort_order: query3?.sortOrder ?? undefined, + select: query3?.select ?? undefined + }; + const [assistants, response] = await this.fetch("/assistants/search", { + method: "POST", + json: json3, + withResponse: true, + signal: query3?.signal + }); + if (query3?.includePagination) + return { + assistants, + next: response.headers.get("X-Pagination-Next") + }; + return assistants; } - *getSubgraphs(namespace, recurse) { - for (const [name, node] of Object.entries(this.nodes)) { - if (namespace !== undefined) { - if (!namespace.startsWith(name)) - continue; - } - const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; - for (const candidate of candidates) { - const graph = findSubgraphPregel2(candidate); - if (graph !== undefined) { - if (name === namespace) { - yield [name, graph]; - return; - } - if (namespace === undefined) - yield [name, graph]; - if (recurse) { - let newNamespace = namespace; - if (namespace !== undefined) - newNamespace = namespace.slice(name.length + 1); - for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) - yield [`${name}|${subgraphName}`, subgraph]; - } - } - } - } + async count(query3) { + return this.fetch(`/assistants/count`, { + method: "POST", + json: { + metadata: query3?.metadata ?? undefined, + graph_id: query3?.graphId ?? undefined, + name: query3?.name ?? undefined + }, + signal: query3?.signal + }); } - async* getSubgraphsAsync(namespace, recurse) { - yield* this.getSubgraphs(namespace, recurse); + async getVersions(assistantId, payload) { + return this.fetch(`/assistants/${assistantId}/versions`, { + method: "POST", + json: { + metadata: payload?.metadata ?? undefined, + limit: payload?.limit ?? 10, + offset: payload?.offset ?? 0 + }, + signal: payload?.signal + }); } - async _prepareStateSnapshot({ config: config2, saved, subgraphCheckpointer, applyPendingWrites = false }) { - if (saved === undefined) - return { - values: {}, - next: [], - config: config2, - tasks: [] - }; - const channels = emptyChannels2(this.channels, saved.checkpoint); - if (saved.pendingWrites?.length) { - const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID2).map(([_, channel, value]) => [String(channel), value]); - if (nullWrites.length > 0) - _applyWrites2(saved.checkpoint, channels, [{ - name: INPUT2, - writes: nullWrites, - triggers: [] - }], undefined, this.triggerToNodes); - } - const nextTasks = Object.values(_prepareNextTasks2(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - store: this.store - })); - const subgraphs = await gatherIterator2(this.getSubgraphsAsync()); - const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; - const taskStates = {}; - for (const task2 of nextTasks) { - const matchingSubgraph = subgraphs.find(([name]) => name === task2.name); - if (!matchingSubgraph) - continue; - let taskNs = `${String(task2.name)}:${task2.id}`; - if (parentNamespace) - taskNs = `${parentNamespace}|${taskNs}`; - if (subgraphCheckpointer === undefined) { - const config3 = { configurable: { - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - taskStates[task2.id] = config3; - } else { - const subgraphConfig = { configurable: { - [CONFIG_KEY_CHECKPOINTER2]: subgraphCheckpointer, - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - const pregel = matchingSubgraph[1]; - taskStates[task2.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); - } - } - if (applyPendingWrites && saved.pendingWrites?.length) { - const nextTaskById = Object.fromEntries(nextTasks.map((task2) => [task2.id, task2])); - for (const [taskId, channel, value] of saved.pendingWrites) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(channel)) - continue; - if (!(taskId in nextTaskById)) - continue; - nextTaskById[taskId].writes.push([String(channel), value]); - } - const tasksWithWrites3 = nextTasks.filter((task2) => task2.writes.length > 0); - if (tasksWithWrites3.length > 0) - _applyWrites2(saved.checkpoint, channels, tasksWithWrites3, undefined, this.triggerToNodes); - } - let metadata = saved?.metadata; - if (metadata && saved?.config?.configurable?.thread_id) - metadata = { - ...metadata, - thread_id: saved.config.configurable.thread_id - }; - const nextList = nextTasks.filter((task2) => task2.writes.length === 0).map((task2) => task2.name); - return { - values: readChannels2(channels, this.streamChannelsAsIs), - next: nextList, - tasks: tasksWithWrites2(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), - metadata, - config: patchCheckpointMap2(saved.config, saved.metadata), - createdAt: saved.checkpoint.ts, - parentConfig: saved.parentConfig - }; + async setLatest(assistantId, version6, options) { + return this.fetch(`/assistants/${assistantId}/latest`, { + method: "POST", + json: { version: version6 }, + signal: options?.signal + }); } - async getState(config2, options) { - const checkpointer = config2.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config2.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config2.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); - for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) - if (name === recastNamespace) - return await subgraph.getState(patchConfigurable3(config2, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), { subgraphs: options?.subgraphs }); - } - const mergedConfig = mergeConfigs(this.config, config2); - const saved = await checkpointer.getTuple(config2); - return await this._prepareStateSnapshot({ - config: mergedConfig, - saved, - subgraphCheckpointer: options?.subgraphs ? checkpointer : undefined, - applyPendingWrites: !config2.configurable?.checkpoint_id + }; +}); + +// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/rng.js +import { randomFillSync } from "node:crypto"; +function rng3() { + if (poolPtr > rnds8Pool.length - 16) { + randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} +var rnds8Pool, poolPtr; +var init_rng3 = __esm(() => { + rnds8Pool = new Uint8Array(256); + poolPtr = rnds8Pool.length; +}); + +// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/stringify.js +function unsafeStringify4(arr3, offset = 0) { + return (byteToHex4[arr3[offset + 0]] + byteToHex4[arr3[offset + 1]] + byteToHex4[arr3[offset + 2]] + byteToHex4[arr3[offset + 3]] + "-" + byteToHex4[arr3[offset + 4]] + byteToHex4[arr3[offset + 5]] + "-" + byteToHex4[arr3[offset + 6]] + byteToHex4[arr3[offset + 7]] + "-" + byteToHex4[arr3[offset + 8]] + byteToHex4[arr3[offset + 9]] + "-" + byteToHex4[arr3[offset + 10]] + byteToHex4[arr3[offset + 11]] + byteToHex4[arr3[offset + 12]] + byteToHex4[arr3[offset + 13]] + byteToHex4[arr3[offset + 14]] + byteToHex4[arr3[offset + 15]]).toLowerCase(); +} +var byteToHex4; +var init_stringify3 = __esm(() => { + byteToHex4 = []; + for (let i = 0;i < 256; ++i) { + byteToHex4.push((i + 256).toString(16).slice(1)); + } +}); + +// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/v7.js +function v75(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes3(options.random ?? options.rng?.() ?? rng3(), options.msecs, options.seq, buf, offset); + } else { + const now = Date.now(); + const rnds = rng3(); + updateV7State3(_state4, now, rnds); + bytes = v7Bytes3(rnds, _state4.msecs, _state4.seq, buf, offset); + } + return buf ?? unsafeStringify4(bytes); +} +function updateV7State3(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + state.msecs = now; + } else { + state.seq = state.seq + 1 | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +function v7Bytes3(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error("Random bytes length must be >= 16"); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9]; + buf[offset++] = msecs / 1099511627776 & 255; + buf[offset++] = msecs / 4294967296 & 255; + buf[offset++] = msecs / 16777216 & 255; + buf[offset++] = msecs / 65536 & 255; + buf[offset++] = msecs / 256 & 255; + buf[offset++] = msecs & 255; + buf[offset++] = 112 | seq >>> 28 & 15; + buf[offset++] = seq >>> 20 & 255; + buf[offset++] = 128 | seq >>> 14 & 63; + buf[offset++] = seq >>> 6 & 255; + buf[offset++] = seq << 2 & 255 | rnds[10] & 3; + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +var _state4, v7_default2; +var init_v73 = __esm(() => { + init_rng3(); + init_stringify3(); + _state4 = {}; + v7_default2 = v75; +}); + +// ../../node_modules/.pnpm/uuid@13.0.2/node_modules/uuid/dist-node/index.js +var init_dist_node = __esm(() => { + init_v73(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/threads/index.js +var ThreadsClient; +var init_threads = __esm(() => { + init_base17(); + init_stream10(); + init_http(); + init_websocket(); + init_dist_node(); + ThreadsClient = class extends BaseClient { + async get(threadId, options) { + return this.fetch(`/threads/${threadId}`, { + params: { include: options?.include ?? undefined }, + signal: options?.signal }); } - async* getStateHistory(config2, options) { - const checkpointer = config2.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config2.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config2.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); - for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) - if (name === recastNamespace) { - yield* pregel.getStateHistory(patchConfigurable3(config2, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), options); - return; - } - } - const mergedConfig = mergeConfigs(this.config, config2, { configurable: { checkpoint_ns: checkpointNamespace } }); - for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) - yield this._prepareStateSnapshot({ - config: checkpointTuple.config, - saved: checkpointTuple - }); + async create(payload) { + const ttlPayload = typeof payload?.ttl === "number" ? { + ttl: payload.ttl, + strategy: "delete" + } : payload?.ttl; + return this.fetch(`/threads`, { + method: "POST", + json: { + metadata: { + ...payload?.metadata, + graph_id: payload?.graphId + }, + thread_id: payload?.threadId, + if_exists: payload?.ifExists, + supersteps: payload?.supersteps?.map((s) => ({ updates: s.updates.map((u) => ({ + values: u.values, + command: u.command, + as_node: u.asNode + })) })), + ttl: ttlPayload + }, + signal: payload?.signal + }); } - async bulkUpdateState(startConfig, supersteps) { - const checkpointer = startConfig.configurable?.["__pregel_checkpointer"] ?? this.checkpointer; - if (!checkpointer) - throw new GraphValueError2("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - if (supersteps.length === 0) - throw new Error("No supersteps provided"); - if (supersteps.some((s) => s.updates.length === 0)) - throw new Error("No updates provided"); - const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && startConfig.configurable?.["__pregel_checkpointer"] === undefined) { - const recastNamespace = recastCheckpointNamespace2(checkpointNamespace); - for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) - return await pregel.bulkUpdateState(patchConfigurable3(startConfig, { [CONFIG_KEY_CHECKPOINTER2]: checkpointer }), supersteps); - throw new Error(`Subgraph "${recastNamespace}" not found`); - } - const updateSuperStep = async (inputConfig, updates) => { - const config2 = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; - const saved = await checkpointer.getTuple(config2); - const checkpoint = saved !== undefined ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); - const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; - const step = saved?.metadata?.step ?? -1; - let checkpointConfig = patchConfigurable3(config2, { checkpoint_ns: config2.configurable?.checkpoint_ns ?? "" }); - let checkpointMetadata = config2.metadata ?? {}; - if (saved?.config.configurable) { - checkpointConfig = patchConfigurable3(config2, saved.config.configurable); - checkpointMetadata = { - ...saved.metadata, - ...checkpointMetadata - }; - } - const { values: values2, asNode } = updates[0]; - if (values2 == null && asNode === undefined) { - if (updates.length > 1) - throw new InvalidUpdateError2(`Cannot create empty checkpoint with multiple updates`); - return patchCheckpointMap2(await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, undefined, step), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, {}), saved ? saved.metadata : undefined); - } - const channels = emptyChannels2(this.channels, checkpoint); - if (values2 === null && asNode === "__end__") { - if (updates.length > 1) - throw new InvalidUpdateError2(`Cannot apply multiple updates when clearing state`); - if (saved) { - const nextTasks = _prepareNextTasks2(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - checkpointer, - store: this.store - }); - const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites2(checkpoint, channels, [{ - name: INPUT2, - writes: nullWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - for (const [taskId, k, v] of saved.pendingWrites || []) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(k)) - continue; - if (!(taskId in nextTasks)) - continue; - nextTasks[taskId].writes.push([k, v]); - } - _applyWrites2(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - } - return patchCheckpointMap2(await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, step), { - ...checkpointMetadata, - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions)), saved ? saved.metadata : undefined); - } - if (asNode === "__copy__") { - if (updates.length > 1) - throw new InvalidUpdateError2(`Cannot copy checkpoint with multiple updates`); - if (saved == null) - throw new InvalidUpdateError2(`Cannot copy a non-existent checkpoint`); - const isCopyWithUpdates = (values3) => { - if (!Array.isArray(values3)) - return false; - if (values3.length === 0) - return false; - return values3.every((v) => Array.isArray(v) && v.length === 2); - }; - const nextCheckpoint = createCheckpoint2(checkpoint, undefined, step); - const nextConfig2 = await checkpointer.put(saved.parentConfig ?? patchConfigurable3(saved.config, { checkpoint_id: undefined }), nextCheckpoint, { - source: "fork", - step: step + 1, - parents: saved.metadata?.parents ?? {} - }, {}); - if (isCopyWithUpdates(values2)) { - const nextTasks = _prepareNextTasks2(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig2, false, { step: step + 2 }); - const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { - acc[name] ??= []; - acc[name].push({ id }); - return acc; - }, {}); - const userGroupBy = values2.reduce((acc, item) => { - const [values3, asNode2] = item; - acc[asNode2] ??= []; - const targetIdx = acc[asNode2].length; - const taskId = tasksGroupBy[asNode2]?.[targetIdx]?.id; - acc[asNode2].push({ - values: values3, - asNode: asNode2, - taskId - }); - return acc; - }, {}); - return updateSuperStep(patchCheckpointMap2(nextConfig2, saved.metadata), Object.values(userGroupBy).flat()); - } - return patchCheckpointMap2(nextConfig2, saved.metadata); - } - if (asNode === "__input__") { - if (updates.length > 1) - throw new InvalidUpdateError2(`Cannot apply multiple updates when updating as input`); - const inputWrites = await gatherIterator2(mapInput2(this.inputChannels, values2)); - if (inputWrites.length === 0) - throw new InvalidUpdateError2(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); - _applyWrites2(checkpoint, channels, [{ - name: INPUT2, - writes: inputWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; - const nextConfig2 = await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, nextStep), { - source: "input", - step: nextStep, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions)); - await checkpointer.putWrites(nextConfig2, inputWrites, uuid5(INPUT2, checkpoint.id)); - return patchCheckpointMap2(nextConfig2, saved ? saved.metadata : undefined); - } - if (config2.configurable?.checkpoint_id === undefined && saved?.pendingWrites !== undefined && saved.pendingWrites.length > 0) { - const nextTasks = _prepareNextTasks2(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - store: this.store, - checkpointer: this.checkpointer, - step: (saved.metadata?.step ?? -1) + 1 - }); - const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID2).map((w) => w.slice(1)); - if (nullWrites.length > 0) - _applyWrites2(saved.checkpoint, channels, [{ - name: INPUT2, - writes: nullWrites, - triggers: [] - }], undefined, this.triggerToNodes); - for (const [tid, k, v] of saved.pendingWrites) { - if ([ - "__error__", - "__interrupt__", - SCHEDULED - ].includes(k) || nextTasks[tid] === undefined) - continue; - nextTasks[tid].writes.push([k, v]); - } - const tasks2 = Object.values(nextTasks).filter((task2) => { - return task2.writes.length > 0; - }); - if (tasks2.length > 0) - _applyWrites2(checkpoint, channels, tasks2, undefined, this.triggerToNodes); - } - const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { - return Object.values(seenVersions); - }).flat().find((v) => !!v); - const validUpdates = []; - if (updates.length === 1) { - let { values: values3, asNode: asNode2, taskId } = updates[0]; - if (asNode2 === undefined && Object.keys(this.nodes).length === 1) - [asNode2] = Object.keys(this.nodes); - else if (asNode2 === undefined && nonNullVersion === undefined) { - if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== undefined) - asNode2 = this.inputChannels; - } else if (asNode2 === undefined) { - const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n4, seen]) => { - return Object.values(seen).map((v) => { - return [v, n4]; - }); - }).flat().filter(([_, v]) => v !== INTERRUPT3).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); - if (lastSeenByNode) { - if (lastSeenByNode.length === 1) - asNode2 = lastSeenByNode[0][1]; - else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) - asNode2 = lastSeenByNode[lastSeenByNode.length - 1][1]; - } - } - if (asNode2 === undefined) - throw new InvalidUpdateError2(`Ambiguous update, specify "asNode"`); - validUpdates.push({ - values: values3, - asNode: asNode2, - taskId - }); - } else - for (const { asNode: asNode2, values: values3, taskId } of updates) { - if (asNode2 == null) - throw new InvalidUpdateError2(`"asNode" is required when applying multiple updates`); - validUpdates.push({ - values: values3, - asNode: asNode2, - taskId - }); - } - const tasks = []; - for (const { asNode: asNode2, values: values3, taskId } of validUpdates) { - if (this.nodes[asNode2] === undefined) - throw new InvalidUpdateError2(`Node "${asNode2.toString()}" does not exist`); - const writers = this.nodes[asNode2].getWriters(); - if (!writers.length) - throw new InvalidUpdateError2(`No writers found for node "${asNode2.toString()}"`); - tasks.push({ - name: asNode2, - input: values3, - proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], - writes: [], - triggers: [INTERRUPT3], - id: taskId ?? uuid5("__interrupt__", checkpoint.id), - writers: [] - }); - } - for (const task2 of tasks) - await task2.proc.invoke(task2.input, patchConfig({ - ...config2, - store: config2?.store ?? this.store - }, { - runName: config2.runName ?? `${this.getName()}UpdateState`, - configurable: { - [CONFIG_KEY_SEND2]: (items) => task2.writes.push(...items), - [CONFIG_KEY_READ2]: (select_, fresh_ = false) => _localRead2(checkpoint, channels, task2, select_, fresh_) - } - })); - for (const task2 of tasks) { - const channelWrites = task2.writes.filter((w) => w[0] !== PUSH2); - if (saved !== undefined && channelWrites.length > 0) - await checkpointer.putWrites(checkpointConfig, channelWrites, task2.id); - } - _applyWrites2(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const newVersions = getNewChannelVersions2(checkpointPreviousVersions, checkpoint.channel_versions); - const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint2(checkpoint, channels, step + 1), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, newVersions); - for (const task2 of tasks) { - const pushWrites = task2.writes.filter((w) => w[0] === PUSH2); - if (pushWrites.length > 0) - await checkpointer.putWrites(nextConfig, pushWrites, task2.id); - } - return patchCheckpointMap2(nextConfig, saved ? saved.metadata : undefined); - }; - let currentConfig = startConfig; - for (const { updates } of supersteps) - currentConfig = await updateSuperStep(currentConfig, updates); - return currentConfig; + async copy(threadId, options) { + return this.fetch(`/threads/${threadId}/copy`, { + method: "POST", + signal: options?.signal + }); } - async updateState(inputConfig, values2, asNode) { - return this.bulkUpdateState(inputConfig, [{ updates: [{ - values: values2, - asNode - }] }]); + async update(threadId, payload) { + const ttlPayload = typeof payload?.ttl === "number" ? { + ttl: payload.ttl, + strategy: "delete" + } : payload?.ttl; + return this.fetch(`/threads/${threadId}`, { + method: "PATCH", + headers: payload?.returnMinimal ? { Prefer: "return=minimal" } : undefined, + json: { + metadata: payload?.metadata, + ttl: ttlPayload + }, + signal: payload?.signal + }); } - _defaults(config2) { - const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore, ...rest } = config2; - let streamModeSingle = true; - const defaultDebug = debug !== undefined ? debug : this.debug; - let defaultOutputKeys = outputKeys; - if (defaultOutputKeys === undefined) - defaultOutputKeys = this.streamChannelsAsIs; - else - validateKeys2(defaultOutputKeys, this.channels); - let defaultInputKeys = inputKeys; - if (defaultInputKeys === undefined) - defaultInputKeys = this.inputChannels; - else - validateKeys2(defaultInputKeys, this.channels); - const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; - const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; - let defaultStreamMode; - if (streamMode !== undefined) { - defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; - streamModeSingle = typeof streamMode === "string"; - } else { - if (config2.configurable?.["__pregel_task_id"] !== undefined) - defaultStreamMode = ["values"]; - else - defaultStreamMode = this.streamMode; - streamModeSingle = true; - } - let defaultCheckpointer; - if (this.checkpointer === false) - defaultCheckpointer = undefined; - else if (config2 !== undefined && config2.configurable?.["__pregel_checkpointer"] !== undefined) - defaultCheckpointer = config2.configurable[CONFIG_KEY_CHECKPOINTER2]; - else if (this.checkpointer === true) - throw new Error("checkpointer: true cannot be used for root graphs."); - else - defaultCheckpointer = this.checkpointer; - const defaultStore = config2.store ?? this.store; - const defaultCache = config2.cache ?? this.cache; - if (config2.durability != null && config2.checkpointDuring != null) - throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); - const checkpointDuringDurability = (() => { - if (config2.checkpointDuring == null) - return; - if (config2.checkpointDuring === false) - return "exit"; - return "async"; - })(); - const defaultDurability = config2.durability ?? checkpointDuringDurability ?? config2?.configurable?.["__pregel_durability"] ?? "async"; - return [ - defaultDebug, - defaultStreamMode, - defaultInputKeys, - defaultOutputKeys, - rest, - defaultInterruptBefore, - defaultInterruptAfter, - defaultCheckpointer, - defaultStore, - streamModeSingle, - defaultCache, - defaultDurability - ]; + async delete(threadId, options) { + return this.fetch(`/threads/${threadId}`, { + method: "DELETE", + signal: options?.signal + }); } - async stream(input, options) { - const abortController = new AbortController; - const config2 = { - recursionLimit: this.config?.recursionLimit, - ...options, - signal: combineAbortSignals2(options?.signal, abortController.signal).signal - }; - const stream2 = await super.stream(input, config2); - return new IterableReadableStreamWithAbortSignal2(options?.encoding === "text/event-stream" ? toEventStream2(stream2) : stream2, abortController); + async prune(threadIds, options) { + return this.fetch("/threads/prune", { + method: "POST", + json: { + thread_ids: threadIds, + strategy: options?.strategy ?? "delete" + }, + signal: options?.signal + }); } - async#streamEventsV3(input, options) { - const { version: version4, encoding, transformers: userTransformers, ...restOptions } = options; - const streamOptions = { - recursionLimit: this.config?.recursionLimit, - ...restOptions, - configurable: { - ...this.config?.configurable, - ...restOptions?.configurable + async search(query3) { + return this.fetch("/threads/search", { + method: "POST", + json: { + metadata: query3?.metadata ?? undefined, + ids: query3?.ids ?? undefined, + limit: query3?.limit ?? 10, + offset: query3?.offset ?? 0, + status: query3?.status, + sort_by: query3?.sortBy, + sort_order: query3?.sortOrder, + select: query3?.select ?? undefined, + values: query3?.values ?? undefined, + extract: query3?.extract ?? undefined }, - version: version4, - streamMode: STREAM_EVENTS_V3_MODES2, - subgraphs: true, - encoding: undefined - }; - const sourcePromise = this.stream(input, streamOptions); - const graphRun = createGraphRunStream2({ [Symbol.asyncIterator]: async function* () { - const src = await sourcePromise; - for await (const chunk of src) - yield chunk; - } }, [...this.streamTransformers ?? [], ...userTransformers ?? []]); - if (encoding === "text/event-stream") { - const abortController = new AbortController; - abortController.signal.addEventListener("abort", () => graphRun.abort(abortController.signal.reason), { once: true }); - return new IterableReadableStreamWithAbortSignal2(protocolEventsToEventStream2(graphRun), abortController); + signal: query3?.signal + }); + } + async count(query3) { + return this.fetch(`/threads/count`, { + method: "POST", + json: { + metadata: query3?.metadata ?? undefined, + values: query3?.values ?? undefined, + status: query3?.status ?? undefined + }, + signal: query3?.signal + }); + } + async getState(threadId, checkpoint, options) { + if (checkpoint != null) { + if (typeof checkpoint !== "string") + return this.fetch(`/threads/${threadId}/state/checkpoint`, { + method: "POST", + json: { + checkpoint, + subgraphs: options?.subgraphs + }, + signal: options?.signal + }); + return this.fetch(`/threads/${threadId}/state/${checkpoint}`, { + params: { subgraphs: options?.subgraphs }, + signal: options?.signal + }); } - return graphRun; + return this.fetch(`/threads/${threadId}/state`, { + params: { subgraphs: options?.subgraphs }, + signal: options?.signal + }); } - streamEvents(input, options, streamOptions) { - if (options.version === "v3") - return this.#streamEventsV3(input, options); - const abortController = new AbortController; - const config2 = { - recursionLimit: this.config?.recursionLimit, - ...options, - callbacks: combineCallbacks2(this.config?.callbacks, options?.callbacks), - signal: combineAbortSignals2(options?.signal, abortController.signal).signal - }; - return new IterableReadableStreamWithAbortSignal2(super.streamEvents(input, config2, streamOptions), abortController); + async updateState(threadId, options) { + return this.fetch(`/threads/${threadId}/state`, { + method: "POST", + json: { + values: options.values, + checkpoint: options.checkpoint, + checkpoint_id: options.checkpointId, + as_node: options?.asNode + }, + signal: options?.signal + }); } - async _validateInput(input) { - return input; + async patchState(threadIdOrConfig, metadata, options) { + let threadId; + if (typeof threadIdOrConfig !== "string") { + if (typeof threadIdOrConfig.configurable?.thread_id !== "string") + throw new Error("Thread ID is required when updating state with a config."); + threadId = threadIdOrConfig.configurable.thread_id; + } else + threadId = threadIdOrConfig; + return this.fetch(`/threads/${threadId}/state`, { + method: "PATCH", + json: { metadata }, + signal: options?.signal + }); } - async _validateContext(context2) { - return context2; + async getHistory(threadId, options) { + return this.fetch(`/threads/${threadId}/history`, { + method: "POST", + json: { + limit: options?.limit ?? 10, + before: options?.before, + metadata: options?.metadata, + checkpoint: options?.checkpoint + }, + signal: options?.signal + }); } - async* _streamIterator(input, options) { - const streamEncoding = "version" in (options ?? {}) ? undefined : options?.encoding ?? undefined; - const streamSubgraphs = options?.subgraphs; - const inputConfig = ensureLangGraphConfig2(this.config, options); - if (inputConfig.recursionLimit === undefined || inputConfig.recursionLimit < 1) - throw new Error(`Passed "recursionLimit" must be at least 1.`); - if (this.checkpointer !== undefined && this.checkpointer !== false && inputConfig.configurable === undefined) - throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); - const validInput = await this._validateInput(input); - const { runId, ...restConfig } = inputConfig; - const [debug, streamMode, , outputKeys, config2, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache2, durability] = this._defaults(restConfig); - config2.metadata = { - ls_integration: "langgraph", - ...config2.metadata + async* joinStream(threadId, options) { + yield* this.streamWithRetry({ + endpoint: `/threads/${threadId}/stream`, + method: "GET", + signal: options?.signal, + headers: options?.lastEventId ? { "Last-Event-ID": options.lastEventId } : undefined, + params: options?.streamMode ? { stream_mode: options.streamMode } : undefined + }); + } + stream(threadIdOrOptions, maybeOptions) { + const { threadId, options } = typeof threadIdOrOptions === "string" ? { + threadId: threadIdOrOptions, + options: maybeOptions + } : { + threadId: v7_default2(), + options: threadIdOrOptions }; - if (typeof config2.context !== "undefined") - config2.context = await this._validateContext(config2.context); + let transport; + if (options.transport != null && typeof options.transport !== "string") + transport = options.transport; else - config2.configurable = await this._validateContext(config2.configurable); - const stream2 = new IterableReadableWritableStream2({ modes: new Set(streamMode) }); - if (this.checkpointer === true) { - config2.configurable ??= {}; - const ns3 = config2.configurable["checkpoint_ns"] ?? ""; - config2.configurable[CONFIG_KEY_CHECKPOINT_NS2] = ns3.split("|").map((part) => part.split(":")[0]).join("|"); - } - if (streamMode.includes("messages")) { - const messageStreamer = options?.version === "v3" ? new StreamProtocolMessagesHandler2((chunk) => stream2.push(chunk)) : new StreamMessagesHandler2((chunk) => stream2.push(chunk)); - const { callbacks } = config2; - if (callbacks === undefined) - config2.callbacks = [messageStreamer]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat(messageStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(messageStreamer, true); - config2.callbacks = copiedCallbacks; - } - } - if (streamMode.includes("tools")) { - const toolStreamer = new StreamToolsHandler2((chunk) => stream2.push(chunk)); - const { callbacks } = config2; - if (callbacks === undefined) - config2.callbacks = [toolStreamer]; - else if (Array.isArray(callbacks)) - config2.callbacks = callbacks.concat(toolStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(toolStreamer, true); - config2.callbacks = copiedCallbacks; - } - } - config2.writer ??= (chunk) => { - if (!streamMode.includes("custom")) - return; - const ns3 = getConfig2()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS2]?.split("|").slice(0, -1); - stream2.push([ - ns3 ?? [], - "custom", - chunk - ]); - }; - config2.interrupt ??= this.userInterrupt ?? interrupt2; - if (config2.serverInfo == null) - config2.serverInfo = _buildServerInfo2(config2); - const callbackManagerOptions = { tracerInheritableMetadata: _getTracingMetadataDefaults2(config2) }; - const runManager = await (await CallbackManager._configureSync(config2?.callbacks, undefined, config2?.tags, undefined, config2?.metadata, undefined, callbackManagerOptions))?.handleChainStart(this.toJSON(), _coerceToDict4(input, "input"), runId, undefined, undefined, undefined, config2?.runName ?? this.getName()); - const channelSpecs = getOnlyChannels2(this.channels); - let loop; - let loopError; - const createAndRunLoop = async () => { - try { - loop = await PregelLoop3.initialize({ - input: validInput, - config: config2, - checkpointer, - nodes: this.nodes, - channelSpecs, - outputKeys, - streamKeys: this.streamChannelsAsIs, - store, - cache: cache2, - stream: stream2, - interruptAfter, - interruptBefore, - manager: runManager, - debug: this.debug, - triggerToNodes: this.triggerToNodes, - durability - }); - const runner = new PregelRunner2({ - loop, - nodeFinished: config2.configurable?.[CONFIG_KEY_NODE_FINISHED2] - }); - if (options?.subgraphs) - loop.config.configurable = { - ...loop.config.configurable, - [CONFIG_KEY_STREAM2]: loop.stream - }; - await this._runLoop({ - loop, - runner, - debug, - config: config2 - }); - if (durability === "sync") - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = e; - } finally { - try { - if (loop) { - await loop.store?.stop(); - await loop.cache?.stop(); - } - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = loopError ?? e; - } - if (loopError) - stream2.error(loopError); - else - stream2.close(); - } + transport = (options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse")) === "websocket" ? new ProtocolWebSocketTransportAdapter({ + apiUrl: this.apiUrl, + threadId, + defaultHeaders: this.defaultHeaders, + onRequest: this.onRequest, + webSocketFactory: options.webSocketFactory + }) : new ProtocolSseTransportAdapter({ + apiUrl: this.apiUrl, + threadId, + defaultHeaders: this.defaultHeaders, + onRequest: this.onRequest, + fetch: options.fetch + }); + return new ThreadStream(transport, options); + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/runs/index.js +var RunsClient; +var init_runs = __esm(() => { + init_base17(); + RunsClient = class extends BaseClient { + async* stream(threadId, assistantId, payload) { + const json3 = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + feedback_keys: payload?.feedbackKeys, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + checkpoint: payload?.checkpoint, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + on_completion: payload?.onCompletion, + on_disconnect: payload?.onDisconnect, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability }; - const runLoopPromise = createAndRunLoop(); - try { - for await (const chunk of stream2) { - if (chunk === undefined) - throw new Error("Data structure error."); - const [namespace, mode, payload, meta3] = chunk; - if (streamMode.includes(mode)) { - if (streamEncoding === "text/event-stream") { - if (streamSubgraphs) - yield [ - namespace, - mode, - payload - ]; - else - yield [ - null, - mode, - payload - ]; - continue; - } - if (streamSubgraphs && !streamModeSingle) - yield meta3 !== undefined ? [ - namespace, - mode, - payload, - meta3 - ] : [ - namespace, - mode, - payload - ]; - else if (!streamModeSingle) - yield [mode, payload]; - else if (streamSubgraphs) - yield [namespace, payload]; - else - yield payload; - } + yield* this.streamWithRetry({ + endpoint: threadId == null ? `/runs/stream` : `/threads/${threadId}/runs/stream`, + method: "POST", + json: json3, + signal: payload?.signal, + onInitialResponse: (response) => { + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) + payload?.onRunCreated?.(runMetadata); } - } catch (e) { - await runManager?.handleChainError(loopError); - throw e; - } finally { - await runLoopPromise; - } - await runManager?.handleChainEnd(loop?.output ?? {}, runId, undefined, undefined, undefined); + }); } - async invoke(input, options) { - const streamMode = options?.streamMode ?? "values"; - const config2 = { - ...options, - outputKeys: options?.outputKeys ?? this.outputChannels, - streamMode, - encoding: undefined + async create(threadId, assistantId, payload) { + const json3 = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + feedback_keys: payload?.feedbackKeys, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + checkpoint: payload?.checkpoint, + checkpoint_id: payload?.checkpointId, + multitask_strategy: payload?.multitaskStrategy, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + on_completion: payload?.onCompletion, + langsmith_tracer: payload?._langsmithTracer ? { + project_name: payload?._langsmithTracer?.projectName, + example_id: payload?._langsmithTracer?.exampleId + } : undefined }; - const chunks = []; - const stream2 = await this.stream(input, config2); - const interruptChunks = []; - let latest; - for await (const chunk of stream2) - if (streamMode === "values") - if (isInterrupted2(chunk)) - interruptChunks.push(chunk[INTERRUPT3]); - else - latest = chunk; - else - chunks.push(chunk); - if (streamMode === "values") { - if (interruptChunks.length > 0) { - const interrupts = interruptChunks.flat(1); - if (latest == null) - return { [INTERRUPT3]: interrupts }; - if (typeof latest === "object") - return { - ...latest, - [INTERRUPT3]: interrupts - }; - } - return latest; - } - return chunks; + const endpoint = threadId === null ? "/runs" : `/threads/${threadId}/runs`; + const [run2, response] = await this.fetch(endpoint, { + method: "POST", + json: json3, + signal: payload?.signal, + withResponse: true + }); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) + payload?.onRunCreated?.(runMetadata); + return run2; } - async _runLoop(params) { - const { loop, runner, debug, config: config2 } = params; - let tickError; - try { - while (await loop.tick({ inputKeys: this.inputChannels })) { - for (const { task: task2 } of await loop._matchCachedWrites()) - loop._outputWrites(task2.id, task2.writes, true); - if (debug) - printStepCheckpoint2(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); - if (debug) - printStepTasks2(loop.step, Object.values(loop.tasks)); - await runner.tick({ - timeout: this.stepTimeout, - retryPolicy: this.retryPolicy, - onStepWrite: (step, writes) => { - if (debug) - printStepWrites2(step, writes, this.streamChannelsList); - }, - maxConcurrency: config2.maxConcurrency, - signal: config2.signal - }); - } - if (loop.status === "out_of_steps") - throw new GraphRecursionError2([ - `Recursion limit of ${config2.recursionLimit} reached`, - "without hitting a stop condition. You can increase the", - `limit by setting the "recursionLimit" config key.` - ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); - } catch (e) { - tickError = e; - if (!await loop.finishAndHandleError(tickError)) - throw e; - } finally { - if (tickError === undefined) - await loop.finishAndHandleError(); - } + async createBatch(payloads, options) { + const filteredPayloads = payloads.map((payload) => ({ + ...payload, + assistant_id: payload.assistantId + })).map((payload) => { + return Object.fromEntries(Object.entries(payload).filter(([_, v]) => v !== undefined)); + }); + return this.fetch("/runs/batch", { + method: "POST", + json: filteredPayloads, + signal: options?.signal + }); } - async clearCache() { - await this.cache?.clear([]); + async wait(threadId, assistantId, payload) { + const json3 = { + input: payload?.input, + command: payload?.command, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + checkpoint: payload?.checkpoint, + checkpoint_id: payload?.checkpointId, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + on_completion: payload?.onCompletion, + on_disconnect: payload?.onDisconnect, + after_seconds: payload?.afterSeconds, + if_not_exists: payload?.ifNotExists, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + langsmith_tracer: payload?._langsmithTracer ? { + project_name: payload?._langsmithTracer?.projectName, + example_id: payload?._langsmithTracer?.exampleId + } : undefined + }; + const endpoint = threadId == null ? `/runs/wait` : `/threads/${threadId}/runs/wait`; + const [run2, response] = await this.fetch(endpoint, { + method: "POST", + json: json3, + timeoutMs: null, + signal: payload?.signal, + withResponse: true + }); + const runMetadata = getRunMetadataFromResponse(response); + if (runMetadata) + payload?.onRunCreated?.(runMetadata); + if ((payload?.raiseError !== undefined ? payload.raiseError : true) && "__error__" in run2 && typeof run2.__error__ === "object" && run2.__error__ && "error" in run2.__error__ && "message" in run2.__error__) + throw new Error(`${run2.__error__?.error}: ${run2.__error__?.message}`); + return run2; } - }; - OMITTED_KEYS2 = new Set([ - "key", - "token", - "secret", - "password", - "auth" - ]); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js -var EphemeralValue3; -var init_ephemeral_value2 = __esm(() => { - init_errors10(); - init_base17(); - EphemeralValue3 = class EphemeralValue4 extends BaseChannel2 { - lc_graph_name = "EphemeralValue"; - guard; - value = []; - constructor(guard = true) { - super(); - this.guard = guard; + async list(threadId, options) { + return this.fetch(`/threads/${threadId}/runs`, { + params: { + limit: options?.limit ?? 10, + offset: options?.offset ?? 0, + status: options?.status ?? undefined, + select: options?.select ?? undefined + }, + signal: options?.signal + }); } - fromCheckpoint(checkpoint) { - const empty = new EphemeralValue4(this.guard); - if (typeof checkpoint !== "undefined") - empty.value = [checkpoint]; - return empty; + async get(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}`, { signal: options?.signal }); } - update(values2) { - if (values2.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - if (values2.length !== 1 && this.guard) - throw new InvalidUpdateError2("EphemeralValue can only receive one value per step."); - this.value = [values2[values2.length - 1]]; - return true; + async cancel(threadId, runId, wait = false, action = "interrupt", options = {}) { + return this.fetch(`/threads/${threadId}/runs/${runId}/cancel`, { + method: "POST", + params: { + wait: wait ? "1" : "0", + action + }, + signal: options?.signal + }); } - get() { - if (this.value.length === 0) - throw new EmptyChannelError2; - return this.value[0]; + async cancelMany(options) { + return this.fetch(`/runs/cancel`, { + method: "POST", + json: { + thread_id: options.threadId, + run_ids: options.runIds, + status: options.status + }, + params: { action: options.action }, + signal: options.signal + }); } - checkpoint() { - if (this.value.length === 0) - throw new EmptyChannelError2; - return this.value[0]; + async join(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}/join`, { + timeoutMs: null, + params: { cancel_on_disconnect: options?.cancelOnDisconnect ? "1" : "0" }, + signal: options?.signal + }); } - isAvailable() { - return this.value.length !== 0; + async* joinStream(threadId, runId, options) { + const opts = typeof options === "object" && options != null && options instanceof AbortSignal ? { signal: options } : options; + yield* this.streamWithRetry({ + endpoint: threadId != null ? `/threads/${threadId}/runs/${runId}/stream` : `/runs/${runId}/stream`, + method: "GET", + signal: opts?.signal, + headers: opts?.lastEventId ? { "Last-Event-ID": opts.lastEventId } : undefined, + params: { + cancel_on_disconnect: opts?.cancelOnDisconnect ? "1" : "0", + stream_mode: opts?.streamMode + } + }); + } + async delete(threadId, runId, options) { + return this.fetch(`/threads/${threadId}/runs/${runId}`, { + method: "DELETE", + signal: options?.signal + }); } }; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js -function $constructor2(name, initializer3, params) { - function init(inst, def) { - var _a4; - Object.defineProperty(inst, "_zod", { - value: inst._zod ?? {}, - enumerable: false - }); - (_a4 = inst._zod).traits ?? (_a4.traits = new Set); - inst._zod.traits.add(name); - initializer3(inst, def); - for (const k in _.prototype) { - if (!(k in inst)) - Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/crons/index.js +var CronsClient; +var init_crons = __esm(() => { + init_base17(); + CronsClient = class extends BaseClient { + async createForThread(threadId, assistantId, payload) { + const json3 = { + schedule: payload?.schedule, + input: payload?.input, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + multitask_strategy: payload?.multitaskStrategy, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + enabled: payload?.enabled, + timezone: payload?.timezone, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + end_time: payload?.endTime, + on_run_completed: payload?.onRunCompleted + }; + return this.fetch(`/threads/${threadId}/runs/crons`, { + method: "POST", + json: json3, + signal: payload?.signal + }); } - inst._zod.constr = _; - inst._zod.def = def; - } - const Parent = params?.Parent ?? Object; - - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a4; - const inst = params?.Parent ? new Definition : this; - init(inst, def); - (_a4 = inst._zod).deferred ?? (_a4.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); + async create(assistantId, payload) { + const json3 = { + schedule: payload?.schedule, + input: payload?.input, + config: payload?.config, + context: payload?.context, + metadata: payload?.metadata, + assistant_id: assistantId, + interrupt_before: payload?.interruptBefore, + interrupt_after: payload?.interruptAfter, + webhook: payload?.webhook, + on_run_completed: payload?.onRunCompleted, + multitask_strategy: payload?.multitaskStrategy, + checkpoint_during: payload?.checkpointDuring, + durability: payload?.durability, + enabled: payload?.enabled, + timezone: payload?.timezone, + stream_mode: payload?.streamMode, + stream_subgraphs: payload?.streamSubgraphs, + stream_resumable: payload?.streamResumable, + end_time: payload?.endTime + }; + return this.fetch(`/runs/crons`, { + method: "POST", + json: json3, + signal: payload?.signal + }); } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); + async update(cronId, payload) { + const json3 = {}; + if (payload?.schedule !== undefined) + json3.schedule = payload.schedule; + if (payload?.timezone !== undefined) + json3.timezone = payload.timezone; + if (payload?.endTime !== undefined) + json3.end_time = payload.endTime; + if (payload?.input !== undefined) + json3.input = payload.input; + if (payload?.metadata !== undefined) + json3.metadata = payload.metadata; + if (payload?.config !== undefined) + json3.config = payload.config; + if (payload?.context !== undefined) + json3.context = payload.context; + if (payload?.webhook !== undefined) + json3.webhook = payload.webhook; + if (payload?.interruptBefore !== undefined) + json3.interrupt_before = payload.interruptBefore; + if (payload?.interruptAfter !== undefined) + json3.interrupt_after = payload.interruptAfter; + if (payload?.onRunCompleted !== undefined) + json3.on_run_completed = payload.onRunCompleted; + if (payload?.enabled !== undefined) + json3.enabled = payload.enabled; + if (payload?.streamMode !== undefined) + json3.stream_mode = payload.streamMode; + if (payload?.streamSubgraphs !== undefined) + json3.stream_subgraphs = payload.streamSubgraphs; + if (payload?.streamResumable !== undefined) + json3.stream_resumable = payload.streamResumable; + if (payload?.durability !== undefined) + json3.durability = payload.durability; + return this.fetch(`/runs/crons/${cronId}`, { + method: "PATCH", + json: json3, + signal: payload?.signal + }); } - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -function config2(newConfig) { - if (newConfig) - Object.assign(globalConfig2, newConfig); - return globalConfig2; -} -var NEVER3, $brand2, $ZodAsyncError2, globalConfig2; -var init_core4 = __esm(() => { - NEVER3 = Object.freeze({ - status: "aborted" - }); - $brand2 = Symbol("zod_brand"); - $ZodAsyncError2 = class $ZodAsyncError2 extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + async delete(cronId, options) { + await this.fetch(`/runs/crons/${cronId}`, { + method: "DELETE", + signal: options?.signal + }); + } + async search(query3) { + return this.fetch("/runs/crons/search", { + method: "POST", + json: { + assistant_id: query3?.assistantId ?? undefined, + thread_id: query3?.threadId ?? undefined, + enabled: query3?.enabled ?? undefined, + limit: query3?.limit ?? 10, + offset: query3?.offset ?? 0, + sort_by: query3?.sortBy ?? undefined, + sort_order: query3?.sortOrder ?? undefined, + select: query3?.select ?? undefined, + metadata: query3?.metadata ?? undefined + }, + signal: query3?.signal + }); + } + async count(query3) { + return this.fetch(`/runs/crons/count`, { + method: "POST", + json: { + assistant_id: query3?.assistantId ?? undefined, + thread_id: query3?.threadId ?? undefined, + metadata: query3?.metadata ?? undefined + }, + signal: query3?.signal + }); } }; - globalConfig2 = {}; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js -var exports_util2 = {}; -__export(exports_util2, { - unwrapMessage: () => unwrapMessage2, - stringifyPrimitive: () => stringifyPrimitive2, - required: () => required2, - randomString: () => randomString2, - propertyKeyTypes: () => propertyKeyTypes2, - promiseAllObject: () => promiseAllObject2, - primitiveTypes: () => primitiveTypes2, - prefixIssues: () => prefixIssues2, - pick: () => pick2, - partial: () => partial2, - optionalKeys: () => optionalKeys2, - omit: () => omit2, - numKeys: () => numKeys2, - nullish: () => nullish3, - normalizeParams: () => normalizeParams2, - merge: () => merge2, - jsonStringifyReplacer: () => jsonStringifyReplacer2, - joinValues: () => joinValues2, - issue: () => issue2, - isPlainObject: () => isPlainObject2, - isObject: () => isObject3, - getSizableOrigin: () => getSizableOrigin2, - getParsedType: () => getParsedType3, - getLengthableOrigin: () => getLengthableOrigin2, - getEnumValues: () => getEnumValues2, - getElementAtPath: () => getElementAtPath2, - floatSafeRemainder: () => floatSafeRemainder3, - finalizeIssue: () => finalizeIssue2, - extend: () => extend2, - escapeRegex: () => escapeRegex3, - esc: () => esc2, - defineLazy: () => defineLazy2, - createTransparentProxy: () => createTransparentProxy2, - clone: () => clone2, - cleanRegex: () => cleanRegex2, - cleanEnum: () => cleanEnum2, - captureStackTrace: () => captureStackTrace2, - cached: () => cached2, - assignProp: () => assignProp2, - assertNotEqual: () => assertNotEqual2, - assertNever: () => assertNever2, - assertIs: () => assertIs2, - assertEqual: () => assertEqual2, - assert: () => assert5, - allowsEval: () => allowsEval2, - aborted: () => aborted2, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES2, - Class: () => Class2, - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES2 +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/store/index.js +var StoreClient; +var init_store = __esm(() => { + init_base17(); + StoreClient = class extends BaseClient { + async putItem(namespace, key, value, options) { + namespace.forEach((label) => { + if (label.includes(".")) + throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + const payload = { + namespace, + key, + value, + index: options?.index, + ttl: options?.ttl + }; + return this.fetch("/store/items", { + method: "PUT", + json: payload, + signal: options?.signal + }); + } + async getItem(namespace, key, options) { + namespace.forEach((label) => { + if (label.includes(".")) + throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + const params = { + namespace: namespace.join("."), + key + }; + if (options?.refreshTtl !== undefined) + params.refresh_ttl = options.refreshTtl; + const response = await this.fetch("/store/items", { + params, + signal: options?.signal + }); + return response ? { + ...response, + createdAt: response.created_at, + updatedAt: response.updated_at + } : null; + } + async deleteItem(namespace, key, options) { + namespace.forEach((label) => { + if (label.includes(".")) + throw new Error(`Invalid namespace label '${label}'. Namespace labels cannot contain periods ('.')`); + }); + return this.fetch("/store/items", { + method: "DELETE", + json: { + namespace, + key + }, + signal: options?.signal + }); + } + async searchItems(namespacePrefix, options) { + const payload = { + namespace_prefix: namespacePrefix, + filter: options?.filter, + limit: options?.limit ?? 10, + offset: options?.offset ?? 0, + query: options?.query, + refresh_ttl: options?.refreshTtl + }; + return { items: (await this.fetch("/store/items/search", { + method: "POST", + json: payload, + signal: options?.signal + })).items.map((item) => ({ + ...item, + createdAt: item.created_at, + updatedAt: item.updated_at + })) }; + } + async listNamespaces(options) { + const payload = { + prefix: options?.prefix, + suffix: options?.suffix, + max_depth: options?.maxDepth, + limit: options?.limit ?? 100, + offset: options?.offset ?? 0 + }; + return this.fetch("/store/namespaces", { + method: "POST", + json: payload, + signal: options?.signal + }); + } + }; }); -function assertEqual2(val) { - return val; -} -function assertNotEqual2(val) { - return val; -} -function assertIs2(_arg) {} -function assertNever2(_x) { - throw new Error; -} -function assert5(_) {} -function getEnumValues2(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values2 = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); - return values2; -} -function joinValues2(array2, separator = "|") { - return array2.map((val) => stringifyPrimitive2(val)).join(separator); -} -function jsonStringifyReplacer2(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached2(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/ui-internal/index.js +var UiClient; +var init_ui_internal = __esm(() => { + init_base17(); + UiClient = class UiClient2 extends BaseClient { + static promiseCache = {}; + static getOrCached(key, fn) { + if (UiClient2.promiseCache[key] != null) + return UiClient2.promiseCache[key]; + const promise3 = fn(); + UiClient2.promiseCache[key] = promise3; + return promise3; + } + async getComponent(assistantId, agentName) { + return UiClient2.getOrCached(`${this.apiUrl}-${assistantId}-${agentName}`, async () => { + let [url3, init] = this.prepareFetchOptions(`/ui/${assistantId}`, { + headers: { + Accept: "text/html", + "Content-Type": "application/json" + }, + method: "POST", + json: { name: agentName } + }); + if (this.onRequest != null) + init = await this.onRequest(url3, init); + return (await this.asyncCaller.fetch(url3.toString(), init)).text(); + }); } }; -} -function nullish3(input) { - return input === null || input === undefined; -} -function cleanRegex2(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder3(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function defineLazy2(object2, key, getter) { - const set2 = false; - Object.defineProperty(object2, key, { - get() { - if (!set2) { - const value = getter(); - object2[key] = value; - return value; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/stream/transport/index.js +var init_transport = __esm(() => { + init_http(); + init_websocket(); + init_agent_server(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client/index.js +var Client2 = class { + assistants; + threads; + runs; + crons; + store; + "~ui"; + "~configHash"; + constructor(config3) { + this["~configHash"] = JSON.stringify({ + apiUrl: config3?.apiUrl, + apiKey: config3?.apiKey, + timeoutMs: config3?.timeoutMs, + defaultHeaders: config3?.defaultHeaders, + streamProtocol: config3?.streamProtocol, + maxConcurrency: config3?.callerOptions?.maxConcurrency, + maxRetries: config3?.callerOptions?.maxRetries, + callbacks: { + onFailedResponseHook: config3?.callerOptions?.onFailedResponseHook != null, + onRequest: config3?.onRequest != null, + fetch: config3?.callerOptions?.fetch != null } - throw new Error("cached value already set"); - }, - set(v) { - Object.defineProperty(object2, key, { - value: v - }); - }, - configurable: true - }); -} -function assignProp2(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true - }); -} -function getElementAtPath2(obj, path4) { - if (!path4) - return obj; - return path4.reduce((acc, key) => acc?.[key], obj); + }); + this.assistants = new AssistantsClient(config3); + this.threads = new ThreadsClient(config3); + this.runs = new RunsClient(config3); + this.crons = new CronsClient(config3); + this.store = new StoreClient(config3); + this["~ui"] = new UiClient(config3); + } +}; +var init_client2 = __esm(() => { + init_base17(); + init_assistants(); + init_subscription(); + init_tools4(); + init_messages8(); + init_media(); + init_subgraphs3(); + init_subagents(); + init_error4(); + init_stream10(); + init_http(); + init_websocket(); + init_threads(); + init_runs(); + init_crons(); + init_store(); + init_ui_internal(); + init_agent_server(); + init_transport(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/client.js +var init_client3 = __esm(() => { + init_base17(); + init_assistants(); + init_subscription(); + init_messages8(); + init_media(); + init_error4(); + init_stream10(); + init_http(); + init_websocket(); + init_threads(); + init_runs(); + init_crons(); + init_store(); + init_agent_server(); + init_client2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/store.js +var StreamStore = class { + #snapshot; + #listeners = /* @__PURE__ */ new Set; + constructor(initial) { + this.#snapshot = initial; + } + subscribe = (listener) => { + this.#listeners.add(listener); + return () => { + this.#listeners.delete(listener); + }; + }; + getSnapshot = () => this.#snapshot; + setValue = (next) => { + if (Object.is(next, this.#snapshot)) + return; + this.#snapshot = next; + for (const listener of this.#listeners) + listener(); + }; + setState = (updater) => { + this.setValue(updater(this.#snapshot)); + }; +}; +var init_store2 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/channel-registry.js +async function tryDispose(runtime) { + try { + await runtime.dispose(); + } catch {} } -function promiseAllObject2(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0;i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; +var ChannelRegistry = class { + #thread; + #rootBus; + #entries = /* @__PURE__ */ new Map; + constructor(rootBus) { + this.#rootBus = rootBus; + } + bind(thread) { + if (this.#thread === thread) + return; + const previous = this.#thread; + this.#thread = thread; + for (const entry of this.#entries.values()) { + if (entry.runtime != null && previous != null) + tryDispose(entry.runtime); + entry.runtime = undefined; + entry.store.setValue(entry.initial); + if (thread != null) + entry.runtime = entry.open({ + thread, + store: entry.store, + rootBus: this.#rootBus + }); } - return resolvedObj; - }); -} -function randomString2(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0;i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; } - return str; -} -function esc2(str) { - return JSON.stringify(str); -} -function isObject3(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -function isPlainObject2(o) { - if (isObject3(o) === false) - return false; - const ctor = o.constructor; - if (ctor === undefined) - return true; - const prot = ctor.prototype; - if (isObject3(prot) === false) - return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; + get thread() { + return this.#thread; } - return true; -} -function numKeys2(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; + acquire(spec) { + let entry = this.#entries.get(spec.key); + if (entry == null) { + const store = new StreamStore(spec.initial); + const newEntry = { + key: spec.key, + store, + initial: spec.initial, + open: spec.open, + refCount: 0, + runtime: undefined + }; + if (this.#thread != null) + newEntry.runtime = spec.open({ + thread: this.#thread, + store, + rootBus: this.#rootBus + }); + this.#entries.set(spec.key, newEntry); + entry = newEntry; } + entry.refCount += 1; + let released = false; + return { + store: entry.store, + release: () => { + if (released) + return; + released = true; + const current = this.#entries.get(spec.key); + if (current == null) + return; + current.refCount -= 1; + if (current.refCount <= 0) { + this.#entries.delete(spec.key); + if (current.runtime != null) + tryDispose(current.runtime); + } + } + }; } - return keyCount; + async dispose() { + this.#thread = undefined; + const entries = [...this.#entries.values()]; + this.#entries.clear(); + await Promise.all(entries.map(async (entry) => { + if (entry.runtime != null) + await tryDispose(entry.runtime); + })); + } + get size() { + return this.#entries.size; + } +}; +var init_channel_registry = __esm(() => { + init_store2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/namespace.js +function namespaceKey2(namespace) { + return namespace.join("\x00"); } -function escapeRegex3(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +function isRootNamespace(namespace) { + return namespace.length === 0; } -function clone2(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; +function isToolNamespaceSegment(segment) { + return segment.startsWith("tools:"); } -function normalizeParams2(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; +function isTaskNamespaceSegment(segment) { + return segment.startsWith("task:"); } -function createTransparentProxy2(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - } - }); +function isInternalWorkNamespace(namespace) { + return namespace.some((segment) => isTaskNamespaceSegment(segment) || isToolNamespaceSegment(segment)); } -function stringifyPrimitive2(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; +function isLegacySubagentNamespace(namespace) { + return namespace.some(isTaskNamespaceSegment); } -function optionalKeys2(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); +function isConcreteToolNamespace(namespace) { + const last = namespace.at(-1); + return last != null && isToolNamespaceSegment(last); } -function pick2(schema, mask) { - const newShape = {}; - const currDef = schema._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) +var init_namespace2 = __esm(() => { + init_constants6(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/discovery/subagents.js +function getFirstHumanMessageText(messages) { + for (const message of messages) { + if (message == null || typeof message !== "object") continue; - newShape[key] = currDef.shape[key]; - } - return clone2(schema, { - ...schema._zod.def, - shape: newShape, - checks: [] - }); -} -function omit2(schema, mask) { - const newShape = { ...schema._zod.def.shape }; - const currDef = schema._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) + const record3 = message; + if ((record3.type ?? record3.role ?? record3.kwargs?.type ?? record3.lc_kwargs?.type) !== "human") continue; - delete newShape[key]; + const content = record3.content ?? record3.kwargs?.content ?? record3.lc_kwargs?.content; + return typeof content === "string" && content.length > 0 ? content : null; } - return clone2(schema, { - ...schema._zod.def, - shape: newShape, - checks: [] - }); + return null; } -function extend2(schema, shape) { - if (!isPlainObject2(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const def = { - ...schema._zod.def, - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp2(this, "shape", _shape); - return _shape; - }, - checks: [] - }; - return clone2(schema, def); +function shouldPromoteToObservedNamespace(entry) { + return entry.name === "fanout-worker" || /^Worker worker-\d+/i.test(entry.taskInput ?? ""); } -function merge2(a, b) { - return clone2(a, { - ...a._zod.def, - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp2(this, "shape", _shape); - return _shape; - }, - catchall: b._zod.def.catchall, - checks: [] - }); +function taskWorkNamespace(toolCallId, eventNamespace) { + const last = eventNamespace.at(-1); + if (last != null && isToolNamespaceSegment(last)) + return [...eventNamespace]; + return [`tools:${toolCallId}`]; } -function partial2(Class2, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - return clone2(schema, { - ...schema._zod.def, - shape, - checks: [] - }); +function toSnapshot(entry) { + return { + id: entry.id, + name: entry.name, + namespace: entry.namespace, + parentId: entry.parentId, + depth: entry.depth, + status: entry.status, + taskInput: entry.taskInput, + output: entry.output, + error: entry.error, + startedAt: entry.startedAt, + completedAt: entry.completedAt + }; } -function required2(Class2, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); +function parseTaskInput(raw2) { + if (raw2 == null) + return {}; + if (typeof raw2 === "string") + try { + const parsed = JSON.parse(raw2); + return { + description: typeof parsed.description === "string" ? parsed.description : undefined, + subagent_type: typeof parsed.subagent_type === "string" ? parsed.subagent_type : undefined + }; + } catch { + return {}; } + if (typeof raw2 === "object" && !Array.isArray(raw2)) { + const obj = raw2; + return { + description: typeof obj.description === "string" ? obj.description : undefined, + subagent_type: typeof obj.subagent_type === "string" ? obj.subagent_type : undefined + }; } - return clone2(schema, { - ...schema._zod.def, - shape, - checks: [] - }); + return {}; } -function aborted2(x, startIndex = 0) { - for (let i = startIndex;i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) - return true; +function getTaskToolCalls(message) { + if (message == null || typeof message !== "object" || Array.isArray(message)) + return []; + const record3 = message; + const toolCalls = record3.tool_calls ?? record3.kwargs?.tool_calls ?? record3.lc_kwargs?.tool_calls; + if (!Array.isArray(toolCalls)) + return []; + const result = []; + for (const toolCall of toolCalls) { + if (toolCall == null || typeof toolCall !== "object" || Array.isArray(toolCall)) + continue; + const record4 = toolCall; + if (typeof record4.id !== "string" || record4.name !== "task") + continue; + result.push({ + id: record4.id, + input: parseTaskInput(record4.args) + }); } - return false; + return result; } -function prefixIssues2(path4, issues) { - return issues.map((iss) => { - var _a4; - (_a4 = iss).path ?? (_a4.path = []); - iss.path.unshift(path4); - return iss; - }); +function getToolMessageCallId(message) { + if (message == null || typeof message !== "object" || Array.isArray(message)) + return; + const record3 = message; + const id = record3.tool_call_id ?? record3.kwargs?.tool_call_id ?? record3.lc_kwargs?.tool_call_id; + return typeof id === "string" && id.length > 0 ? id : undefined; } -function unwrapMessage2(message) { - return typeof message === "string" ? message : message?.message; +function lineageFromNamespace(namespace) { + if (isRootNamespace(namespace)) + return { + parentId: null, + depth: 1 + }; + const last = namespace[namespace.length - 1]; + if (last == null) + return { + parentId: null, + depth: 1 + }; + const trimmed = last.split(":").filter((part) => part.length > 0).slice(1); + const depth = Math.max(1, trimmed.length); + return { + parentId: (trimmed.length >= 2 ? trimmed[trimmed.length - 2] : null) ?? null, + depth + }; } -function finalizeIssue2(iss, ctx, config3) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message = unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config3.customError?.(iss)) ?? unwrapMessage2(config3.localeError?.(iss)) ?? "Invalid input"; - full.message = message; +var EMPTY_SUBAGENT_MAP, SubagentDiscovery = class { + store = new StreamStore(/* @__PURE__ */ new Map); + #map = /* @__PURE__ */ new Map; + #taskIdByObservedNamespace = /* @__PURE__ */ new Map; + #observedOwnNamespaces = /* @__PURE__ */ new Set; + #toolCallIdByTaskInput = /* @__PURE__ */ new Map; + push(event) { + if (event.method === "tools") + this.#onToolEvent(event); + else if (event.method === "values") + this.#onValuesEvent(event); } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; + get snapshot() { + return this.store.getSnapshot(); } - return full; -} -function getSizableOrigin2(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin2(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function issue2(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst - }; + reset() { + this.#map.clear(); + this.#taskIdByObservedNamespace.clear(); + this.#observedOwnNamespaces.clear(); + this.#toolCallIdByTaskInput.clear(); + this.store.setValue(EMPTY_SUBAGENT_MAP); } - return { ...iss }; -} -function cleanEnum2(obj) { - return Object.entries(obj).filter(([k, _]) => { - return Number.isNaN(Number.parseInt(k, 10)); - }).map((el) => el[1]); -} - -class Class2 { - constructor(..._args) {} -} -var captureStackTrace2, allowsEval2, getParsedType3 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); + discoverFromMessage(message, namespace) { + let changed = false; + for (const toolCall of getTaskToolCalls(message)) + changed = this.#upsertTaskToolCall(toolCall.id, toolCall.input, namespace) || changed; + if (changed) + this.#commit(); } -}, propertyKeyTypes2, primitiveTypes2, NUMBER_FORMAT_RANGES2, BIGINT_FORMAT_RANGES2; -var init_util3 = __esm(() => { - captureStackTrace2 = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {}; - allowsEval2 = cached2(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; + #commit() { + this.store.setValue(new Map([...this.#map.values()].map((entry) => [entry.id, toSnapshot(entry)]))); + } + #onToolEvent(event) { + const data = event.params.data; + const toolCallId = data.tool_call_id; + const toolName = data.tool_name; + if (data.event === "tool-started" && toolName === "task") { + const input = parseTaskInput(data.input); + if (toolCallId == null) + return; + this.#upsertTaskToolCall(toolCallId, input, event.params.namespace); + this.#commit(); + return; } - try { - const F = Function; - new F(""); - return true; - } catch (_) { - return false; + if (toolCallId == null) + return; + const entry = this.#map.get(toolCallId); + if (entry == null) + return; + if (data.event === "tool-finished") { + entry.status = "complete"; + entry.output = data.output; + entry.completedAt = /* @__PURE__ */ new Date; + this.#commit(); + return; } - }); - propertyKeyTypes2 = new Set(["string", "number", "symbol"]); - primitiveTypes2 = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); - NUMBER_FORMAT_RANGES2 = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] - }; - BIGINT_FORMAT_RANGES2 = { - int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], - uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] - }; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js -function flattenError2(error52, mapper = (issue3) => issue3.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error52.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); + if (data.event === "tool-error") { + entry.status = "error"; + entry.error = data.message ?? "Subagent failed"; + entry.completedAt = /* @__PURE__ */ new Date; + this.#commit(); } } - return { formErrors, fieldErrors }; -} -function formatError3(error52, _mapper) { - const mapper = _mapper || function(issue3) { - return issue3.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error53) => { - for (const issue3 of error53.issues) { - if (issue3.code === "invalid_union" && issue3.errors.length) { - issue3.errors.map((issues) => processError({ issues })); - } else if (issue3.code === "invalid_key") { - processError({ issues: issue3.issues }); - } else if (issue3.code === "invalid_element") { - processError({ issues: issue3.issues }); - } else if (issue3.path.length === 0) { - fieldErrors._errors.push(mapper(issue3)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue3.path.length) { - const el = issue3.path[i]; - const terminal = i === issue3.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue3)); - } - curr = curr[el]; - i++; - } - } + #onValuesEvent(event) { + const data = event.params.data; + if (data == null || typeof data !== "object" || Array.isArray(data)) + return; + const messages = data.messages; + if (!Array.isArray(messages)) + return; + this.#bindNamespaceByTaskInput(event.params.namespace, messages); + let changed = this.#recordObservedWorkNamespace(event.params.namespace); + for (const message of messages) { + for (const toolCall of getTaskToolCalls(message)) + changed = this.#upsertTaskToolCall(toolCall.id, toolCall.input, event.params.namespace) || changed; + const toolCallId = getToolMessageCallId(message); + if (toolCallId == null) + continue; + const existing = this.#map.get(toolCallId); + if (existing == null) + continue; + existing.status = "complete"; + existing.output = message; + existing.completedAt = /* @__PURE__ */ new Date; + changed = true; } - }; - processError(error52); - return fieldErrors; -} -function treeifyError2(error52, _mapper) { - const mapper = _mapper || function(issue3) { - return issue3.message; - }; - const result = { errors: [] }; - const processError = (error53, path4 = []) => { - var _a4, _b; - for (const issue3 of error53.issues) { - if (issue3.code === "invalid_union" && issue3.errors.length) { - issue3.errors.map((issues) => processError({ issues }, issue3.path)); - } else if (issue3.code === "invalid_key") { - processError({ issues: issue3.issues }, issue3.path); - } else if (issue3.code === "invalid_element") { - processError({ issues: issue3.issues }, issue3.path); - } else { - const fullpath = [...path4, ...issue3.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue3)); - continue; + if (changed) + this.#commit(); + } + #upsertTaskToolCall(toolCallId, input, eventNamespace) { + const namespace = taskWorkNamespace(toolCallId, eventNamespace); + const existing = this.#map.get(toolCallId); + if (existing != null) { + let changed = false; + this.#recordTaskNamespaceCandidate(toolCallId, eventNamespace); + const nextName = input.subagent_type ?? existing.name; + const nextTaskInput = input.description ?? existing.taskInput; + if (existing.name !== nextName) { + existing.name = nextName; + changed = true; + } + if (existing.taskInput !== nextTaskInput) { + existing.taskInput = nextTaskInput; + changed = true; + } + const namespaceKeyed = namespaceKey2(existing.namespace); + const ownNamespaceKey = `tools:${toolCallId}`; + const nextNamespaceKey = namespaceKey2(namespace); + if (isConcreteToolNamespace(eventNamespace) || namespaceKeyed === ownNamespaceKey) { + if (namespaceKeyed === ownNamespaceKey && nextNamespaceKey !== ownNamespaceKey && this.#observedOwnNamespaces.has(toolCallId)) + return changed; + if (namespaceKeyed !== nextNamespaceKey) { + existing.namespace = namespace; + changed = true; } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a4 = curr.properties)[el] ?? (_a4[el] = { errors: [] }); - curr = curr.properties[el]; - } else { - curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue3)); - } - i++; + } + if (existing.status !== "complete" && existing.status !== "error") { + if (existing.status !== "running") { + existing.status = "running"; + changed = true; } } + return changed; } - }; - processError(error52); - return result; -} -function toDotPath2(path4) { - const segs = []; - for (const seg of path4) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); + const { parentId, depth } = lineageFromNamespace(eventNamespace); + this.#recordTaskNamespaceCandidate(toolCallId, eventNamespace); + if (input.description != null) { + const queue2 = this.#toolCallIdByTaskInput.get(input.description) ?? []; + queue2.push(toolCallId); + this.#toolCallIdByTaskInput.set(input.description, queue2); } + this.#map.set(toolCallId, { + id: toolCallId, + name: input.subagent_type ?? "unknown", + namespace, + parentId, + depth, + status: "running", + taskInput: input.description, + output: undefined, + error: undefined, + startedAt: /* @__PURE__ */ new Date, + completedAt: null + }); + return true; } - return segs.join(""); + #recordObservedWorkNamespace(namespace) { + if (!isConcreteToolNamespace(namespace)) + return false; + const last = namespace.at(-1); + if (last == null) + return false; + const namespaceKeyed = namespaceKey2(namespace); + const toolCallId = this.#taskIdByObservedNamespace.get(namespaceKeyed) ?? last.slice(6); + const existing = this.#map.get(toolCallId); + if (existing == null) + return false; + if (namespaceKeyed === `tools:${toolCallId}`) + this.#observedOwnNamespaces.add(toolCallId); + else if (this.#observedOwnNamespaces.has(toolCallId) || !this.#taskIdByObservedNamespace.has(namespaceKeyed) && !shouldPromoteToObservedNamespace(existing)) + return false; + if (namespaceKey2(existing.namespace) === namespaceKeyed) + return false; + existing.namespace = [...namespace]; + return true; + } + #recordTaskNamespaceCandidate(toolCallId, namespace) { + if (!isConcreteToolNamespace(namespace)) + return; + this.#taskIdByObservedNamespace.set(namespaceKey2(namespace), toolCallId); + } + #bindNamespaceByTaskInput(namespace, messages) { + if (!isConcreteToolNamespace(namespace)) + return; + const namespaceKeyed = namespaceKey2(namespace); + if (this.#taskIdByObservedNamespace.has(namespaceKeyed)) + return; + const text = getFirstHumanMessageText(messages); + if (text == null) + return; + const toolCallId = this.#toolCallIdByTaskInput.get(text)?.shift(); + if (toolCallId == null) + return; + this.#taskIdByObservedNamespace.set(namespaceKeyed, toolCallId); + } +}; +var init_subagents2 = __esm(() => { + init_store2(); + init_namespace2(); + EMPTY_SUBAGENT_MAP = /* @__PURE__ */ new Map; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/discovery/subgraphs.js +function parseNodeName(segment) { + const colon = segment.indexOf(":"); + return colon === -1 ? segment : segment.slice(0, colon); } -function prettifyError2(error52) { - const lines = []; - const issues = [...error52.issues].sort((a, b) => a.path.length - b.path.length); - for (const issue3 of issues) { - lines.push(`✖ ${issue3.message}`); - if (issue3.path?.length) - lines.push(` → at ${toDotPath2(issue3.path)}`); +var EMPTY_SUBGRAPH_MAP, EMPTY_SUBGRAPH_BY_NODE_MAP, SubgraphDiscovery = class { + store = new StreamStore(/* @__PURE__ */ new Map); + byNodeStore = new StreamStore(/* @__PURE__ */ new Map); + #shadow = /* @__PURE__ */ new Map; + #promoted = /* @__PURE__ */ new Set; + push(event) { + if (event.method === "values") { + this.#onValuesEvent(event); + return; + } + if (event.method !== "lifecycle") + return; + const lifecycle = event; + const namespace = lifecycle.params.namespace; + if (isRootNamespace(namespace)) + return; + const id = namespaceKey2(namespace); + const data = lifecycle.params.data; + const nodeName = parseNodeName(namespace[namespace.length - 1] ?? ""); + let touched = false; + for (let depth = 1;depth < namespace.length; depth += 1) { + const ancestorId = namespaceKey2(namespace.slice(0, depth)); + if (!this.#promoted.has(ancestorId)) { + this.#promoted.add(ancestorId); + if (this.#shadow.has(ancestorId)) + touched = true; + } + } + if (data.event === "started") { + if (!this.#shadow.has(id)) { + this.#shadow.set(id, { + id, + namespace: [...namespace], + nodeName, + status: "running", + startedAt: /* @__PURE__ */ new Date, + completedAt: null + }); + if (this.#promoted.has(id)) + touched = true; + } + } else if (data.event === "completed" || data.event === "interrupted" || data.event === "failed") { + const entry = this.#ensureShadow(id, namespace, nodeName); + if (data.event === "failed") + entry.status = "error"; + else + entry.status = "complete"; + entry.completedAt = /* @__PURE__ */ new Date; + if (this.#promoted.has(id)) + touched = true; + } + if (touched) + this.#commit(); + } + #onValuesEvent(event) { + const namespace = event.params.namespace; + if (isRootNamespace(namespace)) + return; + if (isInternalWorkNamespace(namespace)) + return; + const data = event.params.data; + if (data == null || typeof data !== "object" || Array.isArray(data)) + return; + const id = namespaceKey2(namespace); + const nodeName = parseNodeName(namespace[namespace.length - 1] ?? ""); + const entry = this.#ensureShadow(id, namespace, nodeName); + entry.status = "running"; + if (!this.#promoted.has(id)) + this.#promoted.add(id); + this.#commit(); + } + get snapshot() { + return this.store.getSnapshot(); + } + get byNodeSnapshot() { + return this.byNodeStore.getSnapshot(); + } + reset() { + this.#shadow.clear(); + this.#promoted.clear(); + this.store.setValue(EMPTY_SUBGRAPH_MAP); + this.byNodeStore.setValue(EMPTY_SUBGRAPH_BY_NODE_MAP); + } + #ensureShadow(id, namespace, nodeName) { + let entry = this.#shadow.get(id); + if (entry == null) { + entry = { + id, + namespace: [...namespace], + nodeName, + status: "running", + startedAt: /* @__PURE__ */ new Date, + completedAt: null + }; + this.#shadow.set(id, entry); + } + return entry; + } + #commit() { + const snapshots = []; + for (const id of this.#promoted) { + const entry = this.#shadow.get(id); + if (entry == null) + continue; + snapshots.push({ ...entry }); + } + this.store.setValue(new Map(snapshots.map((s) => [s.id, s]))); + const byNode = /* @__PURE__ */ new Map; + for (const snap of snapshots) { + const bucket = byNode.get(snap.nodeName); + if (bucket == null) + byNode.set(snap.nodeName, [snap]); + else + bucket.push(snap); + } + this.byNodeStore.setValue(byNode); + } +}; +var init_subgraphs4 = __esm(() => { + init_store2(); + init_namespace2(); + EMPTY_SUBGRAPH_MAP = /* @__PURE__ */ new Map; + EMPTY_SUBGRAPH_BY_NODE_MAP = /* @__PURE__ */ new Map; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/assembled-to-message.js +function assembledToBaseMessage(input) { + const { id, role, blocks: blocks2, toolCallId, usage } = input; + const textContent = extractContentString(blocks2); + const toolCalls = extractToolCalls(blocks2); + const toolCallChunks = extractToolCallChunks(blocks2); + const additionalKwargs = usage != null ? { usage } : undefined; + switch (role) { + case "human": + return new HumanMessage({ + ...id != null ? { id } : {}, + content: textContent, + ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {} + }); + case "system": + return new SystemMessage({ + ...id != null ? { id } : {}, + content: textContent, + ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {} + }); + case "tool": + return new ToolMessage({ + ...id != null ? { id } : {}, + content: textContent, + tool_call_id: toolCallId ?? "" + }); + default: { + const payload = { + ...id != null ? { id } : {}, + content: cloneContentBlocks(blocks2), + ...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}, + ...toolCallChunks.length > 0 ? { tool_call_chunks: toolCallChunks } : {}, + ...additionalKwargs != null ? { additional_kwargs: additionalKwargs } : {}, + response_metadata: { output_version: "v1" } + }; + return toolCallChunks.length > 0 ? new AIMessageChunk(payload) : new AIMessage(payload); + } } - return lines.join(` -`); } -var initializer3 = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - Object.defineProperty(inst, "message", { - get() { - return JSON.stringify(def, jsonStringifyReplacer2, 2); - }, - enumerable: true - }); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false +function assembledMessageToBaseMessage(assembled, role, extras = {}) { + return assembledToBaseMessage({ + id: assembled.id, + role, + blocks: assembled.blocks, + toolCallId: extras.toolCallId, + usage: assembled.usage }); -}, $ZodError2, $ZodRealError2; -var init_errors11 = __esm(() => { - init_core4(); - init_util3(); - $ZodError2 = $constructor2("$ZodError", initializer3); - $ZodRealError2 = $constructor2("$ZodError", initializer3, { Parent: Error }); +} +function extractContentString(blocks2) { + let out = ""; + for (const block of blocks2) + if (block.type === "text" && typeof block.text === "string") + out += block.text; + return out; +} +function cloneContentBlocks(blocks2) { + return blocks2.map((block) => structuredClone(block)); +} +function extractToolCalls(blocks2) { + const out = []; + for (const block of blocks2) { + if (block.type !== "tool_call" && block.type !== "tool_use") + continue; + const tc = block; + out.push({ + id: tc.id ?? "", + name: tc.name ?? "", + args: normalizeToolCallArgs2(tc.args ?? tc.input), + type: "tool_call" + }); + } + return out; +} +function extractToolCallChunks(blocks2) { + const out = []; + for (const block of blocks2) { + if (block.type !== "tool_call_chunk") + continue; + const tc = block; + out.push({ + id: tc.id, + name: tc.name, + args: tc.args, + index: tc.index, + type: "tool_call_chunk" + }); + } + return out; +} +function normalizeToolCallArgs2(value) { + if (value != null && typeof value === "object" && !Array.isArray(value)) + return value; + if (typeof value === "string" && value.length > 0) + try { + const parsed = JSON.parse(value); + if (parsed != null && typeof parsed === "object" && !Array.isArray(parsed)) + return parsed; + } catch {} + return {}; +} +var init_assembled_to_message = __esm(() => { + init_messages(); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js -var _parse2 = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError2; +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/message-metadata-tracker.js +var EMPTY_METADATA_MAP, MessageMetadataTracker = class { + store = new StreamStore(EMPTY_METADATA_MAP); + #pendingCheckpointByNamespace = /* @__PURE__ */ new Map; + reset() { + this.#pendingCheckpointByNamespace.clear(); + this.store.setState(() => EMPTY_METADATA_MAP); } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); - captureStackTrace2(e, _params?.callee); - throw e; + bufferCheckpoint(namespace, data) { + if (data == null || typeof data.id !== "string") + return; + const envelope = { id: data.id }; + if (typeof data.parent_id === "string") + envelope.parent_id = data.parent_id; + this.#pendingCheckpointByNamespace.set(namespaceKey2(namespace), envelope); } - return result.value; -}, parse11, _parseAsync2 = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))); - captureStackTrace2(e, params?.callee); - throw e; + consumeCheckpoint(namespace) { + const key = namespaceKey2(namespace); + const checkpoint = this.#pendingCheckpointByNamespace.get(key); + if (checkpoint != null) + this.#pendingCheckpointByNamespace.delete(key); + return checkpoint; } - return result.value; -}, parseAsync3, _safeParse2 = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError2; + recordMessages(messages, metadata) { + const current = this.store.getSnapshot(); + let changed = false; + const next = new Map(current); + for (const msg of messages) { + const id = msg?.id; + if (typeof id !== "string" || id.length === 0) + continue; + const prev = next.get(id); + if (prev != null && prev.parentCheckpointId === metadata.parentCheckpointId) + continue; + next.set(id, { + ...prev, + ...metadata + }); + changed = true; + } + if (changed) + this.store.setState(() => next); } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError2)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) - } : { success: true, data: result.value }; -}, safeParse3, _safeParseAsync2 = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) - } : { success: true, data: result.value }; -}, safeParseAsync3; -var init_parse6 = __esm(() => { - init_core4(); - init_errors11(); - init_util3(); - parse11 = /* @__PURE__ */ _parse2($ZodRealError2); - parseAsync3 = /* @__PURE__ */ _parseAsync2($ZodRealError2); - safeParse3 = /* @__PURE__ */ _safeParse2($ZodRealError2); - safeParseAsync3 = /* @__PURE__ */ _safeParseAsync2($ZodRealError2); +}; +var init_message_metadata_tracker = __esm(() => { + init_store2(); + init_namespace2(); + EMPTY_METADATA_MAP = /* @__PURE__ */ new Map; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js -var exports_regexes2 = {}; -__export(exports_regexes2, { - xid: () => xid3, - uuid7: () => uuid73, - uuid6: () => uuid63, - uuid4: () => uuid43, - uuid: () => uuid10, - uppercase: () => uppercase2, - unicodeEmail: () => unicodeEmail2, - undefined: () => _undefined4, - ulid: () => ulid3, - time: () => time4, - string: () => string4, - rfc5322Email: () => rfc5322Email2, - number: () => number4, - null: () => _null4, - nanoid: () => nanoid3, - lowercase: () => lowercase2, - ksuid: () => ksuid3, - ipv6: () => ipv63, - ipv4: () => ipv43, - integer: () => integer2, - html5Email: () => html5Email2, - hostname: () => hostname3, - guid: () => guid3, - extendedDuration: () => extendedDuration2, - emoji: () => emoji3, - email: () => email3, - e164: () => e1643, - duration: () => duration3, - domain: () => domain2, - datetime: () => datetime3, - date: () => date6, - cuid2: () => cuid23, - cuid: () => cuid5, - cidrv6: () => cidrv63, - cidrv4: () => cidrv43, - browserEmail: () => browserEmail2, - boolean: () => boolean4, - bigint: () => bigint4, - base64url: () => base64url3, - base64: () => base645, - _emoji: () => _emoji3 +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/lifecycle-loading-tracker.js +var LifecycleLoadingTracker = class { + #store; + #isDisposed; + #lastTerminalLifecycleSeq = -1; + constructor(params) { + this.#store = params.store; + this.#isDisposed = params.isDisposed; + } + listener = (event) => { + this.handle(event); + }; + reset() { + this.#lastTerminalLifecycleSeq = -1; + } + handle(event) { + if (event.method !== "lifecycle") + return; + if (!isRootNamespace(event.params.namespace)) + return; + const lifecycle = event.params.data; + const seq = typeof event.seq === "number" ? event.seq : undefined; + if (lifecycle?.event === "running") { + if (seq != null && seq <= this.#lastTerminalLifecycleSeq) + return; + this.#store.setState((s) => s.isLoading ? s : { + ...s, + isLoading: true + }); + return; + } + if (lifecycle?.event === "completed" || lifecycle?.event === "failed" || lifecycle?.event === "interrupted") { + if (seq != null) + this.#lastTerminalLifecycleSeq = Math.max(this.#lastTerminalLifecycleSeq, seq); + setTimeout(() => { + if (this.#isDisposed()) + return; + this.#store.setState((s) => s.isLoading ? { + ...s, + isLoading: false + } : s); + }, 0); + } + } +}; +var init_lifecycle_loading_tracker = __esm(() => { + init_namespace2(); }); -function emoji3() { - return new RegExp(_emoji3, "u"); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/message-reconciliation.js +function reconcileMessagesFromValues({ valueMessages, currentMessages, currentIndexById, previousValueMessageIds, streamedMessageIds, preferValuesMessage }) { + const valueMessageIds = /* @__PURE__ */ new Set; + const merged = []; + for (const valuesMessage of valueMessages) { + const id = normalizedMessageId(valuesMessage); + if (id == null) { + merged.push(valuesMessage); + continue; + } + valueMessageIds.add(id); + const streamIdx = currentIndexById.get(id); + const streamedMessage = streamIdx != null && (streamedMessageIds == null || streamedMessageIds.has(id)) ? currentMessages[streamIdx] : undefined; + if (streamedMessage != null && preferValuesMessage?.(valuesMessage, streamedMessage) !== true) + merged.push(streamedMessage); + else + merged.push(valuesMessage); + } + for (const existing of currentMessages) { + const id = normalizedMessageId(existing); + if (id == null) + continue; + if (valueMessageIds.has(id)) + continue; + if (previousValueMessageIds.has(id)) + continue; + if (streamedMessageIds != null && !streamedMessageIds.has(id)) + continue; + merged.push(existing); + } + return { + messages: messagesEqualList(currentMessages, merged) ? currentMessages : merged, + valueMessageIds + }; } -function timeSource2(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex2 = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex2; +function buildMessageIndex(messages) { + const index2 = /* @__PURE__ */ new Map; + messages.forEach((message, idx) => { + const id = normalizedMessageId(message); + if (id != null) + index2.set(id, idx); + }); + return index2; } -function time4(args) { - return new RegExp(`^${timeSource2(args)}$`); +function shouldPreferValuesMessageForToolCalls(valuesMessage, streamedMessage) { + const valuesToolCalls = getMessageToolCalls(valuesMessage); + if (valuesToolCalls.length === 0) + return false; + const streamedToolCalls = getMessageToolCalls(streamedMessage); + if (streamedToolCalls.length < valuesToolCalls.length) + return true; + const streamedIds = new Set(streamedToolCalls.map((toolCall) => toolCall.id).filter((id) => typeof id === "string" && id.length > 0)); + if (valuesToolCalls.some((toolCall) => { + return typeof toolCall.id === "string" && !streamedIds.has(toolCall.id); + })) + return true; + return valuesToolCalls.some((valuesToolCall) => { + const streamedToolCall = streamedToolCalls.find((candidate) => typeof valuesToolCall.id === "string" && candidate.id === valuesToolCall.id); + return streamedToolCall != null && hasMeaningfulArgs(valuesToolCall.args) && !jsonishEqual(valuesToolCall.args, streamedToolCall.args); + }); } -function datetime3(args) { - const time5 = timeSource2({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - if (args.offset) - opts.push(`([+-]\\d{2}:\\d{2})`); - const timeRegex2 = `${time5}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource2}T(?:${timeRegex2})$`); +function hasMeaningfulArgs(args) { + if (args == null) + return false; + if (typeof args === "string") + return args.length > 0; + if (typeof args === "object") + return Object.keys(args).length > 0; + return true; } -var cuid5, cuid23, ulid3, xid3, ksuid3, nanoid3, duration3, extendedDuration2, guid3, uuid10 = (version4) => { - if (!version4) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}, uuid43, uuid63, uuid73, email3, html5Email2, rfc5322Email2, unicodeEmail2, browserEmail2, _emoji3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, ipv43, ipv63, cidrv43, cidrv63, base645, base64url3, hostname3, domain2, e1643, dateSource2 = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`, date6, string4 = (params) => { - const regex2 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex2}$`); -}, bigint4, integer2, number4, boolean4, _null4, _undefined4, lowercase2, uppercase2; -var init_regexes2 = __esm(() => { - cuid5 = /^[cC][^\s-]{8,}$/; - cuid23 = /^[0-9a-z]+$/; - ulid3 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; - xid3 = /^[0-9a-vA-V]{20}$/; - ksuid3 = /^[A-Za-z0-9]{27}$/; - nanoid3 = /^[a-zA-Z0-9_-]{21}$/; - duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; - extendedDuration2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; - uuid43 = /* @__PURE__ */ uuid10(4); - uuid63 = /* @__PURE__ */ uuid10(6); - uuid73 = /* @__PURE__ */ uuid10(7); - email3 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; - html5Email2 = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - rfc5322Email2 = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - unicodeEmail2 = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; - browserEmail2 = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; - ipv43 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; - cidrv43 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; - cidrv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base645 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; - base64url3 = /^[A-Za-z0-9_-]*$/; - hostname3 = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; - domain2 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; - e1643 = /^\+(?:[0-9]){6,14}[0-9]$/; - date6 = /* @__PURE__ */ new RegExp(`^${dateSource2}$`); - bigint4 = /^\d+n?$/; - integer2 = /^\d+$/; - number4 = /^-?\d+(?:\.\d+)?/i; - boolean4 = /true|false/i; - _null4 = /null/i; - _undefined4 = /undefined/i; - lowercase2 = /^[^A-Z]*$/; - uppercase2 = /^[^a-z]*$/; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js -function handleCheckPropertyResult2(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...prefixIssues2(property, result.issues)); +function messagesEqualList(previous, next) { + if (previous === next) + return true; + if (previous.length !== next.length) + return false; + for (let i = 0;i < previous.length; i += 1) + if (!messagesEqual(previous[i], next[i])) + return false; + return true; +} +function messagesEqual(previous, next) { + if (previous === next) + return true; + if (previous == null || next == null) + return false; + const previousRecord = previous; + const nextRecord = next; + const previousType = typeof previous.getType === "function" ? previous.getType() : previousRecord.type; + const nextType = typeof next.getType === "function" ? next.getType() : nextRecord.type; + return previous.id === next.id && previousType === nextType && jsonishEqual(previous.content, next.content) && previousRecord.tool_call_id === nextRecord.tool_call_id && previousRecord.status === nextRecord.status && jsonishEqual(previousRecord.additional_kwargs, nextRecord.additional_kwargs) && jsonishEqual(previousRecord.response_metadata, nextRecord.response_metadata) && jsonishEqual(previousRecord.tool_calls, nextRecord.tool_calls) && jsonishEqual(previousRecord.tool_call_chunks, nextRecord.tool_call_chunks) && jsonishEqual(previousRecord.usage_metadata, nextRecord.usage_metadata); +} +function normalizedMessageId(message) { + return typeof message.id === "string" && message.id.length > 0 ? message.id : undefined; +} +function getMessageToolCalls(message) { + const raw2 = message.tool_calls; + if (!Array.isArray(raw2)) + return []; + return raw2.filter((toolCall) => toolCall != null && typeof toolCall === "object"); +} +function jsonishEqual(previous, next) { + return jsonishEqualAtDepth(previous, next, 0); +} +function jsonishEqualAtDepth(previous, next, depth) { + if (Object.is(previous, next)) + return true; + if (previous == null || next == null) + return false; + if (typeof previous !== "object" || typeof next !== "object") + return false; + if (depth >= 4) + return false; + if (Array.isArray(previous) || Array.isArray(next)) { + if (!Array.isArray(previous) || !Array.isArray(next)) + return false; + if (previous.length !== next.length) + return false; + for (let i = 0;i < previous.length; i += 1) + if (!jsonishEqualAtDepth(previous[i], next[i], depth + 1)) + return false; + return true; + } + const previousRecord = previous; + const nextRecord = next; + const previousKeys = Object.keys(previousRecord).filter((key) => typeof previousRecord[key] !== "function"); + const nextKeys = Object.keys(nextRecord).filter((key) => typeof nextRecord[key] !== "function"); + if (previousKeys.length !== nextKeys.length) + return false; + for (const key of previousKeys) { + if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) + return false; + if (!jsonishEqualAtDepth(previousRecord[key], nextRecord[key], depth + 1)) + return false; } + return true; } -var $ZodCheck2, numericOriginMap2, $ZodCheckLessThan2, $ZodCheckGreaterThan2, $ZodCheckMultipleOf2, $ZodCheckNumberFormat2, $ZodCheckBigIntFormat2, $ZodCheckMaxSize2, $ZodCheckMinSize2, $ZodCheckSizeEquals2, $ZodCheckMaxLength2, $ZodCheckMinLength2, $ZodCheckLengthEquals2, $ZodCheckStringFormat2, $ZodCheckRegex2, $ZodCheckLowerCase2, $ZodCheckUpperCase2, $ZodCheckIncludes2, $ZodCheckStartsWith2, $ZodCheckEndsWith2, $ZodCheckProperty2, $ZodCheckMimeType2, $ZodCheckOverwrite2; -var init_checks3 = __esm(() => { - init_core4(); - init_regexes2(); - init_util3(); - $ZodCheck2 = /* @__PURE__ */ $constructor2("$ZodCheck", (inst, def) => { - var _a4; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a4 = inst._zod).onattach ?? (_a4.onattach = []); - }); - numericOriginMap2 = { - number: "number", - bigint: "bigint", - object: "date" +var init_message_reconciliation = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/root-message-projection.js +function syncMessagesIntoValues(values, messagesKey, messages) { + const record3 = values; + const current = record3[messagesKey]; + if (Array.isArray(current) && messagesEqualList2(current, messages)) + return values; + return { + ...record3, + [messagesKey]: messages }; - $ZodCheckLessThan2 = /* @__PURE__ */ $constructor2("$ZodCheckLessThan", (inst, def) => { - $ZodCheck2.init(inst, def); - const origin = numericOriginMap2[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; +} +function messagesEqualList2(previous, next) { + if (previous === next) + return true; + if (previous.length !== next.length) + return false; + for (let i = 0;i < previous.length; i += 1) + if (!messagesEqual(previous[i], next[i])) + return false; + return true; +} +function stateValuesShallowEqual(previous, next, messagesKey) { + if (previous === next) + return true; + const previousRecord = previous; + const nextRecord = next; + const previousKeys = Object.keys(previousRecord); + const nextKeys = Object.keys(nextRecord); + if (previousKeys.length !== nextKeys.length) + return false; + for (const key of previousKeys) { + if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) + return false; + const previousValue = previousRecord[key]; + const nextValue = nextRecord[key]; + if (key === messagesKey && Array.isArray(previousValue) && Array.isArray(nextValue)) + continue; + if (!Object.is(previousValue, nextValue)) + return false; + } + return true; +} +var RootMessageProjection = class { + #messagesKey; + #store; + #assembler = new MessageAssembler; + #roles = /* @__PURE__ */ new Map; + #indexById = /* @__PURE__ */ new Map; + #valuesMessageIds = /* @__PURE__ */ new Set; + #toolCallIdByNamespace = /* @__PURE__ */ new Map; + #pendingMessages = null; + #pendingValues = null; + #flushScheduled = false; + constructor(params) { + this.#messagesKey = params.messagesKey; + this.#store = params.store; + } + reset() { + this.#assembler = new MessageAssembler; + this.#roles.clear(); + this.#indexById.clear(); + this.#valuesMessageIds = /* @__PURE__ */ new Set; + this.#toolCallIdByNamespace.clear(); + this.#pendingMessages = null; + this.#pendingValues = null; + this.#flushScheduled = false; + } + recordToolCallNamespace(namespace, toolCallId) { + this.#toolCallIdByNamespace.set(namespaceKey2(namespace), toolCallId); + } + handleMessage(event) { + const data = event.params.data; + if (data.event === "message-start") { + const startData = data; + const role = startData.role ?? "ai"; + const extendedRole = startData.role ?? role; + let toolCallId = startData.tool_call_id; + if (extendedRole === "tool" && toolCallId == null) { + const messageId = startData.id; + if (messageId != null) { + const match2 = /-tool-(.+)$/.exec(messageId); + if (match2 != null) + toolCallId = match2[1]; + } + if (toolCallId == null) + toolCallId = this.#toolCallIdByNamespace.get(namespaceKey2(event.params.namespace)); } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + if (startData.id != null) + this.#roles.set(startData.id, { + role: extendedRole, + toolCallId + }); + } + const update = this.#assembler.consume(event); + if (update == null) + return; + const id = update.message.id; + if (id == null) + return; + const captured = this.#roles.get(id) ?? { role: "ai" }; + const base = assembledMessageToBaseMessage(update.message, captured.role, { toolCallId: captured.toolCallId }); + const baselineMessages = this.#pendingMessages ?? this.#store.getSnapshot().messages; + const existingIdx = this.#indexById.get(id); + let messages; + if (existingIdx == null) { + this.#indexById.set(id, baselineMessages.length); + messages = [...baselineMessages, base]; + } else if (messagesEqual(baselineMessages[existingIdx], base)) + return; + else { + messages = baselineMessages.slice(); + messages[existingIdx] = base; + } + const baselineValues = this.#pendingValues ?? this.#store.getSnapshot().values; + const values = syncMessagesIntoValues(baselineValues, this.#messagesKey, messages); + this.#pendingMessages = messages; + if (values !== baselineValues) + this.#pendingValues = values; + this.#scheduleFlush(); + } + applyValues(nextValues, nextMessages) { + const baselineSnapshot = this.#store.getSnapshot(); + const baselineMessages = this.#pendingMessages ?? baselineSnapshot.messages; + const baselineValues = this.#pendingValues ?? baselineSnapshot.values; + if (nextMessages.length === 0) { + if (stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)) return; - } - payload.issues.push({ - origin, - code: "too_big", - maximum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); + this.#pendingValues = syncMessagesIntoValues(nextValues, this.#messagesKey, baselineMessages); + this.#scheduleFlush(); + return; + } + const reconciliation = reconcileMessagesFromValues({ + valueMessages: nextMessages, + currentMessages: baselineMessages, + currentIndexById: this.#indexById, + previousValueMessageIds: this.#valuesMessageIds, + preferValuesMessage: shouldPreferValuesMessageForToolCalls + }); + this.#valuesMessageIds = reconciliation.valueMessageIds; + const messages = reconciliation.messages; + const values = { + ...nextValues, + [this.#messagesKey]: messages }; - }); - $ZodCheckGreaterThan2 = /* @__PURE__ */ $constructor2("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck2.init(inst, def); - const origin = numericOriginMap2[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } + if (messages === baselineMessages && stateValuesShallowEqual(baselineValues, values, this.#messagesKey)) + return; + this.#indexById.clear(); + for (const [id, idx] of buildMessageIndex(messages)) + this.#indexById.set(id, idx); + this.#pendingMessages = messages; + this.#pendingValues = values; + this.#scheduleFlush(); + } + #scheduleFlush = () => { + if (this.#flushScheduled) + return; + this.#flushScheduled = true; + setTimeout(this.#flushPending, 0); + }; + #flushPending = () => { + this.#flushScheduled = false; + const messages = this.#pendingMessages; + const values = this.#pendingValues; + this.#pendingMessages = null; + this.#pendingValues = null; + if (messages == null && values == null) + return; + this.#store.setState((s) => { + if (messages == null) + return values == null ? s : { + ...s, + values + }; + if (values == null) + return { + ...s, + messages + }; + return { + ...s, + messages, + values + }; }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + }; +}; +var init_root_message_projection = __esm(() => { + init_messages8(); + init_namespace2(); + init_assembled_to_message(); + init_message_reconciliation(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/submit-coordinator.js +function terminalReason(event) { + if (event === "completed") + return "success"; + if (event === "failed") + return "error"; + if (event === "interrupted") + return "interrupt"; + return "stopped"; +} +function bindThreadConfig(config3, threadId) { + const base = config3 != null && typeof config3 === "object" ? config3 : {}; + const configurable = base.configurable != null && typeof base.configurable === "object" ? base.configurable : {}; + return { + ...base, + configurable: { + ...configurable, + thread_id: threadId + } + }; +} +var EMPTY_QUEUE, SubmitCoordinator = class { + #options; + #rootStore; + #queueStore; + #getDisposed; + #getCurrentThreadId; + #setCurrentThreadId; + #rememberSelfCreatedThreadId; + #forgetSelfCreatedThreadId; + #hydrate; + #ensureThread; + #startDeferredRootPump; + #abandonDeferredRootPump; + #waitForRootPumpReady; + #awaitNextTerminal; + #onSubmitStart; + #onRunStart; + #onRunCreated; + #onRunCompleted; + #onRunEnd; + #runAbort; + constructor(params) { + this.#options = params.options; + this.#rootStore = params.rootStore; + this.#queueStore = params.queueStore; + this.#getDisposed = params.getDisposed; + this.#getCurrentThreadId = params.getCurrentThreadId; + this.#setCurrentThreadId = params.setCurrentThreadId; + this.#rememberSelfCreatedThreadId = params.rememberSelfCreatedThreadId; + this.#forgetSelfCreatedThreadId = params.forgetSelfCreatedThreadId; + this.#hydrate = params.hydrate; + this.#ensureThread = params.ensureThread; + this.#startDeferredRootPump = params.startDeferredRootPump; + this.#abandonDeferredRootPump = params.abandonDeferredRootPump; + this.#waitForRootPumpReady = params.waitForRootPumpReady; + this.#awaitNextTerminal = params.awaitNextTerminal; + this.#onSubmitStart = params.onSubmitStart ?? (() => { + return; + }); + this.#onRunStart = params.onRunStart ?? (() => { + return; + }); + this.#onRunCreated = params.onRunCreated ?? (() => { + return; + }); + this.#onRunCompleted = params.onRunCompleted ?? (() => { + return; + }); + this.#onRunEnd = params.onRunEnd ?? (() => { + return; + }); + } + async submit(input, options) { + if (this.#getDisposed()) + return; + this.#onSubmitStart(); + const overrideThreadId = options?.threadId; + if (overrideThreadId !== undefined && overrideThreadId !== this.#getCurrentThreadId()) + await this.#hydrate(overrideThreadId); + const wasSelfCreated = this.#getCurrentThreadId() == null; + if (wasSelfCreated) { + const threadId = v7_default2(); + this.#setCurrentThreadId(threadId); + this.#rememberSelfCreatedThreadId(threadId); + this.#options.onThreadId?.(threadId); + this.#rootStore.setState((s) => ({ + ...s, + threadId + })); + } + const currentThreadId = this.#getCurrentThreadId(); + if (currentThreadId == null) + return; + const thread = this.#ensureThread(currentThreadId, wasSelfCreated); + const activeThreadId = currentThreadId; + await this.#waitForRootPumpReady(); + const strategy = options?.multitaskStrategy ?? "rollback"; + const hasActiveRun = !wasSelfCreated && this.#runAbort != null && !this.#runAbort.signal.aborted; + if (hasActiveRun && strategy === "reject") + throw new Error("submit() rejected: a run is already in flight and multitaskStrategy is 'reject'."); + if (hasActiveRun && strategy === "enqueue") { + this.#enqueueSubmission(input, options); + return; + } + this.#runAbort?.abort(); + const abort = new AbortController; + this.#runAbort = abort; + this.#rootStore.setState((s) => ({ + ...s, + interrupts: [], + interrupt: undefined, + error: undefined, + isLoading: true + })); + const boundConfig = bindThreadConfig(options?.config, currentThreadId); + const terminalPromise = this.#awaitNextTerminal(abort.signal); + this.#onRunStart(); + let terminalSettled = false; + let createdRunId; + let pendingCompletionReason; + let completionNotified = false; + const notifyCompletion = (reason) => { + if (completionNotified) + return; + if (createdRunId == null) { + pendingCompletionReason = reason; return; } - payload.issues.push({ - origin, - code: "too_small", - minimum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); + completionNotified = true; + this.#onRunCompleted(reason, createdRunId); }; - }); - $ZodCheckMultipleOf2 = /* @__PURE__ */ $constructor2("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck2.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a4; - (_a4 = inst2._zod.bag).multipleOf ?? (_a4.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder3(payload.value, def.value) === 0; - if (isMultiple) + const reportError = (error90) => { + if (abort.signal.aborted) return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort - }); + this.#rootStore.setState((s) => ({ + ...s, + error: error90 + })); + try { + options?.onError?.(error90); + } catch {} }; - }); - $ZodCheckNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck2.init(inst, def); - def.format = def.format || "float64"; - const isInt2 = def.format?.includes("int"); - const origin = isInt2 ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES2[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt2) - bag.pattern = integer2; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt2) { - if (!Number.isInteger(input)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - input, - inst - }); - return; + try { + let terminal; + const commandPromise = thread.submitRun({ + input: input ?? null, + config: boundConfig, + metadata: options?.metadata ?? undefined, + forkFrom: options?.forkFrom, + multitaskStrategy: options?.multitaskStrategy === "enqueue" ? "enqueue" : options?.multitaskStrategy + }); + commandPromise.then(() => { + this.#startDeferredRootPump(); + this.#forgetSelfCreatedThreadId(activeThreadId); + }, () => { + if (wasSelfCreated) { + this.#abandonDeferredRootPump(); + this.#forgetSelfCreatedThreadId(activeThreadId); } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort - }); - } else { - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort - }); - } + }); + const notifyCreated = (result) => { + if (typeof result.run_id !== "string") return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort + createdRunId = result.run_id; + this.#onRunCreated(createdRunId); + if (pendingCompletionReason != null) + notifyCompletion(pendingCompletionReason); + }; + const first = await Promise.race([terminalPromise.then((value) => ({ + type: "terminal", + value + })), commandPromise.then((result) => ({ + type: "command", + result + }), (error90) => ({ + type: "error", + error: error90 + }))]); + if (first.type === "error") + throw first.error; + if (first.type === "command") + notifyCreated(first.result); + else { + terminal = first.value; + terminalSettled = true; + commandPromise.then(notifyCreated).catch((error90) => { + if (!terminalSettled) + reportError(error90); }); } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inst - }); - } - }; - }); - $ZodCheckBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck2.init(inst, def); - const [minimum, maximum] = BIGINT_FORMAT_RANGES2[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inst - }); + terminal ??= await terminalPromise; + terminalSettled = true; + if (terminal.event === "failed" && !abort.signal.aborted) { + const runError = new Error(terminal.error ?? "Run failed with no error message"); + this.#rootStore.setState((s) => ({ + ...s, + error: runError + })); + try { + options?.onError?.(runError); + } catch {} } + notifyCompletion(terminalReason(terminal.event)); + } catch (error90) { + reportError(error90); + } finally { + this.#rootStore.setState((s) => ({ + ...s, + isLoading: false + })); + if (this.#runAbort === abort) + this.#runAbort = undefined; + this.#onRunEnd(); + setTimeout(() => this.#drainQueue(), 0); + } + } + async stop() { + this.abortActiveRun(); + this.#rootStore.setState((s) => ({ + ...s, + isLoading: false + })); + } + abortActiveRun() { + this.#runAbort?.abort(); + this.#runAbort = undefined; + } + async cancelQueued(id) { + const current = this.#queueStore.getSnapshot(); + const next = current.filter((entry) => entry.id !== id); + if (next.length === current.length) + return false; + this.#queueStore.setState(() => next); + return true; + } + async clearQueue() { + this.#queueStore.setState(() => EMPTY_QUEUE); + } + #enqueueSubmission(input, options) { + const entry = { + id: v7_default2(), + values: input ?? undefined, + options, + createdAt: /* @__PURE__ */ new Date }; - }); - $ZodCheckMaxSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxSize", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: getSizableOrigin2(input), - code: "too_big", - maximum: def.maximum, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckMinSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMinSize", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: getSizableOrigin2(input), - code: "too_small", - minimum: def.minimum, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckSizeEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckSizeEquals", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: getSizableOrigin2(input), - ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); + this.#queueStore.setState((current) => [...current, entry]); + } + #drainQueue() { + if (this.#getDisposed()) + return; + if (this.#runAbort != null && !this.#runAbort.signal.aborted) + return; + const current = this.#queueStore.getSnapshot(); + if (current.length === 0) + return; + const [next, ...rest] = current; + this.#queueStore.setState(() => rest); + const nextOptions = { + ...next.options ?? {}, + multitaskStrategy: undefined }; - }); - $ZodCheckMaxLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxLength", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; + this.submit(next.values, nextOptions).catch(() => {}); + } +}; +var init_submit_coordinator = __esm(() => { + init_dist_node(); + EMPTY_QUEUE = Object.freeze([]); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/tool-calls.js +function upsertToolCall(current, next) { + const snapshot = { ...next }; + const idx = current.findIndex((toolCall) => toolCall.callId === next.callId); + if (idx < 0) + return [...current, snapshot]; + const updated = current.slice(); + updated[idx] = snapshot; + return updated; +} +function reconcileToolCallsFromMessages(toolCalls, messages) { + let updated; + for (const message of messages) { + if (!ToolMessage.isInstance(message)) + continue; + const callId = message.tool_call_id; + if (typeof callId !== "string" || callId.length === 0) + continue; + const currentToolCalls = updated ?? toolCalls; + const idx = currentToolCalls.findIndex((toolCall) => toolCall.callId === callId); + if (idx < 0) + continue; + const current = currentToolCalls[idx]; + if (current.status === "finished" && current.output != null) + continue; + const output = parseToolOutput(message.content); + if (output == null) + continue; + updated = upsertToolCall(currentToolCalls, { + ...current, + output, + status: "finished", + error: undefined }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin2(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); + } + return updated ?? toolCalls; +} +var init_tool_calls = __esm(() => { + init_tools4(); + init_messages(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/controller.js +function isAbortLikeError(error90) { + if (error90 == null || typeof error90 !== "object") + return false; + const maybeError = error90; + return maybeError.name === "AbortError" || typeof maybeError.message === "string" && maybeError.message.includes("aborted"); +} +function lifecycleReason(event) { + if (event === "completed") + return "success"; + if (event === "failed") + return "error"; + if (event === "interrupted") + return "interrupt"; + return null; +} +function extractAndCoerceMessages(values, messagesKey) { + const raw2 = values[messagesKey]; + if (!Array.isArray(raw2)) + return []; + return ensureMessageInstances(raw2); +} +var ROOT_NAMESPACE, ROOT_PUMP_CHANNELS, StreamController = class { + rootStore; + subagentStore; + subgraphStore; + subgraphByNodeStore; + messageMetadataStore; + queueStore; + registry; + #options; + #messagesKey; + #subagents = new SubagentDiscovery; + #subgraphs = new SubgraphDiscovery; + #messageMetadata = new MessageMetadataTracker; + #thread; + #currentThreadId; + #rootSubscription; + #rootPump; + #rootPumpReady; + #rootPumpDeferred = false; + #threadEventUnsubscribe; + #disposed = false; + #pendingDisposeTimer = null; + #resolvedInterrupts = /* @__PURE__ */ new Set; + #hydratedActiveInterruptIds = null; + #submitGeneration = 0; + #selfCreatedThreadIds = /* @__PURE__ */ new Set; + #rootEventListeners = /* @__PURE__ */ new Set; + #rootBus; + #activeRunId; + #localRunDepth = 0; + #hydrationPromise; + #resolveHydration; + #rejectHydration; + #rootToolAssembler = new ToolCallAssembler; + #rootMessages; + #lifecycleLoading; + #submitter; + #threadListeners = /* @__PURE__ */ new Set; + constructor(options) { + this.#options = options; + this.#messagesKey = options.messagesKey ?? "messages"; + this.#currentThreadId = options.threadId ?? null; + this.#rootBus = { + channels: ROOT_PUMP_CHANNELS, + subscribe: (listener) => { + this.#rootEventListeners.add(listener); + return () => { + this.#rootEventListeners.delete(listener); + }; + } }; - }); - $ZodCheckMinLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMinLength", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; + this.registry = new ChannelRegistry(this.#rootBus); + this.subagentStore = this.#subagents.store; + this.subgraphStore = this.#subgraphs.store; + this.subgraphByNodeStore = this.#subgraphs.byNodeStore; + this.rootStore = new StreamStore(this.#createInitialSnapshot()); + this.#rootMessages = new RootMessageProjection({ + messagesKey: this.#messagesKey, + store: this.rootStore }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin2(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckLengthEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckLengthEquals", (inst, def) => { - var _a4; - $ZodCheck2.init(inst, def); - (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => { - const val = payload.value; - return !nullish3(val) && val.length !== undefined; + this.#lifecycleLoading = new LifecycleLoadingTracker({ + store: this.rootStore, + isDisposed: () => this.#disposed }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; + this.messageMetadataStore = this.#messageMetadata.store; + this.queueStore = new StreamStore(EMPTY_QUEUE); + this.#submitter = new SubmitCoordinator({ + options: this.#options, + rootStore: this.rootStore, + queueStore: this.queueStore, + getDisposed: () => this.#disposed, + getCurrentThreadId: () => this.#currentThreadId, + setCurrentThreadId: (threadId) => { + this.#currentThreadId = threadId; + }, + rememberSelfCreatedThreadId: (threadId) => { + this.#selfCreatedThreadIds.add(threadId); + }, + hydrate: (threadId) => this.hydrate(threadId), + ensureThread: (threadId, deferRootPump) => this.#ensureThread(threadId, deferRootPump), + startDeferredRootPump: () => this.#startDeferredRootPump(), + abandonDeferredRootPump: () => this.#abandonDeferredRootPump(), + forgetSelfCreatedThreadId: (threadId) => { + this.#selfCreatedThreadIds.delete(threadId); + }, + waitForRootPumpReady: () => this.#rootPumpReady, + awaitNextTerminal: (signal) => this.#awaitNextTerminal(signal), + onSubmitStart: () => { + this.#hydratedActiveInterruptIds = null; + this.#submitGeneration += 1; + }, + onRunStart: () => this.#markLocalRunStart(), + onRunCreated: (runId) => this.#notifyCreated(runId), + onRunCompleted: (reason, runId) => this.#notifyCompleted(reason, runId), + onRunEnd: () => this.#markLocalRunEnd() }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin2(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckStringFormat", (inst, def) => { - var _a4, _b; - $ZodCheck2.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set); - bag.patterns.add(def.pattern); - } + this.#hydrationPromise = this.#createHydrationPromise(); + this.#hydrationPromise.catch(() => { + return; }); - if (def.pattern) - (_a4 = inst._zod).check ?? (_a4.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...def.pattern ? { pattern: def.pattern.toString() } : {}, - inst, - continue: !def.abort - }); - }); + if (this.#currentThreadId != null) + this.hydrate(this.#currentThreadId); else - (_b = inst._zod).check ?? (_b.check = () => {}); - }); - $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat2.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase2); - $ZodCheckStringFormat2.init(inst, def); - }); - $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase2); - $ZodCheckStringFormat2.init(inst, def); - }); - $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => { - $ZodCheck2.init(inst, def); - const escapedRegex = escapeRegex3(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = new Set); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckStartsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck2.init(inst, def); - const pattern = new RegExp(`^${escapeRegex3(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = new Set); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckEndsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck2.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex3(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = new Set); - bag.patterns.add(pattern); + this.#resolveHydration(); + } + get hydrationPromise() { + return this.#hydrationPromise; + } + #createHydrationPromise() { + return new Promise((resolve2, reject) => { + this.#resolveHydration = resolve2; + this.#rejectHydration = reject; }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCheckProperty2 = /* @__PURE__ */ $constructor2("$ZodCheckProperty", (inst, def) => { - $ZodCheck2.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [] - }, {}); - if (result instanceof Promise) { - return result.then((result2) => handleCheckPropertyResult2(result2, payload, def.property)); - } - handleCheckPropertyResult2(result, payload, def.property); + } + #resetHydrationPromise() { + this.#hydrationPromise.catch(() => { return; - }; - }); - $ZodCheckMimeType2 = /* @__PURE__ */ $constructor2("$ZodCheckMimeType", (inst, def) => { - $ZodCheck2.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.mime = def.mime; }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst - }); - }; - }); - $ZodCheckOverwrite2 = /* @__PURE__ */ $constructor2("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck2.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; - }); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js -class Doc2 { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; + this.#hydrationPromise = this.#createHydrationPromise(); } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); + async hydrate(threadId) { + if (this.#disposed) + return; + const target = threadId === undefined ? this.#currentThreadId : threadId; + const changed = target !== this.#currentThreadId; + this.#currentThreadId = target ?? null; + this.rootStore.setState((s) => ({ + ...s, + threadId: this.#currentThreadId + })); + if (changed) { + this.#resetHydrationPromise(); + await this.#teardownThread(); + this.rootStore.setState(() => ({ + ...this.#createInitialSnapshot(), + threadId: this.#currentThreadId + })); + this.queueStore.setState(() => EMPTY_QUEUE); + } + if (this.#currentThreadId == null) { + this.rootStore.setState((s) => ({ + ...s, + isThreadLoading: false + })); + this.#resolveHydration(); return; } - const content = arg; - const lines = content.split(` -`).filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); + if (this.#selfCreatedThreadIds.has(this.#currentThreadId)) { + this.rootStore.setState((s) => ({ + ...s, + isThreadLoading: false + })); + this.#resolveHydration(); + return; + } + this.rootStore.setState((s) => ({ + ...s, + isThreadLoading: true + })); + let hydrationError; + let threadExists = false; + try { + const state = await this.#options.client.threads.getState(this.#currentThreadId); + threadExists = state != null; + if (state?.values != null) { + const checkpointId = state.checkpoint?.checkpoint_id; + const parentCheckpointId = state.parent_checkpoint?.checkpoint_id ?? undefined; + const syntheticCheckpoint = typeof checkpointId === "string" ? { + id: checkpointId, + ...parentCheckpointId != null ? { parent_id: parentCheckpointId } : {} + } : undefined; + this.#applyValues(state.values, syntheticCheckpoint); + } + if (Array.isArray(state?.tasks)) { + const generationAtFetch = this.#submitGeneration; + const activeInterrupts = []; + const activeIds = /* @__PURE__ */ new Set; + for (const task3 of state.tasks) { + if (!Array.isArray(task3?.interrupts)) + continue; + for (const interrupt3 of task3.interrupts) { + const typed = interrupt3; + const id = typed?.id; + if (typeof id !== "string" || activeIds.has(id)) + continue; + activeIds.add(id); + activeInterrupts.push({ + id, + value: typed?.value + }); + } + } + this.rootStore.setState((s) => ({ + ...s, + interrupts: activeInterrupts, + interrupt: activeInterrupts[0] + })); + if (this.#submitGeneration === generationAtFetch) + this.#hydratedActiveInterruptIds = activeIds; + } + } catch (error90) { + if (error90?.status !== 404) { + hydrationError = error90; + this.rootStore.setState((s) => ({ + ...s, + error: error90 + })); + } + } finally { + this.rootStore.setState((s) => ({ + ...s, + isThreadLoading: false + })); + if (hydrationError != null) + this.#rejectHydration(hydrationError); + else + this.#resolveHydration(); } + const thread = this.#ensureThread(this.#currentThreadId); + if (threadExists) + thread.startLifecycleWatcher(); } - compile() { - const F = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join(` -`)); + async submit(input, options) { + await this.#submitter.submit(input, options); } -} - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js -var version4; -var init_versions4 = __esm(() => { - version4 = { - major: 4, - minor: 0, - patch: 0 - }; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js -function isValidBase642(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } catch { - return false; + async stop(options) { + if (options?.cancel ?? true) { + const threadId = this.#currentThreadId; + const runId = this.#activeRunId; + if (threadId != null && runId != null) + try { + await this.#options.client.runs.cancel(threadId, runId); + } catch {} + } + await this.#submitter.stop(); } -} -function isValidBase64URL2(data) { - if (!base64url3.test(data)) - return false; - const base646 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - const padded = base646.padEnd(Math.ceil(base646.length / 4) * 4, "="); - return isValidBase642(padded); -} -function isValidJWT3(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } catch { - return false; + async disconnect() { + return this.stop({ cancel: false }); } -} -function handleArrayResult2(result, final2, index2) { - if (result.issues.length) { - final2.issues.push(...prefixIssues2(index2, result.issues)); + #markLocalRunStart() { + this.#localRunDepth += 1; } - final2.value[index2] = result.value; -} -function handleObjectResult(result, final2, key) { - if (result.issues.length) { - final2.issues.push(...prefixIssues2(key, result.issues)); + #markLocalRunEnd() { + this.#localRunDepth = Math.max(0, this.#localRunDepth - 1); } - final2.value[key] = result.value; -} -function handleOptionalObjectResult(result, final2, key, input) { - if (result.issues.length) { - if (input[key] === undefined) { - if (key in input) { - final2.value[key] = undefined; - } else { - final2.value[key] = result.value; - } - } else { - final2.issues.push(...prefixIssues2(key, result.issues)); - } - } else if (result.value === undefined) { - if (key in input) - final2.value[key] = undefined; - } else { - final2.value[key] = result.value; + #notifyCreated(runId) { + this.#activeRunId = runId; + try { + this.#options.onCreated?.({ runId }); + } catch {} } -} -function handleUnionResults2(results, final2, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final2.value = result.value; - return final2; - } + #notifyCompleted(reason, runId = this.#activeRunId) { + if (runId != null && runId === this.#activeRunId) + this.#activeRunId = undefined; + setTimeout(() => { + if (this.#disposed) + return; + try { + this.#options.onCompleted?.(runId == null ? { reason } : { + runId, + reason + }); + } catch {} + }, 0); } - final2.issues.push({ - code: "invalid_union", - input: final2.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))) - }); - return final2; -} -function mergeValues3(a, b) { - if (a === b) { - return { valid: true, data: a }; + #runLifecycleListener = (event) => { + if (this.#localRunDepth > 0) + return; + if (event.method !== "lifecycle") + return; + if (!isRootNamespace(event.params.namespace)) + return; + if (!this.rootStore.getSnapshot().isLoading) + return; + const lifecycle = event.params.data; + const reason = lifecycleReason(lifecycle?.event); + if (reason == null) + return; + this.#notifyCompleted(reason); + }; + async cancelQueued(id) { + return this.#submitter.cancelQueued(id); } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; + async clearQueue() { + await this.#submitter.clearQueue(); } - if (isPlainObject2(a) && isPlainObject2(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues3(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - } - newObj[key] = sharedValue.data; + async respond(response, options) { + if (this.#disposed || this.#thread == null) + throw new Error("No active thread to respond to."); + const resolved = options?.interruptId != null ? { + interruptId: options.interruptId, + namespace: options.namespace ?? [...ROOT_NAMESPACE] + } : this.#resolveInterruptForResume(); + if (resolved == null) + throw new Error("No pending interrupt to respond to."); + try { + await this.#thread.respondInput({ + namespace: resolved.namespace, + interrupt_id: resolved.interruptId, + response, + config: options?.config, + metadata: options?.metadata + }); + this.#markInterruptResolvedInRootStore(resolved.interruptId); + } catch (error90) { + if (this.#disposed && isAbortLikeError(error90)) + return; + throw error90; } - return { valid: true, data: newObj }; } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index2 = 0;index2 < a.length; index2++) { - const itemA = a[index2]; - const itemB = b[index2]; - const sharedValue = mergeValues3(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] - }; - } - newArray.push(sharedValue.data); + async respondAll(responsesById, options) { + if (this.#disposed || this.#thread == null) + throw new Error("No active thread to respond to."); + const entries = Object.entries(responsesById); + if (entries.length === 0) + throw new Error("respondAll() requires at least one response."); + const pending = this.#thread.interrupts; + const responses = entries.map(([interruptId, response]) => ({ + interrupt_id: interruptId, + response, + namespace: pending.find((entry) => entry.interruptId === interruptId)?.namespace ?? [...ROOT_NAMESPACE] + })); + try { + await this.#thread.respondInput({ + responses, + config: options?.config, + metadata: options?.metadata + }); + for (const { interrupt_id: interruptId } of responses) + this.#markInterruptResolvedInRootStore(interruptId); + } catch (error90) { + if (this.#disposed && isAbortLikeError(error90)) + return; + throw error90; } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults2(result, left, right) { - if (left.issues.length) { - result.issues.push(...left.issues); - } - if (right.issues.length) { - result.issues.push(...right.issues); } - if (aborted2(result)) - return result; - const merged = mergeValues3(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + async dispose() { + if (this.#disposed) + return; + this.#cancelPendingDispose(); + this.#disposed = true; + this.#submitter.abortActiveRun(); + await this.#teardownThread(); + await this.registry.dispose(); + this.#threadListeners.clear(); } - result.value = merged.data; - return result; -} -function handleTupleResult2(result, final2, index2) { - if (result.issues.length) { - final2.issues.push(...prefixIssues2(index2, result.issues)); + activate() { + this.#cancelPendingDispose(); + return () => { + if (this.#disposed) + return; + this.#pendingDisposeTimer = setTimeout(() => { + this.#pendingDisposeTimer = null; + this.dispose().catch(() => { + return; + }); + }, 0); + }; } - final2.value[index2] = result.value; -} -function handleMapResult2(keyResult, valueResult, final2, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes2.has(typeof key)) { - final2.issues.push(...prefixIssues2(key, keyResult.issues)); - } else { - final2.issues.push({ - origin: "map", - code: "invalid_key", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) - }); + #cancelPendingDispose() { + if (this.#pendingDisposeTimer != null) { + clearTimeout(this.#pendingDisposeTimer); + this.#pendingDisposeTimer = null; } } - if (valueResult.issues.length) { - if (propertyKeyTypes2.has(typeof key)) { - final2.issues.push(...prefixIssues2(key, valueResult.issues)); - } else { - final2.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key, - issues: valueResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) - }); - } + getThread() { + return this.#thread; } - final2.value.set(keyResult.value, valueResult.value); -} -function handleSetResult2(result, final2) { - if (result.issues.length) { - final2.issues.push(...result.issues); + subscribeThread(listener) { + this.#threadListeners.add(listener); + listener(this.#thread); + return () => { + this.#threadListeners.delete(listener); + }; } - final2.value.add(result.value); -} -function handleDefaultResult2(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; + #createInitialSnapshot() { + const values = this.#options.initialValues ?? {}; + return { + values, + messages: extractAndCoerceMessages(values, this.#messagesKey), + toolCalls: [], + interrupts: [], + interrupt: undefined, + isLoading: false, + isThreadLoading: this.#currentThreadId != null && !this.#selfCreatedThreadIds.has(this.#currentThreadId), + error: undefined, + threadId: this.#currentThreadId + }; } - return payload; -} -function handleNonOptionalResult2(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst + #ensureThread(threadId, deferRootPump = false) { + if (this.#thread != null) + return this.#thread; + this.#thread = this.#options.client.threads.stream(threadId, { + assistantId: this.#options.assistantId, + transport: this.#options.transport, + fetch: this.#options.fetch, + webSocketFactory: this.#options.webSocketFactory }); + this.registry.bind(this.#thread); + if (deferRootPump) { + this.#rootPumpReady = Promise.resolve(); + this.#rootPumpDeferred = true; + } else + this.#startRootPump(this.#thread); + this.#notifyThreadListeners(); + return this.#thread; } - return payload; -} -function handlePipeResult2(left, def, ctx) { - if (aborted2(left)) { - return left; + #startDeferredRootPump() { + if (!this.#rootPumpDeferred) + return; + if (this.#thread == null) + return; + this.#rootPumpDeferred = false; + this.#startRootPump(this.#thread); } - return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); -} -function handleReadonlyResult2(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -function handleRefineResult2(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - path: [...inst._zod.def.path ?? []], - continue: !inst._zod.def.abort - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(issue2(_iss)); + #abandonDeferredRootPump() { + if (!this.#rootPumpDeferred) + return; + this.#rootPumpDeferred = false; + this.#teardownThread(); } -} -var $ZodType2, $ZodString2, $ZodStringFormat2, $ZodGUID2, $ZodUUID2, $ZodEmail2, $ZodURL2, $ZodEmoji2, $ZodNanoID2, $ZodCUID3, $ZodCUID22, $ZodULID2, $ZodXID2, $ZodKSUID2, $ZodISODateTime2, $ZodISODate2, $ZodISOTime2, $ZodISODuration2, $ZodIPv42, $ZodIPv62, $ZodCIDRv42, $ZodCIDRv62, $ZodBase642, $ZodBase64URL2, $ZodE1642, $ZodJWT2, $ZodCustomStringFormat2, $ZodNumber2, $ZodNumberFormat2, $ZodBoolean2, $ZodBigInt2, $ZodBigIntFormat2, $ZodSymbol2, $ZodUndefined2, $ZodNull2, $ZodAny2, $ZodUnknown2, $ZodNever2, $ZodVoid2, $ZodDate2, $ZodArray2, $ZodObject2, $ZodUnion2, $ZodDiscriminatedUnion2, $ZodIntersection2, $ZodTuple2, $ZodRecord2, $ZodMap2, $ZodSet2, $ZodEnum2, $ZodLiteral2, $ZodFile2, $ZodTransform2, $ZodOptional2, $ZodNullable2, $ZodDefault2, $ZodPrefault2, $ZodNonOptional2, $ZodSuccess2, $ZodCatch2, $ZodNaN2, $ZodPipe2, $ZodReadonly2, $ZodTemplateLiteral2, $ZodPromise2, $ZodLazy2, $ZodCustom2; -var init_schemas3 = __esm(() => { - init_checks3(); - init_core4(); - init_parse6(); - init_regexes2(); - init_util3(); - init_versions4(); - init_util3(); - $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => { - var _a4; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version4; - const checks3 = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks3.unshift(inst); - } - for (const ch of checks3) { - for (const fn of ch._zod.onattach) { - fn(inst); - } + async#teardownThread() { + const thread = this.#thread; + this.#thread = undefined; + this.registry.bind(undefined); + this.#threadEventUnsubscribe?.(); + this.#threadEventUnsubscribe = undefined; + this.#rootEventListeners.delete(this.#lifecycleLoading.listener); + this.#rootEventListeners.delete(this.#runLifecycleListener); + try { + await this.#rootSubscription?.unsubscribe(); + } catch {} + this.#rootSubscription = undefined; + this.#rootPumpReady = undefined; + this.#rootPumpDeferred = false; + try { + await this.#rootPump; + } catch {} + this.#rootPump = undefined; + this.#rootMessages.reset(); + this.#rootToolAssembler = new ToolCallAssembler; + this.#lifecycleLoading.reset(); + this.#subagents.reset(); + this.#subgraphs.reset(); + this.#activeRunId = undefined; + this.#localRunDepth = 0; + this.#messageMetadata.reset(); + this.#hydratedActiveInterruptIds = null; + this.queueStore.setState(() => EMPTY_QUEUE); + if (thread != null) { + try { + await thread.close(); + } catch {} + this.#notifyThreadListeners(); } - if (checks3.length === 0) { - (_a4 = inst._zod).deferred ?? (_a4.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks4, ctx) => { - let isAborted2 = aborted2(payload); - let asyncResult; - for (const ch of checks4) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } else if (isAborted2) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError2; - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - if (!isAborted2) - isAborted2 = aborted2(payload, currLen); - }); - } else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted2) - isAborted2 = aborted2(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - inst._zod.run = (payload, ctx) => { - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError2; - return result.then((result2) => runChecks(result2, checks3, ctx)); + } + #usesEventStreamTransport() { + const transport = this.#options.transport; + if (transport === "websocket") + return false; + if (transport == null || transport === "sse") + return true; + return typeof transport.openEventStream === "function"; + } + #startRootPump(thread) { + if (this.#rootPump != null) + return; + let resolveReady; + this.#rootPumpReady = new Promise((resolve2) => { + resolveReady = resolve2; + }); + this.#threadEventUnsubscribe = thread.onEvent((event) => this.#onWildcardEvent(event)); + this.#rootEventListeners.add(this.#lifecycleLoading.listener); + this.#rootEventListeners.add(this.#runLifecycleListener); + this.#rootPump = (async () => { + try { + const subscriptionPromise = thread.subscribe({ + channels: [...ROOT_PUMP_CHANNELS], + namespaces: [[]], + depth: 1 + }); + if (this.#usesEventStreamTransport()) + queueMicrotask(() => { + resolveReady?.(); + resolveReady = undefined; + }); + const subscription = await subscriptionPromise; + resolveReady?.(); + resolveReady = undefined; + this.#rootSubscription = subscription; + while (!this.#disposed) { + for await (const event of subscription) { + if (this.#disposed) + break; + try { + this.#onRootEvent(event); + } catch {} + } + if (this.#disposed) + break; + if (!subscription.isPaused) + break; + await subscription.waitForResume(); } - return runChecks(result, checks3, ctx); + } catch { + resolveReady?.(); + resolveReady = undefined; + } + })(); + } + #onWildcardEvent(event) { + try { + this.#subagents.push(event); + } catch {} + this.#subgraphs.push(event); + this.#lifecycleLoading.handle(event); + this.#recordRootInterrupt(event); + } + #onRootEvent(event) { + try { + this.#subagents.push(event); + } catch {} + if (this.#rootEventListeners.size > 0) + for (const listener of this.#rootEventListeners) + try { + listener(event); + } catch {} + const isInternalNamespace = isInternalWorkNamespace(event.params.namespace); + const hasLegacySubagentNamespace = isLegacySubagentNamespace(event.params.namespace); + if (event.method === "messages") { + if (!isInternalNamespace) + this.#rootMessages.handleMessage(event); + return; + } + if (event.method === "tools") { + if (event.params.namespace.length <= 1 && !hasLegacySubagentNamespace) { + const toolData = event.params.data; + if (toolData.event === "tool-started" && typeof toolData.tool_call_id === "string") + this.#rootMessages.recordToolCallNamespace(event.params.namespace, toolData.tool_call_id); + const tc = this.#rootToolAssembler.consume(event); + if (tc != null) + this.rootStore.setState((s) => ({ + ...s, + toolCalls: upsertToolCall(s.toolCalls, tc) + })); + } + return; + } + if (event.method === "checkpoints") { + const data = event.params.data; + this.#messageMetadata.bufferCheckpoint(event.params.namespace, data); + return; + } + if (!isRootNamespace(event.params.namespace)) + return; + if (event.method === "values") { + const valuesEvent = event; + const bufferedCheckpoint = this.#messageMetadata.consumeCheckpoint(event.params.namespace); + this.#applyValues(valuesEvent.params.data, bufferedCheckpoint); + return; + } + if (event.method === "input.requested") { + this.#recordRootInterrupt(event); + return; + } + if (event.method === "lifecycle") + event.params.data; + } + #applyValues(raw2, checkpoint) { + if (raw2 == null || typeof raw2 !== "object" || Array.isArray(raw2)) + return; + const state = raw2; + const parentCheckpointId = checkpoint?.parent_id; + if (parentCheckpointId != null && Array.isArray(state[this.#messagesKey])) + this.#messageMetadata.recordMessages(state[this.#messagesKey], { parentCheckpointId }); + const maybeMessages = state[this.#messagesKey]; + let nextValues; + let nextMessages; + if (Array.isArray(maybeMessages)) { + const coerced = ensureMessageInstances(maybeMessages); + nextValues = { + ...state, + [this.#messagesKey]: coerced }; + nextMessages = coerced; + } else { + nextValues = state; + nextMessages = []; } - inst["~standard"] = { - validate: (value) => { - try { - const r = safeParse3(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } catch (_) { - return safeParseAsync3(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); - } - }, - vendor: "zod", - version: 1 - }; - }); - $ZodString2 = /* @__PURE__ */ $constructor2("$ZodString", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string4(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } catch (_2) {} - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst + this.#rootMessages.applyValues(nextValues, nextMessages); + if (nextMessages.length > 0) + this.rootStore.setState((s) => { + const toolCalls = reconcileToolCallsFromMessages(s.toolCalls, nextMessages); + if (toolCalls === s.toolCalls) + return s; + return { + ...s, + toolCalls + }; }); - return payload; + } + #recordRootInterrupt(event) { + if (event.method !== "input.requested") + return; + if (!isRootNamespace(event.params.namespace)) + return; + const data = event.params.data; + const interruptId = data?.interrupt_id; + if (typeof interruptId !== "string" || this.#resolvedInterrupts.has(interruptId)) + return; + if (this.#hydratedActiveInterruptIds != null && !this.#hydratedActiveInterruptIds.has(interruptId)) + return; + const interrupt3 = { + id: interruptId, + value: data.payload }; - }); - $ZodStringFormat2 = /* @__PURE__ */ $constructor2("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat2.init(inst, def); - $ZodString2.init(inst, def); - }); - $ZodGUID2 = /* @__PURE__ */ $constructor2("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid3); - $ZodStringFormat2.init(inst, def); - }); - $ZodUUID2 = /* @__PURE__ */ $constructor2("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8 + this.rootStore.setState((s) => { + if (s.interrupts.some((entry) => entry.id === interruptId)) + return s; + const interrupts = [...s.interrupts, interrupt3]; + return { + ...s, + interrupts, + interrupt: interrupts[0] }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid10(v)); - } else - def.pattern ?? (def.pattern = uuid10()); - $ZodStringFormat2.init(inst, def); - }); - $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email3); - $ZodStringFormat2.init(inst, def); - }); - $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => { - $ZodStringFormat2.init(inst, def); - inst._zod.check = (payload) => { - try { - const orig = payload.value; - const url2 = new URL(orig); - const href = url2.href; - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url2.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: hostname3.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (!orig.endsWith("/") && href.endsWith("/")) { - payload.value = href.slice(0, -1); - } else { - payload.value = href; - } - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodEmoji2 = /* @__PURE__ */ $constructor2("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji3()); - $ZodStringFormat2.init(inst, def); - }); - $ZodNanoID2 = /* @__PURE__ */ $constructor2("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid3); - $ZodStringFormat2.init(inst, def); - }); - $ZodCUID3 = /* @__PURE__ */ $constructor2("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid5); - $ZodStringFormat2.init(inst, def); - }); - $ZodCUID22 = /* @__PURE__ */ $constructor2("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid23); - $ZodStringFormat2.init(inst, def); - }); - $ZodULID2 = /* @__PURE__ */ $constructor2("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid3); - $ZodStringFormat2.init(inst, def); - }); - $ZodXID2 = /* @__PURE__ */ $constructor2("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid3); - $ZodStringFormat2.init(inst, def); - }); - $ZodKSUID2 = /* @__PURE__ */ $constructor2("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid3); - $ZodStringFormat2.init(inst, def); - }); - $ZodISODateTime2 = /* @__PURE__ */ $constructor2("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime3(def)); - $ZodStringFormat2.init(inst, def); - }); - $ZodISODate2 = /* @__PURE__ */ $constructor2("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date6); - $ZodStringFormat2.init(inst, def); - }); - $ZodISOTime2 = /* @__PURE__ */ $constructor2("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time4(def)); - $ZodStringFormat2.init(inst, def); - }); - $ZodISODuration2 = /* @__PURE__ */ $constructor2("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration3); - $ZodStringFormat2.init(inst, def); - }); - $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv43); - $ZodStringFormat2.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv4`; }); - }); - $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv63); - $ZodStringFormat2.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv6`; + } + #markInterruptResolvedInRootStore(interruptId) { + this.#resolvedInterrupts.add(interruptId); + this.rootStore.setState((s) => { + const interrupts = s.interrupts.filter((entry) => entry.id !== interruptId); + if (interrupts.length === s.interrupts.length && s.interrupt?.id !== interruptId) + return s; + return { + ...s, + interrupts, + interrupt: interrupts[0] + }; }); - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; - }); - $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv43); - $ZodStringFormat2.init(inst, def); - }); - $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv63); - $ZodStringFormat2.init(inst, def); - inst._zod.check = (payload) => { - const [address, prefix] = payload.value.split("/"); - try { - if (!prefix) - throw new Error; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error; - if (prefixNum < 0 || prefixNum > 128) - throw new Error; - new URL(`http://[${address}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); + } + #awaitNextTerminal(signal) { + return new Promise((resolve2) => { + let settled = false; + function finish(result) { + if (settled) + return; + settled = true; + unsubscribeRoot?.(); + unsubscribeThread?.(); + signal.removeEventListener("abort", finishAborted); + resolve2(result); } - }; - }); - $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base645); - $ZodStringFormat2.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64"; - }); - inst._zod.check = (payload) => { - if (isValidBase642(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url3); - $ZodStringFormat2.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64url"; + const finishAborted = () => finish({ event: "aborted" }); + const onEvent = (event) => { + if (settled) + return; + if (event.method !== "lifecycle") + return; + if (!isRootNamespace(event.params.namespace)) + return; + const lifecycle = event.params.data; + if (lifecycle?.event === "completed") + setTimeout(() => finish({ event: "completed" }), 0); + else if (lifecycle?.event === "failed") + setTimeout(() => finish({ + event: "failed", + error: lifecycle.error + }), 0); + else if (lifecycle?.event === "interrupted") + setTimeout(() => finish({ event: "interrupted" }), 0); + }; + const unsubscribeRoot = this.#rootBus.subscribe(onEvent); + const unsubscribeThread = this.#thread?.onEvent(onEvent); + if (signal.aborted) + finishAborted(); + else + signal.addEventListener("abort", finishAborted, { once: true }); }); - inst._zod.check = (payload) => { - if (isValidBase64URL2(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodE1642 = /* @__PURE__ */ $constructor2("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e1643); - $ZodStringFormat2.init(inst, def); - }); - $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => { - $ZodStringFormat2.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT3(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat2.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort - }); - }; - }); - $ZodNumber2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number4; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; + } + #resolveInterruptForResume(resume) { + const thread = this.#thread; + if (thread == null) + return null; + return resolveInterruptTargetForHeadlessResume(resume, thread.interrupts, this.#resolvedInterrupts); + } + #notifyThreadListeners() { + for (const listener of this.#threadListeners) + listener(this.#thread); + } +}; +var init_controller = __esm(() => { + init_messages9(); + init_tools4(); + init_headless_tools(); + init_store2(); + init_channel_registry(); + init_namespace2(); + init_subagents2(); + init_subgraphs4(); + init_message_metadata_tracker(); + init_lifecycle_loading_tracker(); + init_root_message_projection(); + init_submit_coordinator(); + init_tool_calls(); + init_messages(); + ROOT_NAMESPACE = []; + ROOT_PUMP_CHANNELS = [ + "values", + "checkpoints", + "lifecycle", + "input", + "messages", + "tools" + ]; +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/runtime.js +var init_runtime3 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/messages.js +var init_messages10 = __esm(() => { + init_messages9(); + init_messages8(); + init_namespace2(); + init_assembled_to_message(); + init_message_reconciliation(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/tool-calls.js +var init_tool_calls2 = __esm(() => { + init_tools4(); + init_namespace2(); + init_tool_calls(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/values.js +var init_values5 = __esm(() => { + init_messages9(); + init_namespace2(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/extension.js +var init_extension = __esm(() => { + init_namespace2(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/channel.js +var init_channel = __esm(() => { + init_namespace2(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/media.js +var init_media2 = __esm(() => { + init_media(); + init_namespace2(); + init_runtime3(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/projections/index.js +var init_projections = __esm(() => { + init_messages10(); + init_tool_calls2(); + init_values5(); + init_extension(); + init_channel(); + init_media2(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/stream/index.js +var init_stream12 = __esm(() => { + init_tools4(); + init_media(); + init_constants6(); + init_store2(); + init_channel_registry(); + init_subagents2(); + init_subgraphs4(); + init_assembled_to_message(); + init_controller(); + init_messages10(); + init_tool_calls2(); + init_values5(); + init_extension(); + init_channel(); + init_media2(); + init_projections(); +}); + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/ui/errors.js +var init_errors11 = () => {}; + +// ../../node_modules/.pnpm/@langchain+langgraph-sdk@1.9.10_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetr_ffvfyupxds3dozosgz4cj3mjf4/node_modules/@langchain/langgraph-sdk/dist/index.js +var init_dist8 = __esm(() => { + init_fetch2(); + init_base17(); + init_messages8(); + init_media(); + init_error4(); + init_constants6(); + init_headless_tools(); + init_stream10(); + init_http(); + init_websocket(); + init_agent_server(); + init_client2(); + init_client3(); + init_stream12(); + init_errors11(); +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/array.js +var require_array = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.splitWhen = exports.flatten = undefined; + function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); + } + exports.flatten = flatten; + function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } else { + result[groupIndex].push(item); } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : undefined : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; - }); - $ZodNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => { - $ZodCheckNumberFormat2.init(inst, def); - $ZodNumber2.init(inst, def); - }); - $ZodBoolean2 = /* @__PURE__ */ $constructor2("$ZodBoolean", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = boolean4; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } catch (_) {} - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodBigInt2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = bigint4; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } catch (_) {} - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => { - $ZodCheckBigIntFormat2.init(inst, def); - $ZodBigInt2.init(inst, def); - }); - $ZodSymbol2 = /* @__PURE__ */ $constructor2("$ZodSymbol", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodUndefined2 = /* @__PURE__ */ $constructor2("$ZodUndefined", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = _undefined4; - inst._zod.values = new Set([undefined]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodNull2 = /* @__PURE__ */ $constructor2("$ZodNull", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.pattern = _null4; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodAny2 = /* @__PURE__ */ $constructor2("$ZodAny", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $ZodUnknown2 = /* @__PURE__ */ $constructor2("$ZodUnknown", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload) => payload; - }); - $ZodNever2 = /* @__PURE__ */ $constructor2("$ZodNever", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; - }); - $ZodVoid2 = /* @__PURE__ */ $constructor2("$ZodVoid", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst - }); - return payload; - }; - }); - $ZodDate2 = /* @__PURE__ */ $constructor2("$ZodDate", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } catch (_err) {} + } + return result; + } + exports.splitWhen = splitWhen; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/errno.js +var require_errno = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEnoentCodeError = undefined; + function isEnoentCodeError(error90) { + return error90.code === "ENOENT"; + } + exports.isEnoentCodeError = isEnoentCodeError; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/fs.js +var require_fs = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDirentFromStats = undefined; + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + } + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + exports.createDirentFromStats = createDirentFromStats; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/path.js +var require_path = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = undefined; + var os = __require("os"); + var path2 = __require("path"); + var IS_WINDOWS_PLATFORM = os.platform() === "win32"; + var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; + var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; + var WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; + var DOS_DEVICE_PATH_RE = /^\\\\([.?])/; + var WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; + function unixify(filepath) { + return filepath.replace(/\\/g, "/"); + } + exports.unixify = unixify; + function makeAbsolute(cwd, filepath) { + return path2.resolve(cwd, filepath); + } + exports.makeAbsolute = makeAbsolute; + function removeLeadingDotSegment(entry) { + if (entry.charAt(0) === ".") { + const secondCharactery = entry.charAt(1); + if (secondCharactery === "/" || secondCharactery === "\\") { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...isDate ? { received: "Invalid Date" } : {}, - inst - }); - return payload; - }; - }); - $ZodArray2 = /* @__PURE__ */ $constructor2("$ZodArray", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload; + } + return entry; + } + exports.removeLeadingDotSegment = removeLeadingDotSegment; + exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; + function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); + } + exports.escapeWindowsPath = escapeWindowsPath; + function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2"); + } + exports.escapePosixPath = escapePosixPath; + exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; + function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath).replace(DOS_DEVICE_PATH_RE, "//$1").replace(WINDOWS_BACKSLASHES_RE, "/"); + } + exports.convertWindowsPathToPattern = convertWindowsPathToPattern; + function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); + } + exports.convertPosixPathToPattern = convertPosixPathToPattern; +}); + +// ../../node_modules/.pnpm/is-extglob@2.1.1/node_modules/is-extglob/index.js +var require_is_extglob = __commonJS((exports, module) => { + /*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + module.exports = function isExtglob(str) { + if (typeof str !== "string" || str === "") { + return false; + } + var match2; + while (match2 = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { + if (match2[2]) + return true; + str = str.slice(match2.index + match2[0].length); + } + return false; + }; +}); + +// ../../node_modules/.pnpm/is-glob@4.0.3/node_modules/is-glob/index.js +var require_is_glob = __commonJS((exports, module) => { + /*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + var isExtglob = require_is_extglob(); + var chars = { "{": "}", "(": ")", "[": "]" }; + var strictCheck = function(str) { + if (str[0] === "!") { + return true; + } + var index2 = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index2 < str.length) { + if (str[index2] === "*") { + return true; } - payload.value = Array(input.length); - const proms = []; - for (let i = 0;i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleArrayResult2(result2, payload, i))); - } else { - handleArrayResult2(result, payload, i); + if (str[index2 + 1] === "?" && /[\].+)]/.test(str[index2])) { + return true; + } + if (closeSquareIndex !== -1 && str[index2] === "[" && str[index2 + 1] !== "]") { + if (closeSquareIndex < index2) { + closeSquareIndex = str.indexOf("]", index2); + } + if (closeSquareIndex > index2) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf("\\", index2); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } } } - if (proms.length) { - return Promise.all(proms).then(() => payload); + if (closeCurlyIndex !== -1 && str[index2] === "{" && str[index2 + 1] !== "}") { + closeCurlyIndex = str.indexOf("}", index2); + if (closeCurlyIndex > index2) { + backSlashIndex = str.indexOf("\\", index2); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } } - return payload; - }; - }); - $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => { - $ZodType2.init(inst, def); - const _normalized = cached2(() => { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!(def.shape[k] instanceof $ZodType2)) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + if (closeParenIndex !== -1 && str[index2] === "(" && str[index2 + 1] === "?" && /[:!=]/.test(str[index2 + 2]) && str[index2 + 3] !== ")") { + closeParenIndex = str.indexOf(")", index2); + if (closeParenIndex > index2) { + backSlashIndex = str.indexOf("\\", index2); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } } } - const okeys = optionalKeys2(def.shape); - return { - shape: def.shape, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; - }); - defineLazy2(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = new Set); - for (const v of field.values) - propValues[key].add(v); + if (pipeIndex !== -1 && str[index2] === "(" && str[index2 + 1] !== "|") { + if (pipeIndex < index2) { + pipeIndex = str.indexOf("|", index2); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") { + closeParenIndex = str.indexOf(")", pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf("\\", pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } } } - return propValues; - }); - const generateFastpass = (shape) => { - const doc2 = new Doc2(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc2(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc2.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc2.write(`const newResult = {}`); - for (const key of normalized.keys) { - if (normalized.optionalKeys.has(key)) { - const id = ids[key]; - doc2.write(`const ${id} = ${parseStr(key)};`); - const k = esc2(key); - doc2.write(` - if (${id}.issues.length) { - if (input[${k}] === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${id}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}], - })) - ); + if (str[index2] === "\\") { + var open = str[index2 + 1]; + index2 += 2; + var close = chars[open]; + if (close) { + var n4 = str.indexOf(close, index2); + if (n4 !== -1) { + index2 = n4 + 1; } - } else if (${id}.value === undefined) { - if (${k} in input) newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; } - `); - } else { - const id = ids[key]; - doc2.write(`const ${id} = ${parseStr(key)};`); - doc2.write(` - if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${esc2(key)}, ...iss.path] : [${esc2(key)}] - })));`); - doc2.write(`newResult[${esc2(key)}] = ${id}.value`); + if (str[index2] === "!") { + return true; } - } - doc2.write(`payload.value = newResult;`); - doc2.write(`return payload;`); - const fn = doc2.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject4 = isObject3; - const jit = !globalConfig2.jitless; - const allowsEval3 = allowsEval2; - const fastEnabled = jit && allowsEval3.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject4(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); } else { - payload.value = {}; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; - if (r instanceof Promise) { - proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); - } else if (isOptional) { - handleOptionalObjectResult(r, payload, key, input); - } else { - handleObjectResult(r, payload, key); - } - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - const unrecognized = []; - const keySet = value.keySet; - const _catchall = catchall._zod; - const t = _catchall.def.type; - for (const key of Object.keys(input)) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); - } else { - handleObjectResult(r, payload, key); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); - }; - }); - $ZodUnion2 = /* @__PURE__ */ $constructor2("$ZodUnion", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); - defineLazy2(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazy2(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return; - }); - defineLazy2(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex2(p.source)).join("|")})$`); + index2++; } - return; - }); - inst._zod.parse = (payload, ctx) => { - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) - return result; - results.push(result); - } + } + return false; + }; + var relaxedCheck = function(str) { + if (str[0] === "!") { + return true; + } + var index2 = 0; + while (index2 < str.length) { + if (/[*?{}()[\]]/.test(str[index2])) { + return true; } - if (!async) - return handleUnionResults2(results, payload, inst, ctx); - return Promise.all(results).then((results2) => { - return handleUnionResults2(results2, payload, inst, ctx); - }); - }; - }); - $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUnion", (inst, def) => { - $ZodUnion2.init(inst, def); - const _super = inst._zod.parse; - defineLazy2(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = new Set; - for (const val of v) { - propValues[k].add(val); + if (str[index2] === "\\") { + var open = str[index2 + 1]; + index2 += 2; + var close = chars[open]; + if (close) { + var n4 = str.indexOf(close, index2); + if (n4 !== -1) { + index2 = n4 + 1; } } - } - return propValues; - }); - const disc = cached2(() => { - const opts = def.options; - const map2 = new Map; - for (const o of opts) { - const values2 = o._zod.propValues[def.discriminator]; - if (!values2 || values2.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values2) { - if (map2.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map2.set(v, o); + if (str[index2] === "!") { + return true; } + } else { + index2++; } - return map2; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject3(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); + } + return false; + }; + module.exports = function isGlob(str, options) { + if (typeof str !== "string" || str === "") { + return false; + } + if (isExtglob(str)) { + return true; + } + var check3 = strictCheck; + if (options && options.strict === false) { + check3 = relaxedCheck; + } + return check3(str); + }; +}); + +// ../../node_modules/.pnpm/glob-parent@5.1.2/node_modules/glob-parent/index.js +var require_glob_parent = __commonJS((exports, module) => { + var isGlob = require_is_glob(); + var pathPosixDirname = __require("path").posix.dirname; + var isWin32 = __require("os").platform() === "win32"; + var slash = "/"; + var backslash = /\\/g; + var enclosure = /[\{\[].*[\}\]]$/; + var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; + var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + if (enclosure.test(str)) { + str += slash; + } + str += "a"; + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); + return str.replace(escaped, "$1"); + }; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/pattern.js +var require_pattern = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = undefined; + var path2 = __require("path"); + var globParent = require_glob_parent(); + var micromatch = require_micromatch(); + var GLOBSTAR = "**"; + var ESCAPE_SYMBOL = "\\"; + var COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; + var REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; + var REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; + var GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; + var BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; + var DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; + function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); + } + exports.isStaticPattern = isStaticPattern; + function isDynamicPattern(pattern, options = {}) { + if (pattern === "") { + return false; + } + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; + } + exports.isDynamicPattern = isDynamicPattern; + function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf("{"); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf("}", openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); + } + function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; + } + exports.convertToPositivePattern = convertToPositivePattern; + function convertToNegativePattern(pattern) { + return "!" + pattern; + } + exports.convertToNegativePattern = convertToNegativePattern; + function isNegativePattern(pattern) { + return pattern.startsWith("!") && pattern[1] !== "("; + } + exports.isNegativePattern = isNegativePattern; + function isPositivePattern(pattern) { + return !isNegativePattern(pattern); + } + exports.isPositivePattern = isPositivePattern; + function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); + } + exports.getNegativePatterns = getNegativePatterns; + function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); + } + exports.getPositivePatterns = getPositivePatterns; + function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); + } + exports.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; + function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); + } + exports.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; + function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith("..") || pattern.startsWith("./.."); + } + exports.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; + function getBaseDirectory(pattern) { + return globParent(pattern, { flipBackslashes: false }); + } + exports.getBaseDirectory = getBaseDirectory; + function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); + } + exports.hasGlobStar = hasGlobStar; + function endsWithSlashGlobStar(pattern) { + return pattern.endsWith("/" + GLOBSTAR); + } + exports.endsWithSlashGlobStar = endsWithSlashGlobStar; + function isAffectDepthOfReadingPattern(pattern) { + const basename = path2.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); + } + exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; + function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); + } + exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; + function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + patterns.sort((a, b) => a.length - b.length); + return patterns.filter((pattern2) => pattern2 !== ""); + } + exports.expandBraceExpansion = expandBraceExpansion; + function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + if (parts.length === 0) { + parts = [pattern]; + } + if (parts[0].startsWith("/")) { + parts[0] = parts[0].slice(1); + parts.unshift(""); + } + return parts; + } + exports.getPatternParts = getPatternParts; + function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); + } + exports.makeRe = makeRe; + function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); + } + exports.convertPatternsToRe = convertPatternsToRe; + function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); + } + exports.matchAny = matchAny; + function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, "/"); + } + exports.removeDuplicateSlashes = removeDuplicateSlashes; + function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative2 = []; + for (const pattern of patterns) { + if (isAbsolute2(pattern)) { + absolute.push(pattern); + } else { + relative2.push(pattern); } - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - input, - path: [def.discriminator], - inst - }); - return payload; - }; - }); - $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left2, right2]) => { - return handleIntersectionResults2(payload, left2, right2); - }); + } + return [absolute, relative2]; + } + exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; + function isAbsolute2(pattern) { + return path2.isAbsolute(pattern); + } + exports.isAbsolute = isAbsolute2; +}); + +// ../../node_modules/.pnpm/merge2@1.4.1/node_modules/merge2/index.js +var require_merge2 = __commonJS((exports, module) => { + var Stream = __require("stream"); + var PassThrough = Stream.PassThrough; + var slice = Array.prototype.slice; + module.exports = merge22; + function merge22() { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + if (options.objectMode == null) { + options.objectMode = true; + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + const mergedStream = PassThrough(options); + function addStream() { + for (let i = 0, len = arguments.length;i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); } - return handleIntersectionResults2(payload, left, right); - }; - }); - $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => { - $ZodType2.init(inst, def); - const items = def.items; - const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type" - }); - return payload; + mergeStream(); + return this; + } + function mergeStream() { + if (merging) { + return; } - payload.value = []; - const proms = []; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - input, - inst, - origin: "array", - ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length } - }); - return payload; - } + merging = true; + let streams = streamsQueue.shift(); + if (!streams) { + process.nextTick(endStream); + return; } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) { - if (i >= optStart) - continue; - } - const result = item._zod.run({ - value: input[i], - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult2(result2, payload, i))); - } else { - handleTupleResult2(result, payload, i); - } + if (!Array.isArray(streams)) { + streams = [streams]; } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleTupleResult2(result2, payload, i))); - } else { - handleTupleResult2(result, payload, i); - } + let pipesCount = streams.length + 1; + function next() { + if (--pipesCount > 0) { + return; } + merging = false; + mergeStream(); } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject2(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - if (def.keyType._zod.values) { - const values2 = def.keyType._zod.values; - payload.value = {}; - for (const key of values2) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues2(key, result2.issues)); - } - payload.value[key] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues2(key, result.issues)); - } - payload.value[key] = result.value; - } + function pipe3(stream2) { + function onend() { + stream2.removeListener("merge2UnpipeEnd", onend); + stream2.removeListener("end", onend); + if (doPipeError) { + stream2.removeListener("error", onerror); } + next(); } - let unrecognized; - for (const key in input) { - if (!values2.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } + function onerror(err) { + mergedStream.emit("error", err); } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); + if (stream2._readableState.endEmitted) { + return next(); } - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - origin: "record", - code: "invalid_key", - issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2())), - input: key, - path: [key], - inst - }); - payload.value[keyResult.value] = keyResult.value; - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues2(key, result2.issues)); - } - payload.value[keyResult.value] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues2(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } + stream2.on("merge2UnpipeEnd", onend); + stream2.on("end", onend); + if (doPipeError) { + stream2.on("error", onerror); } + stream2.pipe(mergedStream, { end: false }); + stream2.resume(); } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; - }); - $ZodMap2 = /* @__PURE__ */ $constructor2("$ZodMap", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst - }); - return payload; + for (let i = 0;i < streams.length; i++) { + pipe3(streams[i]); } - const proms = []; - payload.value = new Map; - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { - handleMapResult2(keyResult2, valueResult2, payload, key, input, inst, ctx); - })); - } else { - handleMapResult2(keyResult, valueResult, payload, key, input, inst, ctx); - } + next(); + } + function endStream() { + merging = false; + mergedStream.emit("queueDrain"); + if (doEnd) { + mergedStream.end(); } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodSet2 = /* @__PURE__ */ $constructor2("$ZodSet", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type" - }); - return payload; + } + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on("unpipe", function(stream2) { + stream2.emit("merge2UnpipeEnd"); + }); + if (args.length) { + addStream.apply(null, args); + } + return mergedStream; + } + function pauseStreams(streams, options) { + if (!Array.isArray(streams)) { + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)); } - const proms = []; - payload.value = new Set; - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleSetResult2(result2, payload))); - } else - handleSetResult2(result, payload); + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error("Only readable stream can be merged."); } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; - }); - $ZodEnum2 = /* @__PURE__ */ $constructor2("$ZodEnum", (inst, def) => { - $ZodType2.init(inst, def); - const values2 = getEnumValues2(def.entries); - inst._zod.values = new Set(values2); - inst._zod.pattern = new RegExp(`^(${values2.filter((k) => propertyKeyTypes2.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex3(o) : o.toString()).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; + streams.pause(); + } else { + for (let i = 0, len = streams.length;i < len; i++) { + streams[i] = pauseStreams(streams[i], options); } - payload.issues.push({ - code: "invalid_value", - values: values2, - input, - inst - }); - return payload; - }; - }); - $ZodLiteral2 = /* @__PURE__ */ $constructor2("$ZodLiteral", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.values = new Set(def.values); - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex3(o) : o ? o.toString() : String(o)).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; + } + return streams; + } +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/stream.js +var require_stream = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.merge = undefined; + var merge22 = require_merge2(); + function merge3(streams) { + const mergedStream = merge22(streams); + streams.forEach((stream2) => { + stream2.once("error", (error90) => mergedStream.emit("error", error90)); + }); + mergedStream.once("close", () => propagateCloseEventToSources(streams)); + mergedStream.once("end", () => propagateCloseEventToSources(streams)); + return mergedStream; + } + exports.merge = merge3; + function propagateCloseEventToSources(streams) { + streams.forEach((stream2) => stream2.emit("close")); + } +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/string.js +var require_string2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEmpty = exports.isString = undefined; + function isString2(input) { + return typeof input === "string"; + } + exports.isString = isString2; + function isEmpty2(input) { + return input === ""; + } + exports.isEmpty = isEmpty2; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/utils/index.js +var require_utils3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = undefined; + var array3 = require_array(); + exports.array = array3; + var errno = require_errno(); + exports.errno = errno; + var fs = require_fs(); + exports.fs = fs; + var path2 = require_path(); + exports.path = path2; + var pattern = require_pattern(); + exports.pattern = pattern; + var stream2 = require_stream(); + exports.stream = stream2; + var string7 = require_string2(); + exports.string = string7; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/managers/tasks.js +var require_tasks = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = undefined; + var utils = require_utils3(); + function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, true); + return staticTasks.concat(dynamicTasks); + } + exports.generate = generate; + function processPatterns(input, settings) { + let patterns = input; + if (settings.braceExpansion) { + patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + } + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes("/") ? pattern : `**/${pattern}`); + } + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); + } + function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + if ("." in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask(".", patternsInsideCurrentDirectory, negative, dynamic)); + } else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; + } + exports.convertPatternsToTasks = convertPatternsToTasks; + function getPositivePatterns(patterns) { + return utils.pattern.getPositivePatterns(patterns); + } + exports.getPositivePatterns = getPositivePatterns; + function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils.pattern.convertToPositivePattern); + return positive; + } + exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; + function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } else { + collection[base] = [pattern]; } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst - }); - return payload; - }; - }); - $ZodFile2 = /* @__PURE__ */ $constructor2("$ZodFile", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst - }); - return payload; + return collection; + }, group); + } + exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; + function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); + } + exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; + function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils.pattern.convertToNegativePattern)) }; - }); - $ZodTransform2 = /* @__PURE__ */ $constructor2("$ZodTransform", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const _out = def.transform(payload.value, payload); - if (_ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - return payload; - }); + } + exports.convertPatternGroupToTask = convertPatternGroupToTask; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/providers/async.js +var require_async = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.read = undefined; + function read(path2, settings, callback) { + settings.fs.lstat(path2, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback(callback, lstatError); + return; } - if (_out instanceof Promise) { - throw new $ZodAsyncError2; + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback(callback, lstat); + return; } - payload.value = _out; - return payload; - }; - }); - $ZodOptional2 = /* @__PURE__ */ $constructor2("$ZodOptional", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy2(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; - }); - defineLazy2(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)})?$`) : undefined; + settings.fs.stat(path2, (statError, stat4) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback(callback, statError); + return; + } + callSuccessCallback(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat4.isSymbolicLink = () => true; + } + callSuccessCallback(callback, stat4); + }); }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - return def.innerType._zod.run(payload, ctx); + } + exports.read = read; + function callFailureCallback(callback, error90) { + callback(error90); + } + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/providers/sync.js +var require_sync = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.read = undefined; + function read(path2, settings) { + const lstat = settings.fs.lstatSync(path2); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat4 = settings.fs.statSync(path2); + if (settings.markSymbolicLink) { + stat4.isSymbolicLink = () => true; } - if (payload.value === undefined) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodNullable2 = /* @__PURE__ */ $constructor2("$ZodNullable", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy2(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)}|null)$`) : undefined; - }); - defineLazy2(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodDefault2 = /* @__PURE__ */ $constructor2("$ZodDefault", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.optin = "optional"; - defineLazy2(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - payload.value = def.defaultValue; - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleDefaultResult2(result2, def)); - } - return handleDefaultResult2(result, def); - }; - }); - $ZodPrefault2 = /* @__PURE__ */ $constructor2("$ZodPrefault", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.optin = "optional"; - defineLazy2(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; - }); - $ZodNonOptional2 = /* @__PURE__ */ $constructor2("$ZodNonOptional", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleNonOptionalResult2(result2, inst)); - } - return handleNonOptionalResult2(result, inst); - }; - }); - $ZodSuccess2 = /* @__PURE__ */ $constructor2("$ZodSuccess", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; - }); - $ZodCatch2 = /* @__PURE__ */ $constructor2("$ZodCatch", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.optin = "optional"; - defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy2(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue2(iss, ctx, config2())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }; - }); - $ZodNaN2 = /* @__PURE__ */ $constructor2("$ZodNaN", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type" - }); - return payload; - } - return payload; - }; - }); - $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "values", () => def.in._zod.values); - defineLazy2(inst._zod, "optin", () => def.in._zod.optin); - defineLazy2(inst._zod, "optout", () => def.out._zod.optout); - inst._zod.parse = (payload, ctx) => { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left2) => handlePipeResult2(left2, def, ctx)); - } - return handlePipeResult2(left, def, ctx); - }; - }); - $ZodReadonly2 = /* @__PURE__ */ $constructor2("$ZodReadonly", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy2(inst._zod, "values", () => def.innerType._zod.values); - defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult2); - } - return handleReadonlyResult2(result); - }; - }); - $ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("$ZodTemplateLiteral", (inst, def) => { - $ZodType2.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (part instanceof $ZodType2) { - if (!part._zod.pattern) { - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } else if (part === null || primitiveTypes2.has(typeof part)) { - regexParts.push(escapeRegex3(`${part}`)); - } else { - throw new Error(`Invalid template literal part: ${part}`); + return stat4; + } catch (error90) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; } + throw error90; } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "template_literal", - code: "invalid_type" - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: "template_literal", - pattern: inst._zod.pattern.source - }); - return payload; - } - return payload; - }; - }); - $ZodPromise2 = /* @__PURE__ */ $constructor2("$ZodPromise", (inst, def) => { - $ZodType2.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; - }); - $ZodLazy2 = /* @__PURE__ */ $constructor2("$ZodLazy", (inst, def) => { - $ZodType2.init(inst, def); - defineLazy2(inst._zod, "innerType", () => def.getter()); - defineLazy2(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); - defineLazy2(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); - defineLazy2(inst._zod, "optin", () => inst._zod.innerType._zod.optin); - defineLazy2(inst._zod, "optout", () => inst._zod.innerType._zod.optout); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; - }); - $ZodCustom2 = /* @__PURE__ */ $constructor2("$ZodCustom", (inst, def) => { - $ZodCheck2.init(inst, def); - $ZodType2.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r2) => handleRefineResult2(r2, payload, input, inst)); - } - handleRefineResult2(r, payload, input, inst); - return; - }; - }); + } + exports.read = read; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ar.js -function ar_default2() { - return { - localeError: error52() - }; -} -var error52 = () => { - const Sizable = { - string: { unit: "حرف", verb: "أن يحوي" }, - file: { unit: "بايت", verb: "أن يحوي" }, - array: { unit: "عنصر", verb: "أن يحوي" }, - set: { unit: "عنصر", verb: "أن يحوي" } +// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/adapters/fs.js +var require_fs2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = undefined; + var fs = __require("fs"); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync }; - function getSizing(origin) { - return Sizable[origin] ?? null; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/settings.js +var require_settings = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fs = require_fs2(); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); } - return t; - }; - const Nouns = { - regex: "مدخل", - email: "بريد إلكتروني", - url: "رابط", - emoji: "إيموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاريخ ووقت بمعيار ISO", - date: "تاريخ بمعيار ISO", - time: "وقت بمعيار ISO", - duration: "مدة بمعيار ISO", - ipv4: "عنوان IPv4", - ipv6: "عنوان IPv6", - cidrv4: "مدى عناوين بصيغة IPv4", - cidrv6: "مدى عناوين بصيغة IPv6", - base64: "نَص بترميز base64-encoded", - base64url: "نَص بترميز base64url-encoded", - json_string: "نَص على هيئة JSON", - e164: "رقم هاتف بمعيار E.164", - jwt: "JWT", - template_literal: "مدخل" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `مدخلات غير مقبولة: يفترض إدخال ${issue3.expected}، ولكن تم إدخال ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive2(issue3.values[0])}`; - return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return ` أكبر من اللازم: يفترض أن تكون ${issue3.origin ?? "القيمة"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "عنصر"}`; - return `أكبر من اللازم: يفترض أن تكون ${issue3.origin ?? "القيمة"} ${adj} ${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; - } - return `أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `نَص غير مقبول: يجب أن يبدأ بـ "${issue3.prefix}"`; - if (_issue.format === "ends_with") - return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; - if (_issue.format === "regex") - return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} غير مقبول`; - } - case "not_multiple_of": - return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue3.divisor}`; - case "unrecognized_keys": - return `معرف${issue3.keys.length > 1 ? "ات" : ""} غريب${issue3.keys.length > 1 ? "ة" : ""}: ${joinValues2(issue3.keys, "، ")}`; - case "invalid_key": - return `معرف غير مقبول في ${issue3.origin}`; - case "invalid_union": - return "مدخل غير مقبول"; - case "invalid_element": - return `مدخل غير مقبول في ${issue3.origin}`; - default: - return "مدخل غير مقبول"; + _getValue(option, value) { + return option !== null && option !== undefined ? option : value; } - }; -}; -var init_ar2 = __esm(() => { - init_util3(); + } + exports.default = Settings; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/az.js -function az_default2() { - return { - localeError: error53() - }; -} -var error53 = () => { - const Sizable = { - string: { unit: "simvol", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "element", verb: "olmalıdır" }, - set: { unit: "element", verb: "olmalıdır" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/@nodelib+fs.stat@2.0.5/node_modules/@nodelib/fs.stat/out/index.js +var require_out = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.statSync = exports.stat = exports.Settings = undefined; + var async = require_async(); + var sync = require_sync(); + var settings_1 = require_settings(); + exports.Settings = settings_1.default; + function stat4(path2, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + async.read(path2, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path2, getSettings(optionsOrSettingsOrCallback), callback); } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + exports.stat = stat4; + function statSync(path2, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path2, settings); + } + exports.statSync = statSync; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; } - return t; - }; - const Nouns = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Yanlış dəyər: gözlənilən ${issue3.expected}, daxil olan ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Yanlış dəyər: gözlənilən ${stringifyPrimitive2(issue3.values[0])}`; - return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Çox böyük: gözlənilən ${issue3.origin ?? "dəyər"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; - return `Çox böyük: gözlənilən ${issue3.origin ?? "dəyər"} ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - return `Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + return new settings_1.default(settingsOrOptions); + } +}); + +// ../../node_modules/.pnpm/queue-microtask@1.2.3/node_modules/queue-microtask/index.js +var require_queue_microtask = __commonJS((exports, module) => { + /*! queue-microtask. MIT License. Feross Aboukhadijeh */ + var promise3; + module.exports = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : global) : (cb) => (promise3 || (promise3 = Promise.resolve())).then(cb).catch((err) => setTimeout(() => { + throw err; + }, 0)); +}); + +// ../../node_modules/.pnpm/run-parallel@1.2.0/node_modules/run-parallel/index.js +var require_run_parallel = __commonJS((exports, module) => { + /*! run-parallel. MIT License. Feross Aboukhadijeh */ + module.exports = runParallel; + var queueMicrotask2 = require_queue_microtask(); + function runParallel(tasks, cb) { + let results, pending, keys; + let isSync = true; + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + function done(err) { + function end() { + if (cb) + cb(err, results); + cb = null; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; - if (_issue.format === "ends_with") - return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; - if (_issue.format === "includes") - return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; - if (_issue.format === "regex") - return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; - return `Yanlış ${Nouns[_issue.format] ?? issue3.format}`; + if (isSync) + queueMicrotask2(end); + else + end(); + } + function each(i, err, result) { + results[i] = result; + if (--pending === 0 || err) { + done(err); } - case "not_multiple_of": - return `Yanlış ədəd: ${issue3.divisor} ilə bölünə bilən olmalıdır`; - case "unrecognized_keys": - return `Tanınmayan açar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `${issue3.origin} daxilində yanlış açar`; - case "invalid_union": - return "Yanlış dəyər"; - case "invalid_element": - return `${issue3.origin} daxilində yanlış dəyər`; - default: - return `Yanlış dəyər`; } - }; -}; -var init_az2 = __esm(() => { - init_util3(); + if (!pending) { + done(null); + } else if (keys) { + keys.forEach(function(key) { + tasks[key](function(err, result) { + each(key, err, result); + }); + }); + } else { + tasks.forEach(function(task3, i) { + task3(function(err, result) { + each(i, err, result); + }); + }); + } + isSync = false; + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/be.js -function getBelarusianPlural2(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/constants.js +var require_constants3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = undefined; + var NODE_PROCESS_VERSION_PARTS = process.versions.node.split("."); + if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); } - if (lastDigit === 1) { - return one; + var MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); + var MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); + var SUPPORTED_MAJOR_VERSION = 10; + var SUPPORTED_MINOR_VERSION = 10; + var IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; + var IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/utils/fs.js +var require_fs3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDirentFromStats = undefined; + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); } - return many; -} -function be_default2() { - return { - localeError: error54() - }; -} -var error54 = () => { - const Sizable = { - string: { - unit: { - one: "сімвал", - few: "сімвалы", - many: "сімвалаў" - }, - verb: "мець" - }, - array: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў" - }, - verb: "мець" - }, - set: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў" - }, - verb: "мець" - }, - file: { - unit: { - one: "байт", - few: "байты", - many: "байтаў" - }, - verb: "мець" + exports.createDirentFromStats = createDirentFromStats; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/utils/index.js +var require_utils4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fs = undefined; + var fs = require_fs3(); + exports.fs = fs; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/common.js +var require_common = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.joinPathSegments = undefined; + function joinPathSegments(a, b, separator) { + if (a.endsWith(separator)) { + return a + b; } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; + return a + separator + b; } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "лік"; + exports.joinPathSegments = joinPathSegments; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/async.js +var require_async2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readdir = exports.readdirWithFileTypes = exports.read = undefined; + var fsStat = require_out(); + var rpl = require_run_parallel(); + var constants_1 = require_constants3(); + var utils = require_utils4(); + var common = require_common(); + function read(directory, settings, callback) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes(directory, settings, callback); + return; + } + readdir4(directory, settings, callback); + } + exports.read = read; + function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; } - case "object": { - if (Array.isArray(data)) { - return "масіў"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; } + callSuccessCallback(callback, rplEntries); + }); + }); + } + exports.readdirWithFileTypes = readdirWithFileTypes; + function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; } - } - return t; - }; - const Nouns = { - regex: "увод", - email: "email адрас", - url: "URL", - emoji: "эмодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата і час", - date: "ISO дата", - time: "ISO час", - duration: "ISO працягласць", - ipv4: "IPv4 адрас", - ipv6: "IPv6 адрас", - cidrv4: "IPv4 дыяпазон", - cidrv6: "IPv6 дыяпазон", - base64: "радок у фармаце base64", - base64url: "радок у фармаце base64url", - json_string: "JSON радок", - e164: "нумар E.164", - jwt: "JWT", - template_literal: "увод" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Няправільны ўвод: чакаўся ${issue3.expected}, атрымана ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Няправільны ўвод: чакалася ${stringifyPrimitive2(issue3.values[0])}`; - return `Няправільны варыянт: чакаўся адзін з ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - const maxValue = Number(issue3.maximum); - const unit = getBelarusianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта вялікі: чакалася, што ${issue3.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue3.maximum.toString()} ${unit}`; + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; } - return `Занадта вялікі: чакалася, што ${issue3.origin ?? "значэнне"} павінна быць ${adj}${issue3.maximum.toString()}`; + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; + } + function readdir4(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback(callback, readdirError); + return; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - const minValue = Number(issue3.minimum); - const unit = getBelarusianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта малы: чакалася, што ${issue3.origin} павінна ${sizing.verb} ${adj}${issue3.minimum.toString()} ${unit}`; + const tasks = names.map((name) => { + const path2 = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat.stat(path2, settings.fsStatSettings, (error90, stats) => { + if (error90 !== null) { + done(error90); + return; + } + const entry = { + name, + path: path2, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback(callback, rplError); + return; + } + callSuccessCallback(callback, entries); + }); + }); + } + exports.readdir = readdir4; + function callFailureCallback(callback, error90) { + callback(error90); + } + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/providers/sync.js +var require_sync2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readdir = exports.readdirWithFileTypes = exports.read = undefined; + var fsStat = require_out(); + var constants_1 = require_constants3(); + var utils = require_utils4(); + var common = require_common(); + function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir4(directory, settings); + } + exports.read = read; + function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils.fs.createDirentFromStats(entry.name, stats); + } catch (error90) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error90; + } } - return `Занадта малы: чакалася, што ${issue3.origin} павінна быць ${adj}${issue3.minimum.toString()}`; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; - if (_issue.format === "regex") - return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; - return `Няправільны ${Nouns[_issue.format] ?? issue3.format}`; + return entry; + }); + } + exports.readdirWithFileTypes = readdirWithFileTypes; + function readdir4(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; } - case "not_multiple_of": - return `Няправільны лік: павінен быць кратным ${issue3.divisor}`; - case "unrecognized_keys": - return `Нераспазнаны ${issue3.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Няправільны ключ у ${issue3.origin}`; - case "invalid_union": - return "Няправільны ўвод"; - case "invalid_element": - return `Няправільнае значэнне ў ${issue3.origin}`; - default: - return `Няправільны ўвод`; - } - }; -}; -var init_be2 = __esm(() => { - init_util3(); + return entry; + }); + } + exports.readdir = readdir4; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ca.js -function ca_default2() { - return { - localeError: error55() - }; -} -var error55 = () => { - const Sizable = { - string: { unit: "caràcters", verb: "contenir" }, - file: { unit: "bytes", verb: "contenir" }, - array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" } +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/adapters/fs.js +var require_fs4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = undefined; + var fs = __require("fs"); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync }; - function getSizing(origin) { - return Sizable[origin] ?? null; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/settings.js +var require_settings2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path2 = __require("path"); + var fsStat = require_out(); + var fs = require_fs4(); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path2.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); } - return t; - }; - const Nouns = { - regex: "entrada", - email: "adreça electrònica", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "durada ISO", - ipv4: "adreça IPv4", - ipv6: "adreça IPv6", - cidrv4: "rang IPv4", - cidrv6: "rang IPv6", - base64: "cadena codificada en base64", - base64url: "cadena codificada en base64url", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Tipus invàlid: s'esperava ${issue3.expected}, s'ha rebut ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Valor invàlid: s'esperava ${stringifyPrimitive2(issue3.values[0])}`; - return `Opció invàlida: s'esperava una de ${joinValues2(issue3.values, " o ")}`; - case "too_big": { - const adj = issue3.inclusive ? "com a màxim" : "menys de"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} contingués ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} fos ${adj} ${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? "com a mínim" : "més de"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Massa petit: s'esperava que ${issue3.origin} contingués ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Format invàlid: ha de començar amb "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Format invàlid: ha d'incloure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; - return `Format invàlid per a ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `Número invàlid: ha de ser múltiple de ${issue3.divisor}`; - case "unrecognized_keys": - return `Clau${issue3.keys.length > 1 ? "s" : ""} no reconeguda${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Clau invàlida a ${issue3.origin}`; - case "invalid_union": - return "Entrada invàlida"; - case "invalid_element": - return `Element invàlid a ${issue3.origin}`; - default: - return `Entrada invàlida`; + _getValue(option, value) { + return option !== null && option !== undefined ? option : value; } - }; -}; -var init_ca2 = __esm(() => { - init_util3(); + } + exports.default = Settings; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/cs.js -function cs_default2() { - return { - localeError: error56() - }; -} -var error56 = () => { - const Sizable = { - string: { unit: "znaků", verb: "mít" }, - file: { unit: "bajtů", verb: "mít" }, - array: { unit: "prvků", verb: "mít" }, - set: { unit: "prvků", verb: "mít" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/@nodelib+fs.scandir@2.1.5/node_modules/@nodelib/fs.scandir/out/index.js +var require_out2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Settings = exports.scandirSync = exports.scandir = undefined; + var async = require_async2(); + var sync = require_sync2(); + var settings_1 = require_settings2(); + exports.Settings = settings_1.default; + function scandir(path2, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + async.read(path2, getSettings(), optionsOrSettingsOrCallback); + return; + } + async.read(path2, getSettings(optionsOrSettingsOrCallback), callback); } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "číslo"; - } - case "string": { - return "řetězec"; - } - case "boolean": { - return "boolean"; + exports.scandir = scandir; + function scandirSync(path2, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path2, settings); + } + exports.scandirSync = scandirSync; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); + } +}); + +// ../../node_modules/.pnpm/reusify@1.1.0/node_modules/reusify/reusify.js +var require_reusify = __commonJS((exports, module) => { + function reusify(Constructor) { + var head = new Constructor; + var tail = head; + function get() { + var current = head; + if (current.next) { + head = current.next; + } else { + head = new Constructor; + tail = head; } - case "bigint": { - return "bigint"; + current.next = null; + return current; + } + function release(obj) { + tail.next = obj; + tail = obj; + } + return { + get, + release + }; + } + module.exports = reusify; +}); + +// ../../node_modules/.pnpm/fastq@1.20.1/node_modules/fastq/queue.js +var require_queue = __commonJS((exports, module) => { + var reusify = require_reusify(); + function fastqueue(context2, worker, _concurrency) { + if (typeof context2 === "function") { + _concurrency = worker; + worker = context2; + context2 = null; + } + if (!(_concurrency >= 1)) { + throw new Error("fastqueue concurrency must be equal to or greater than 1"); + } + var cache2 = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler2 = null; + var self2 = { + push: push2, + drain: noop, + saturated: noop, + pause, + paused: false, + get concurrency() { + return _concurrency; + }, + set concurrency(value) { + if (!(value >= 1)) { + throw new Error("fastqueue concurrency must be equal to or greater than 1"); + } + _concurrency = value; + if (self2.paused) + return; + for (;queueHead && _running < _concurrency; ) { + _running++; + release(); + } + }, + running, + resume, + idle, + length, + getQueue: getQueue2, + unshift, + empty: noop, + kill, + killAndDrain, + error: error90, + abort + }; + return self2; + function running() { + return _running; + } + function pause() { + self2.paused = true; + } + function length() { + var current = queueHead; + var counter = 0; + while (current) { + current = current.next; + counter++; } - case "function": { - return "funkce"; + return counter; + } + function getQueue2() { + var current = queueHead; + var tasks = []; + while (current) { + tasks.push(current.value); + current = current.next; } - case "symbol": { - return "symbol"; + return tasks; + } + function resume() { + if (!self2.paused) + return; + self2.paused = false; + if (queueHead === null) { + _running++; + release(); + return; } - case "undefined": { - return "undefined"; + for (;queueHead && _running < _concurrency; ) { + _running++; + release(); } - case "object": { - if (Array.isArray(data)) { - return "pole"; - } - if (data === null) { - return "null"; + } + function idle() { + return _running === 0 && self2.length() === 0; + } + function push2(value, done) { + var current = cache2.get(); + current.context = context2; + current.release = release; + current.value = value; + current.callback = done || noop; + current.errorHandler = errorHandler2; + if (_running >= _concurrency || self2.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self2.saturated(); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } else { + _running++; + worker.call(context2, current.value, current.worked); + } + } + function unshift(value, done) { + var current = cache2.get(); + current.context = context2; + current.release = release; + current.value = value; + current.callback = done || noop; + current.errorHandler = errorHandler2; + if (_running >= _concurrency || self2.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self2.saturated(); } + } else { + _running++; + worker.call(context2, current.value, current.worked); } } - return t; - }; - const Nouns = { - regex: "regulární výraz", - email: "e-mailová adresa", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "datum a čas ve formátu ISO", - date: "datum ve formátu ISO", - time: "čas ve formátu ISO", - duration: "doba trvání ISO", - ipv4: "IPv4 adresa", - ipv6: "IPv6 adresa", - cidrv4: "rozsah IPv4", - cidrv6: "rozsah IPv6", - base64: "řetězec zakódovaný ve formátu base64", - base64url: "řetězec zakódovaný ve formátu base64url", - json_string: "řetězec ve formátu JSON", - e164: "číslo E.164", - jwt: "JWT", - template_literal: "vstup" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Neplatný vstup: očekáváno ${issue3.expected}, obdrženo ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Neplatný vstup: očekáváno ${stringifyPrimitive2(issue3.values[0])}`; - return `Neplatná možnost: očekávána jedna z hodnot ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Hodnota je příliš velká: ${issue3.origin ?? "hodnota"} musí mít ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "prvků"}`; + function release(holder) { + if (holder) { + cache2.release(holder); + } + var next = queueHead; + if (next && _running <= _concurrency) { + if (!self2.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + queueHead = next.next; + next.next = null; + worker.call(context2, next.value, next.worked); + if (queueTail === null) { + self2.empty(); + } + } else { + _running--; } - return `Hodnota je příliš velká: ${issue3.origin ?? "hodnota"} musí být ${adj}${issue3.maximum.toString()}`; + } else if (--_running === 0) { + self2.drain(); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Hodnota je příliš malá: ${issue3.origin ?? "hodnota"} musí mít ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "prvků"}`; + } + function kill() { + queueHead = null; + queueTail = null; + self2.drain = noop; + } + function killAndDrain() { + queueHead = null; + queueTail = null; + self2.drain(); + self2.drain = noop; + } + function abort() { + var current = queueHead; + queueHead = null; + queueTail = null; + while (current) { + var next = current.next; + var callback = current.callback; + var errorHandler3 = current.errorHandler; + var val = current.value; + var context3 = current.context; + current.value = null; + current.callback = noop; + current.errorHandler = null; + if (errorHandler3) { + errorHandler3(new Error("abort"), val); } - return `Hodnota je příliš malá: ${issue3.origin ?? "hodnota"} musí být ${adj}${issue3.minimum.toString()}`; + callback.call(context3, new Error("abort")); + current.release(current); + current = next; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; - return `Neplatný formát ${Nouns[_issue.format] ?? issue3.format}`; + self2.drain = noop; + } + function error90(handler) { + errorHandler2 = handler; + } + } + function noop() {} + function Task() { + this.value = null; + this.callback = noop; + this.next = null; + this.release = noop; + this.context = null; + this.errorHandler = null; + var self2 = this; + this.worked = function worked(err, result) { + var callback = self2.callback; + var errorHandler2 = self2.errorHandler; + var val = self2.value; + self2.value = null; + self2.callback = noop; + if (self2.errorHandler) { + errorHandler2(err, val); } - case "not_multiple_of": - return `Neplatné číslo: musí být násobkem ${issue3.divisor}`; - case "unrecognized_keys": - return `Neznámé klíče: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Neplatný klíč v ${issue3.origin}`; - case "invalid_union": - return "Neplatný vstup"; - case "invalid_element": - return `Neplatná hodnota v ${issue3.origin}`; - default: - return `Neplatný vstup`; + callback.call(self2.context, err, result); + self2.release(self2); + }; + } + function queueAsPromised(context2, worker, _concurrency) { + if (typeof context2 === "function") { + _concurrency = worker; + worker = context2; + context2 = null; } - }; -}; -var init_cs2 = __esm(() => { - init_util3(); + function asyncWrapper(arg, cb) { + worker.call(this, arg).then(function(res) { + cb(null, res); + }, cb); + } + var queue2 = fastqueue(context2, asyncWrapper, _concurrency); + var pushCb = queue2.push; + var unshiftCb = queue2.unshift; + queue2.push = push2; + queue2.unshift = unshift; + queue2.drained = drained; + return queue2; + function push2(value) { + var p = new Promise(function(resolve2, reject) { + pushCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve2(result); + }); + }); + p.catch(noop); + return p; + } + function unshift(value) { + var p = new Promise(function(resolve2, reject) { + unshiftCb(value, function(err, result) { + if (err) { + reject(err); + return; + } + resolve2(result); + }); + }); + p.catch(noop); + return p; + } + function drained() { + var p = new Promise(function(resolve2) { + process.nextTick(function() { + if (queue2.idle()) { + resolve2(); + } else { + var previousDrain = queue2.drain; + queue2.drain = function() { + if (typeof previousDrain === "function") + previousDrain(); + resolve2(); + queue2.drain = previousDrain; + }; + } + }); + }); + return p; + } + } + module.exports = fastqueue; + module.exports.promise = queueAsPromised; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/de.js -function de_default2() { - return { - localeError: error57() - }; -} -var error57 = () => { - const Sizable = { - string: { unit: "Zeichen", verb: "zu haben" }, - file: { unit: "Bytes", verb: "zu haben" }, - array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/common.js +var require_common2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.joinPathSegments = exports.replacePathSegmentSeparator = exports.isAppliedFilter = exports.isFatalError = undefined; + function isFatalError(settings, error90) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error90); } - const parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "Zahl"; + exports.isFatalError = isFatalError; + function isAppliedFilter(filter, value) { + return filter === null || filter(value); + } + exports.isAppliedFilter = isAppliedFilter; + function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); + } + exports.replacePathSegmentSeparator = replacePathSegmentSeparator; + function joinPathSegments(a, b, separator) { + if (a === "") { + return b; + } + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; + } + exports.joinPathSegments = joinPathSegments; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/reader.js +var require_reader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var common = require_common2(); + + class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } + } + exports.default = Reader; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/async.js +var require_async3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var events_1 = __require("events"); + var fsScandir = require_out2(); + var fastq = require_queue(); + var common = require_common2(); + var reader_1 = require_reader(); + + class AsyncReader extends reader_1.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir.scandir; + this._emitter = new events_1.EventEmitter; + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit("end"); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error("The reader is already destroyed"); } - case "object": { - if (Array.isArray(data)) { - return "Array"; + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on("entry", callback); + } + onError(callback) { + this._emitter.once("error", callback); + } + onEnd(callback) { + this._emitter.once("end", callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error90) => { + if (error90 !== null) { + this._handleError(error90); } - if (data === null) { - return "null"; + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error90, entries) => { + if (error90 !== null) { + done(error90, undefined); + return; } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + for (const entry of entries) { + this._handleEntry(entry, item.base); } + done(null, undefined); + }); + } + _handleError(error90) { + if (this._isDestroyed || !common.isFatalError(this._settings, error90)) { + return; } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit("error", error90); } - return t; - }; - const Nouns = { - regex: "Eingabe", - email: "E-Mail-Adresse", - url: "URL", - emoji: "Emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-Datum und -Uhrzeit", - date: "ISO-Datum", - time: "ISO-Uhrzeit", - duration: "ISO-Dauer", - ipv4: "IPv4-Adresse", - ipv6: "IPv6-Adresse", - cidrv4: "IPv4-Bereich", - cidrv6: "IPv6-Bereich", - base64: "Base64-codierter String", - base64url: "Base64-URL-codierter String", - json_string: "JSON-String", - e164: "E.164-Nummer", - jwt: "JWT", - template_literal: "Eingabe" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Ungültige Eingabe: erwartet ${issue3.expected}, erhalten ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Ungültige Eingabe: erwartet ${stringifyPrimitive2(issue3.values[0])}`; - return `Ungültige Option: erwartet eine von ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Zu groß: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; - return `Zu groß: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ist`; + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`; - } - return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`; + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; - if (_issue.format === "ends_with") - return `Ungültiger String: muss mit "${_issue.suffix}" enden`; - if (_issue.format === "includes") - return `Ungültiger String: muss "${_issue.includes}" enthalten`; - if (_issue.format === "regex") - return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; - return `Ungültig: ${Nouns[_issue.format] ?? issue3.format}`; + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } - case "not_multiple_of": - return `Ungültige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`; - case "unrecognized_keys": - return `${issue3.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Ungültiger Schlüssel in ${issue3.origin}`; - case "invalid_union": - return "Ungültige Eingabe"; - case "invalid_element": - return `Ungültiger Wert in ${issue3.origin}`; - default: - return `Ungültige Eingabe`; } - }; -}; -var init_de2 = __esm(() => { - init_util3(); + _emitEntry(entry) { + this._emitter.emit("entry", entry); + } + } + exports.default = AsyncReader; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js -function en_default3() { - return { - localeError: error58() - }; -} -var parsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/async.js +var require_async4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var async_1 = require_async3(); + + class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._storage = []; } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + read(callback) { + this._reader.onError((error90) => { + callFailureCallback(callback, error90); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); } } - return t; -}, error58 = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; + exports.default = AsyncProvider; + function callFailureCallback(callback, error90) { + callback(error90); } - const Nouns = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Invalid input: expected ${issue3.expected}, received ${parsedType2(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; - return `Invalid option: expected one of ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Too big: expected ${issue3.origin ?? "value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue3.origin ?? "value"} to be ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; + function callSuccessCallback(callback, entries) { + callback(null, entries); + } +}); + +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/stream.js +var require_stream2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1 = __require("stream"); + var async_1 = require_async3(); + + class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1.default(this._root, this._settings); + this._stream = new stream_1.Readable({ + objectMode: true, + read: () => {}, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue3.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue3.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue3.origin}`; - default: - return `Invalid input`; + }); } - }; -}; -var init_en3 = __esm(() => { - init_util3(); + read() { + this._reader.onError((error90) => { + this._stream.emit("error", error90); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } + } + exports.default = StreamProvider; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/eo.js -function eo_default2() { - return { - localeError: error59() - }; -} -var parsedType3 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombro"; +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/readers/sync.js +var require_sync3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsScandir = require_out2(); + var common = require_common2(); + var reader_1 = require_reader(); + + class SyncReader extends reader_1.default { + constructor() { + super(...arguments); + this._scandir = fsScandir.scandirSync; + this._storage = []; + this._queue = new Set; } - case "object": { - if (Array.isArray(data)) { - return "tabelo"; + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); } - if (data === null) { - return "senvalora"; + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } catch (error90) { + this._handleError(error90); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } + _handleError(error90) { + if (!common.isFatalError(this._settings, error90)) { + return; } + throw error90; } - } - return t; -}, error59 = () => { - const Sizable = { - string: { unit: "karaktrojn", verb: "havi" }, - file: { unit: "bajtojn", verb: "havi" }, - array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "enigo", - email: "retadreso", - url: "URL", - emoji: "emoĝio", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datotempo", - date: "ISO-dato", - time: "ISO-tempo", - duration: "ISO-daŭro", - ipv4: "IPv4-adreso", - ipv6: "IPv6-adreso", - cidrv4: "IPv4-rango", - cidrv6: "IPv6-rango", - base64: "64-ume kodita karaktraro", - base64url: "URL-64-ume kodita karaktraro", - json_string: "JSON-karaktraro", - e164: "E.164-nombro", - jwt: "JWT", - template_literal: "enigo" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Nevalida enigo: atendiĝis ${issue3.expected}, riceviĝis ${parsedType3(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Nevalida enigo: atendiĝis ${stringifyPrimitive2(issue3.values[0])}`; - return `Nevalida opcio: atendiĝis unu el ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Tro granda: atendiĝis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementojn"}`; - return `Tro granda: atendiĝis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()}`; + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Tro malgranda: atendiĝis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Tro malgranda: atendiĝis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`; + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; - return `Nevalida ${Nouns[_issue.format] ?? issue3.format}`; + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); } - case "not_multiple_of": - return `Nevalida nombro: devas esti oblo de ${issue3.divisor}`; - case "unrecognized_keys": - return `Nekonata${issue3.keys.length > 1 ? "j" : ""} ŝlosilo${issue3.keys.length > 1 ? "j" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Nevalida ŝlosilo en ${issue3.origin}`; - case "invalid_union": - return "Nevalida enigo"; - case "invalid_element": - return `Nevalida valoro en ${issue3.origin}`; - default: - return `Nevalida enigo`; } - }; -}; -var init_eo2 = __esm(() => { - init_util3(); + _pushToStorage(entry) { + this._storage.push(entry); + } + } + exports.default = SyncReader; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/es.js -function es_default2() { - return { - localeError: error60() - }; -} -var error60 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "tener" }, - file: { unit: "bytes", verb: "tener" }, - array: { unit: "elementos", verb: "tener" }, - set: { unit: "elementos", verb: "tener" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/providers/sync.js +var require_sync4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var sync_1 = require_sync3(); + + class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "número"; - } - case "object": { - if (Array.isArray(data)) { - return "arreglo"; - } - if (data === null) { - return "nulo"; - } - if (Object.getPrototypeOf(data) !== Object.prototype) { - return data.constructor.name; - } + exports.default = SyncProvider; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/settings.js +var require_settings3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path2 = __require("path"); + var fsScandir = require_out2(); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path2.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== undefined ? option : value; + } + } + exports.default = Settings; +}); + +// ../../node_modules/.pnpm/@nodelib+fs.walk@1.2.8/node_modules/@nodelib/fs.walk/out/index.js +var require_out3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Settings = exports.walkStream = exports.walkSync = exports.walk = undefined; + var async_1 = require_async4(); + var stream_1 = require_stream2(); + var sync_1 = require_sync4(); + var settings_1 = require_settings3(); + exports.Settings = settings_1.default; + function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === "function") { + new async_1.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); + } + exports.walk = walk; + function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1.default(directory, settings); + return provider.read(); + } + exports.walkSync = walkSync; + function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1.default(directory, settings); + return provider.read(); + } + exports.walkStream = walkStream; + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1.default) { + return settingsOrOptions; + } + return new settings_1.default(settingsOrOptions); + } +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/reader.js +var require_reader2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path2 = __require("path"); + var fsStat = require_out(); + var utils = require_utils3(); + + class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path2.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; } + return entry; } - return t; - }; - const Nouns = { - regex: "entrada", - email: "dirección de correo electrónico", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "fecha y hora ISO", - date: "fecha ISO", - time: "hora ISO", - duration: "duración ISO", - ipv4: "dirección IPv4", - ipv6: "dirección IPv6", - cidrv4: "rango IPv4", - cidrv6: "rango IPv6", - base64: "cadena codificada en base64", - base64url: "URL codificada en base64", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Entrada inválida: se esperaba ${issue3.expected}, recibido ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Entrada inválida: se esperaba ${stringifyPrimitive2(issue3.values[0])}`; - return `Opción inválida: se esperaba una de ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Demasiado grande: se esperaba que ${issue3.origin ?? "valor"} fuera ${adj}${issue3.maximum.toString()}`; + _isFatalError(error90) { + return !utils.errno.isEnoentCodeError(error90) && !this._settings.suppressErrors; + } + } + exports.default = Reader; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/stream.js +var require_stream3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1 = __require("stream"); + var fsStat = require_out(); + var fsWalk = require_out3(); + var reader_1 = require_reader2(); + + class ReaderStream extends reader_1.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk.walkStream; + this._stat = fsStat.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream2 = new stream_1.PassThrough({ objectMode: true }); + stream2._write = (index2, _enc, done) => { + return this._getEntry(filepaths[index2], patterns[index2], options).then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream2.push(entry); + } + if (index2 === filepaths.length - 1) { + stream2.end(); + } + done(); + }).catch(done); + }; + for (let i = 0;i < filepaths.length; i++) { + stream2.write(i); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Demasiado pequeño: se esperaba que ${issue3.origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + return stream2; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath).then((stats) => this._makeEntry(stats, pattern)).catch((error90) => { + if (options.errorFilter(error90)) { + return null; } - return `Demasiado pequeño: se esperaba que ${issue3.origin} fuera ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cadena inválida: debe terminar en "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cadena inválida: debe incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; - return `Inválido ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `Número inválido: debe ser múltiplo de ${issue3.divisor}`; - case "unrecognized_keys": - return `Llave${issue3.keys.length > 1 ? "s" : ""} desconocida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Llave inválida en ${issue3.origin}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido en ${issue3.origin}`; - default: - return `Entrada inválida`; + throw error90; + }); } - }; -}; -var init_es2 = __esm(() => { - init_util3(); + _getStat(filepath) { + return new Promise((resolve2, reject) => { + this._stat(filepath, this._fsStatSettings, (error90, stats) => { + return error90 === null ? resolve2(stats) : reject(error90); + }); + }); + } + } + exports.default = ReaderStream; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fa.js -function fa_default2() { - return { - localeError: error61() - }; -} -var error61 = () => { - const Sizable = { - string: { unit: "کاراکتر", verb: "داشته باشد" }, - file: { unit: "بایت", verb: "داشته باشد" }, - array: { unit: "آیتم", verb: "داشته باشد" }, - set: { unit: "آیتم", verb: "داشته باشد" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/async.js +var require_async5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsWalk = require_out3(); + var reader_1 = require_reader2(); + var stream_1 = require_stream3(); + + class ReaderAsync extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve2, reject) => { + this._walkAsync(root, options, (error90, entries) => { + if (error90 === null) { + resolve2(entries); + } else { + reject(error90); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream2 = this._readerStream.static(patterns, options); + return new Promise((resolve2, reject) => { + stream2.once("error", reject); + stream2.on("data", (entry) => entries.push(entry)); + stream2.once("end", () => resolve2(entries)); + }); + } } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "عدد"; + exports.default = ReaderAsync; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/matchers/matcher.js +var require_matcher = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils3(); + + class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); } - case "object": { - if (Array.isArray(data)) { - return "آرایه"; + } + _getPatternSegments(pattern) { + const parts = utils.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; } - if (data === null) { - return "null"; + return { + dynamic: true, + pattern: part, + patternRe: utils.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils.array.splitWhen(segments, (segment) => segment.dynamic && utils.pattern.hasGlobStar(segment.pattern)); + } + } + exports.default = Matcher; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/matchers/partial.js +var require_partial = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var matcher_1 = require_matcher(); + + class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split("/"); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + if (!pattern.complete && levels > section.length) { + return true; } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + const match2 = parts.every((part, index2) => { + const segment = pattern.segments[index2]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match2) { + return true; } } + return false; } - return t; - }; - const Nouns = { - regex: "ورودی", - email: "آدرس ایمیل", - url: "URL", - emoji: "ایموجی", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاریخ و زمان ایزو", - date: "تاریخ ایزو", - time: "زمان ایزو", - duration: "مدت زمان ایزو", - ipv4: "IPv4 آدرس", - ipv6: "IPv6 آدرس", - cidrv4: "IPv4 دامنه", - cidrv6: "IPv6 دامنه", - base64: "base64-encoded رشته", - base64url: "base64url-encoded رشته", - json_string: "JSON رشته", - e164: "E.164 عدد", - jwt: "JWT", - template_literal: "ورودی" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `ورودی نامعتبر: می‌بایست ${issue3.expected} می‌بود، ${parsedType4(issue3.input)} دریافت شد`; - case "invalid_value": - if (issue3.values.length === 1) { - return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive2(issue3.values[0])} می‌بود`; - } - return `گزینه نامعتبر: می‌بایست یکی از ${joinValues2(issue3.values, "|")} می‌بود`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `خیلی بزرگ: ${issue3.origin ?? "مقدار"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; - } - return `خیلی بزرگ: ${issue3.origin ?? "مقدار"} باید ${adj}${issue3.maximum.toString()} باشد`; + } + exports.default = PartialMatcher; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/deep.js +var require_deep = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils3(); + var partial_1 = require_partial(); + + class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils.pattern.isAffectDepthOfReadingPattern); + return utils.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} باشد`; - } - return `خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} باشد`; + if (this._isSkippedSymbolicLink(entry)) { + return false; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; - } - if (_issue.format === "ends_with") { - return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; - } - if (_issue.format === "includes") { - return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; - } - if (_issue.format === "regex") { - return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; - } - return `${Nouns[_issue.format] ?? issue3.format} نامعتبر`; + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; } - case "not_multiple_of": - return `عدد نامعتبر: باید مضرب ${issue3.divisor} باشد`; - case "unrecognized_keys": - return `کلید${issue3.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `کلید ناشناس در ${issue3.origin}`; - case "invalid_union": - return `ورودی نامعتبر`; - case "invalid_element": - return `مقدار نامعتبر در ${issue3.origin}`; - default: - return `ورودی نامعتبر`; + return this._isSkippedByNegativePatterns(filepath, negativeRe); } - }; -}; -var init_fa2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fi.js -function fi_default2() { - return { - localeError: error62() - }; -} -var error62 = () => { - const Sizable = { - string: { unit: "merkkiä", subject: "merkkijonon" }, - file: { unit: "tavua", subject: "tiedoston" }, - array: { unit: "alkiota", subject: "listan" }, - set: { unit: "alkiota", subject: "joukon" }, - number: { unit: "", subject: "luvun" }, - bigint: { unit: "", subject: "suuren kokonaisluvun" }, - int: { unit: "", subject: "kokonaisluvun" }, - date: { unit: "", subject: "päivämäärän" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; + _isSkippedByDeep(basePath, entryPath) { + if (this._settings.deep === Infinity) { + return false; } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split("/").length; + if (basePath === "") { + return entryPathDepth; } + const basePathDepth = basePath.split("/").length; + return entryPathDepth - basePathDepth; } - return t; - }; - const Nouns = { - regex: "säännöllinen lauseke", - email: "sähköpostiosoite", - url: "URL-osoite", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-aikaleima", - date: "ISO-päivämäärä", - time: "ISO-aika", - duration: "ISO-kesto", - ipv4: "IPv4-osoite", - ipv6: "IPv6-osoite", - cidrv4: "IPv4-alue", - cidrv6: "IPv6-alue", - base64: "base64-koodattu merkkijono", - base64url: "base64url-koodattu merkkijono", - json_string: "JSON-merkkijono", - e164: "E.164-luku", - jwt: "JWT", - template_literal: "templaattimerkkijono" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Virheellinen tyyppi: odotettiin ${issue3.expected}, oli ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Virheellinen syöte: täytyy olla ${stringifyPrimitive2(issue3.values[0])}`; - return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim(); + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils.pattern.matchAny(entryPath, patternsRe); + } + } + exports.default = DeepFilter; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/entry.js +var require_entry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils3(); + + class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map; + } + getFilter(positive, negative) { + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) } - return `Liian suuri: arvon täytyy olla ${adj}${issue3.maximum.toString()}`; + }; + return (entry) => this._filter(entry, patterns); + } + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim(); - } - return `Liian pieni: arvon täytyy olla ${adj}${issue3.minimum.toString()}`; + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; - if (_issue.format === "regex") { - return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; - } - return `Virheellinen ${Nouns[_issue.format] ?? issue3.format}`; + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); + if (this._settings.unique && isMatched) { + this._createIndexRecord(filepath); } - case "not_multiple_of": - return `Virheellinen luku: täytyy olla luvun ${issue3.divisor} monikerta`; - case "unrecognized_keys": - return `${issue3.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return "Virheellinen avain tietueessa"; - case "invalid_union": - return "Virheellinen unioni"; - case "invalid_element": - return "Virheellinen arvo joukossa"; - default: - return `Virheellinen syöte`; + return isMatched; } - }; -}; -var init_fi2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr.js -function fr_default2() { - return { - localeError: error63() - }; -} -var error63 = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombre"; + _isDuplicateEntry(filepath) { + return this.index.has(filepath); + } + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { + return false; } - case "object": { - if (Array.isArray(data)) { - return "tableau"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { + return false; + } + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; } + return true; } - return t; - }; - const Nouns = { - regex: "entrée", - email: "adresse e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date et heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Entrée invalide : ${issue3.expected} attendu, ${parsedType4(issue3.input)} reçu`; - case "invalid_value": - if (issue3.values.length === 1) - return `Entrée invalide : ${stringifyPrimitive2(issue3.values[0])} attendu`; - return `Option invalide : une valeur parmi ${joinValues2(issue3.values, "|")} attendue`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Trop grand : ${issue3.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; - return `Trop grand : ${issue3.origin ?? "valeur"} doit être ${adj}${issue3.maximum.toString()}`; + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Trop petit : ${issue3.origin} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : ${issue3.origin} doit être ${adj}${issue3.minimum.toString()}`; + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} invalide`; + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + if (!isMatched && isDirectory) { + return utils.pattern.matchAny(filepath + "/", patternsRe); } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue3.divisor}`; - case "unrecognized_keys": - return `Clé${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue3.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue3.origin}`; - default: - return `Entrée invalide`; + return isMatched; } - }; -}; -var init_fr2 = __esm(() => { - init_util3(); + } + exports.default = EntryFilter; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/fr-CA.js -function fr_CA_default2() { - return { - localeError: error64() - }; -} -var error64 = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/filters/error.js +var require_error = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils3(); + + class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error90) => this._isNonFatalError(error90); + } + _isNonFatalError(error90) { + return utils.errno.isEnoentCodeError(error90) || this._settings.suppressErrors; + } } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + exports.default = ErrorFilter; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/transformers/entry.js +var require_entry2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var utils = require_utils3(); + + class EntryTransformer { + constructor(_settings) { + this._settings = _settings; } - return t; - }; - const Nouns = { - regex: "entrée", - email: "adresse courriel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date-heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Entrée invalide : attendu ${issue3.expected}, reçu ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Entrée invalide : attendu ${stringifyPrimitive2(issue3.values[0])}`; - return `Option invalide : attendu l'une des valeurs suivantes ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "≤" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`; - return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} soit ${adj}${issue3.maximum.toString()}`; + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils.path.unixify(filepath); } - case "too_small": { - const adj = issue3.inclusive ? "≥" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`; + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += "/"; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} invalide`; + if (!this._settings.objectMode) { + return filepath; } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue3.divisor}`; - case "unrecognized_keys": - return `Clé${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue3.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue3.origin}`; - default: - return `Entrée invalide`; + return Object.assign(Object.assign({}, entry), { path: filepath }); } - }; -}; -var init_fr_CA2 = __esm(() => { - init_util3(); + } + exports.default = EntryTransformer; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/he.js -function he_default2() { - return { - localeError: error65() - }; -} -var error65 = () => { - const Sizable = { - string: { unit: "אותיות", verb: "לכלול" }, - file: { unit: "בייטים", verb: "לכלול" }, - array: { unit: "פריטים", verb: "לכלול" }, - set: { unit: "פריטים", verb: "לכלול" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/provider.js +var require_provider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var path2 = __require("path"); + var deep_1 = require_deep(); + var entry_1 = require_entry(); + var error_1 = require_error(); + var entry_2 = require_entry2(); + + class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task3) { + return path2.resolve(this._settings.cwd, task3.base); + } + _getReaderOptions(task3) { + const basePath = task3.base === "." ? "" : task3.base; + return { + basePath, + pathSegmentSeparator: "/", + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task3.positive, task3.negative), + entryFilter: this.entryFilter.getFilter(task3.positive, task3.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + exports.default = Provider; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/async.js +var require_async6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var async_1 = require_async5(); + var provider_1 = require_provider(); + + class ProviderAsync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new async_1.default(this._settings); } - return t; - }; - const Nouns = { - regex: "קלט", - email: "כתובת אימייל", - url: "כתובת רשת", - emoji: "אימוג'י", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "תאריך וזמן ISO", - date: "תאריך ISO", - time: "זמן ISO", - duration: "משך זמן ISO", - ipv4: "כתובת IPv4", - ipv6: "כתובת IPv6", - cidrv4: "טווח IPv4", - cidrv6: "טווח IPv6", - base64: "מחרוזת בבסיס 64", - base64url: "מחרוזת בבסיס 64 לכתובות רשת", - json_string: "מחרוזת JSON", - e164: "מספר E.164", - jwt: "JWT", - template_literal: "קלט" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `קלט לא תקין: צריך ${issue3.expected}, התקבל ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `קלט לא תקין: צריך ${stringifyPrimitive2(issue3.values[0])}`; - return `קלט לא תקין: צריך אחת מהאפשרויות ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `גדול מדי: ${issue3.origin ?? "value"} צריך להיות ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `גדול מדי: ${issue3.origin ?? "value"} צריך להיות ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `מחרוזת לא תקינה: חייבת להתחיל ב"${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `מחרוזת לא תקינה: חייבת להסתיים ב "${_issue.suffix}"`; - if (_issue.format === "includes") - return `מחרוזת לא תקינה: חייבת לכלול "${_issue.includes}"`; - if (_issue.format === "regex") - return `מחרוזת לא תקינה: חייבת להתאים לתבנית ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} לא תקין`; + async read(task3) { + const root = this._getRootDirectory(task3); + const options = this._getReaderOptions(task3); + const entries = await this.api(root, task3, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task3, options) { + if (task3.dynamic) { + return this._reader.dynamic(root, options); } - case "not_multiple_of": - return `מספר לא תקין: חייב להיות מכפלה של ${issue3.divisor}`; - case "unrecognized_keys": - return `מפתח${issue3.keys.length > 1 ? "ות" : ""} לא מזוה${issue3.keys.length > 1 ? "ים" : "ה"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `מפתח לא תקין ב${issue3.origin}`; - case "invalid_union": - return "קלט לא תקין"; - case "invalid_element": - return `ערך לא תקין ב${issue3.origin}`; - default: - return `קלט לא תקין`; + return this._reader.static(task3.patterns, options); } - }; -}; -var init_he2 = __esm(() => { - init_util3(); + } + exports.default = ProviderAsync; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/hu.js -function hu_default2() { - return { - localeError: error66() - }; -} -var error66 = () => { - const Sizable = { - string: { unit: "karakter", verb: "legyen" }, - file: { unit: "byte", verb: "legyen" }, - array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "szám"; +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/stream.js +var require_stream4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var stream_1 = __require("stream"); + var stream_2 = require_stream3(); + var provider_1 = require_provider(); + + class ProviderStream extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task3) { + const root = this._getRootDirectory(task3); + const options = this._getReaderOptions(task3); + const source = this.api(root, task3, options); + const destination = new stream_1.Readable({ objectMode: true, read: () => {} }); + source.once("error", (error90) => destination.emit("error", error90)).on("data", (entry) => destination.emit("data", options.transform(entry))).once("end", () => destination.emit("end")); + destination.once("close", () => source.destroy()); + return destination; + } + api(root, task3, options) { + if (task3.dynamic) { + return this._reader.dynamic(root, options); } - case "object": { - if (Array.isArray(data)) { - return "tömb"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + return this._reader.static(task3.patterns, options); + } + } + exports.default = ProviderStream; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/readers/sync.js +var require_sync5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var fsStat = require_out(); + var fsWalk = require_out3(); + var reader_1 = require_reader2(); + + class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; } + entries.push(entry); } + return entries; } - return t; - }; - const Nouns = { - regex: "bemenet", - email: "email cím", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO időbélyeg", - date: "ISO dátum", - time: "ISO idő", - duration: "ISO időintervallum", - ipv4: "IPv4 cím", - ipv6: "IPv6 cím", - cidrv4: "IPv4 tartomány", - cidrv6: "IPv6 tartomány", - base64: "base64-kódolt string", - base64url: "base64url-kódolt string", - json_string: "JSON string", - e164: "E.164 szám", - jwt: "JWT", - template_literal: "bemenet" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Érvénytelen bemenet: a várt érték ${issue3.expected}, a kapott érték ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive2(issue3.values[0])}`; - return `Érvénytelen opció: valamelyik érték várt ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Túl nagy: ${issue3.origin ?? "érték"} mérete túl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elem"}`; - return `Túl nagy: a bemeneti érték ${issue3.origin ?? "érték"} túl nagy: ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Túl kicsi: a bemeneti érték ${issue3.origin} mérete túl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } catch (error90) { + if (options.errorFilter(error90)) { + return null; } - return `Túl kicsi: a bemeneti érték ${issue3.origin} túl kicsi ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; - if (_issue.format === "ends_with") - return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; - if (_issue.format === "includes") - return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; - if (_issue.format === "regex") - return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; - return `Érvénytelen ${Nouns[_issue.format] ?? issue3.format}`; + throw error90; } - case "not_multiple_of": - return `Érvénytelen szám: ${issue3.divisor} többszörösének kell lennie`; - case "unrecognized_keys": - return `Ismeretlen kulcs${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Érvénytelen kulcs ${issue3.origin}`; - case "invalid_union": - return "Érvénytelen bemenet"; - case "invalid_element": - return `Érvénytelen érték: ${issue3.origin}`; - default: - return `Érvénytelen bemenet`; } - }; -}; -var init_hu2 = __esm(() => { - init_util3(); + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } + } + exports.default = ReaderSync; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/id.js -function id_default2() { - return { - localeError: error67() - }; -} -var error67 = () => { - const Sizable = { - string: { unit: "karakter", verb: "memiliki" }, - file: { unit: "byte", verb: "memiliki" }, - array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/providers/sync.js +var require_sync6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var sync_1 = require_sync5(); + var provider_1 = require_provider(); + + class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1.default(this._settings); + } + read(task3) { + const root = this._getRootDirectory(task3); + const options = this._getReaderOptions(task3); + const entries = this.api(root, task3, options); + return entries.map(options.transform); + } + api(root, task3, options) { + if (task3.dynamic) { + return this._reader.dynamic(root, options); } + return this._reader.static(task3.patterns, options); } - return t; - }; - const Nouns = { - regex: "input", - email: "alamat email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tanggal dan waktu format ISO", - date: "tanggal format ISO", - time: "jam format ISO", - duration: "durasi format ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "rentang alamat IPv4", - cidrv6: "rentang alamat IPv6", - base64: "string dengan enkode base64", - base64url: "string dengan enkode base64url", - json_string: "string JSON", - e164: "angka E.164", - jwt: "JWT", - template_literal: "input" + } + exports.default = ProviderSync; +}); + +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/settings.js +var require_settings4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = undefined; + var fs = __require("fs"); + var os = __require("os"); + var CPU_COUNT = Math.max(os.cpus().length, 1); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Input tidak valid: diharapkan ${issue3.expected}, diterima ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Input tidak valid: diharapkan ${stringifyPrimitive2(issue3.values[0])}`; - return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} menjadi ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`; + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak valid: harus menyertakan "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak valid: harus sesuai pola ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} tidak valid`; + if (this.stats) { + this.objectMode = true; } - case "not_multiple_of": - return `Angka tidak valid: harus kelipatan dari ${issue3.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak valid di ${issue3.origin}`; - case "invalid_union": - return "Input tidak valid"; - case "invalid_element": - return `Nilai tidak valid di ${issue3.origin}`; - default: - return `Input tidak valid`; + this.ignore = [].concat(this.ignore); } - }; -}; -var init_id3 = __esm(() => { - init_util3(); + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + } + exports.default = Settings; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/it.js -function it_default2() { - return { - localeError: error68() - }; -} -var error68 = () => { - const Sizable = { - string: { unit: "caratteri", verb: "avere" }, - file: { unit: "byte", verb: "avere" }, - array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/fast-glob@3.3.3/node_modules/fast-glob/out/index.js +var require_out4 = __commonJS((exports, module) => { + var taskManager = require_tasks(); + var async_1 = require_async6(); + var stream_1 = require_stream4(); + var sync_1 = require_sync6(); + var settings_1 = require_settings4(); + var utils = require_utils3(); + async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "numero"; - } - case "object": { - if (Array.isArray(data)) { - return "vettore"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + (function(FastGlob2) { + FastGlob2.glob = FastGlob2; + FastGlob2.globSync = sync; + FastGlob2.globStream = stream2; + FastGlob2.async = FastGlob2; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); } - return t; - }; - const Nouns = { - regex: "input", - email: "indirizzo email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e ora ISO", - date: "data ISO", - time: "ora ISO", - duration: "durata ISO", - ipv4: "indirizzo IPv4", - ipv6: "indirizzo IPv6", - cidrv4: "intervallo IPv4", - cidrv6: "intervallo IPv6", - base64: "stringa codificata in base64", - base64url: "URL codificata in base64", - json_string: "stringa JSON", - e164: "numero E.164", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Input non valido: atteso ${issue3.expected}, ricevuto ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Input non valido: atteso ${stringifyPrimitive2(issue3.values[0])}`; - return `Opzione non valida: atteso uno tra ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Troppo grande: ${issue3.origin ?? "valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementi"}`; - return `Troppo grande: ${issue3.origin ?? "valore"} deve essere ${adj}${issue3.maximum.toString()}`; + FastGlob2.sync = sync; + function stream2(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + return utils.stream.merge(works); + } + FastGlob2.stream = stream2; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob2.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob2.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob2.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob2.convertPathToPattern = convertPathToPattern; + let posix; + (function(posix2) { + function escapePath2(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`; + posix2.escapePath = escapePath2; + function convertPathToPattern2(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Stringa non valida: deve terminare con "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Stringa non valida: deve includere "${_issue.includes}"`; - if (_issue.format === "regex") - return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; + posix2.convertPathToPattern = convertPathToPattern2; + })(posix = FastGlob2.posix || (FastGlob2.posix = {})); + let win32; + (function(win322) { + function escapePath2(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); } - case "not_multiple_of": - return `Numero non valido: deve essere un multiplo di ${issue3.divisor}`; - case "unrecognized_keys": - return `Chiav${issue3.keys.length > 1 ? "i" : "e"} non riconosciut${issue3.keys.length > 1 ? "e" : "a"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Chiave non valida in ${issue3.origin}`; - case "invalid_union": - return "Input non valido"; - case "invalid_element": - return `Valore non valido in ${issue3.origin}`; - default: - return `Input non valido`; + win322.escapePath = escapePath2; + function convertPathToPattern2(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win322.convertPathToPattern = convertPathToPattern2; + })(win32 = FastGlob2.win32 || (FastGlob2.win32 = {})); + })(FastGlob || (FastGlob = {})); + function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); + } + function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError("Patterns must be a string (non empty) or an array of strings"); } - }; -}; -var init_it2 = __esm(() => { - init_util3(); + } + module.exports = FastGlob; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ja.js -function ja_default2() { - return { - localeError: error69() +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/errors.js +var LangSmithSandboxError, LangSmithSandboxAPIError, LangSmithSandboxAuthenticationError, LangSmithSandboxConnectionError, LangSmithResourceNotFoundError, LangSmithResourceTimeoutError, LangSmithResourceNameConflictError, LangSmithValidationError, LangSmithQuotaExceededError, LangSmithResourceCreationError, LangSmithSandboxCreationError, LangSmithDataplaneNotConfiguredError, LangSmithSandboxNotReadyError, LangSmithSandboxOperationError, LangSmithCommandTimeoutError, LangSmithSandboxServerReloadError; +var init_errors12 = __esm(() => { + LangSmithSandboxError = class LangSmithSandboxError extends Error { + constructor(message) { + super(message); + this.name = "LangSmithSandboxError"; + } }; -} -var error69 = () => { - const Sizable = { - string: { unit: "文字", verb: "である" }, - file: { unit: "バイト", verb: "である" }, - array: { unit: "要素", verb: "である" }, - set: { unit: "要素", verb: "である" } + LangSmithSandboxAPIError = class LangSmithSandboxAPIError extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxAPIError"; + } }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "数値"; - } - case "object": { - if (Array.isArray(data)) { - return "配列"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + LangSmithSandboxAuthenticationError = class LangSmithSandboxAuthenticationError extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxAuthenticationError"; } - return t; }; - const Nouns = { - regex: "入力値", - email: "メールアドレス", - url: "URL", - emoji: "絵文字", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日時", - date: "ISO日付", - time: "ISO時刻", - duration: "ISO期間", - ipv4: "IPv4アドレス", - ipv6: "IPv6アドレス", - cidrv4: "IPv4範囲", - cidrv6: "IPv6範囲", - base64: "base64エンコード文字列", - base64url: "base64urlエンコード文字列", - json_string: "JSON文字列", - e164: "E.164番号", - jwt: "JWT", - template_literal: "入力値" + LangSmithSandboxConnectionError = class LangSmithSandboxConnectionError extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxConnectionError"; + } }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `無効な入力: ${issue3.expected}が期待されましたが、${parsedType4(issue3.input)}が入力されました`; - case "invalid_value": - if (issue3.values.length === 1) - return `無効な入力: ${stringifyPrimitive2(issue3.values[0])}が期待されました`; - return `無効な選択: ${joinValues2(issue3.values, "、")}のいずれかである必要があります`; - case "too_big": { - const adj = issue3.inclusive ? "以下である" : "より小さい"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `大きすぎる値: ${issue3.origin ?? "値"}は${issue3.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; - return `大きすぎる値: ${issue3.origin ?? "値"}は${issue3.maximum.toString()}${adj}必要があります`; - } - case "too_small": { - const adj = issue3.inclusive ? "以上である" : "より大きい"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${sizing.unit}${adj}必要があります`; - return `小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${adj}必要があります`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; - if (_issue.format === "ends_with") - return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; - if (_issue.format === "includes") - return `無効な文字列: "${_issue.includes}"を含む必要があります`; - if (_issue.format === "regex") - return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; - return `無効な${Nouns[_issue.format] ?? issue3.format}`; + LangSmithResourceNotFoundError = class LangSmithResourceNotFoundError extends LangSmithSandboxError { + constructor(message, resourceType) { + super(message); + Object.defineProperty(this, "resourceType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithResourceNotFoundError"; + this.resourceType = resourceType; + } + }; + LangSmithResourceTimeoutError = class LangSmithResourceTimeoutError extends LangSmithSandboxError { + constructor(message, resourceType, lastStatus) { + super(message); + Object.defineProperty(this, "resourceType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "lastStatus", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithResourceTimeoutError"; + this.resourceType = resourceType; + this.lastStatus = lastStatus; + } + toString() { + const base = super.toString(); + if (this.lastStatus) { + return `${base} (last_status: ${this.lastStatus})`; } - case "not_multiple_of": - return `無効な数値: ${issue3.divisor}の倍数である必要があります`; - case "unrecognized_keys": - return `認識されていないキー${issue3.keys.length > 1 ? "群" : ""}: ${joinValues2(issue3.keys, "、")}`; - case "invalid_key": - return `${issue3.origin}内の無効なキー`; - case "invalid_union": - return "無効な入力"; - case "invalid_element": - return `${issue3.origin}内の無効な値`; - default: - return `無効な入力`; + return base; } }; -}; -var init_ja2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/kh.js -function kh_default2() { - return { - localeError: error70() + LangSmithResourceNameConflictError = class LangSmithResourceNameConflictError extends LangSmithSandboxError { + constructor(message, resourceType) { + super(message); + Object.defineProperty(this, "resourceType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithResourceNameConflictError"; + this.resourceType = resourceType; + } }; -} -var error70 = () => { - const Sizable = { - string: { unit: "តួអក្សរ", verb: "គួរមាន" }, - file: { unit: "បៃ", verb: "គួរមាន" }, - array: { unit: "ធាតុ", verb: "គួរមាន" }, - set: { unit: "ធាតុ", verb: "គួរមាន" } + LangSmithValidationError = class LangSmithValidationError extends LangSmithSandboxError { + constructor(message, field, details, errorType) { + super(message); + Object.defineProperty(this, "field", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "errorType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithValidationError"; + this.field = field; + this.details = details; + this.errorType = errorType; + } }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; + LangSmithQuotaExceededError = class LangSmithQuotaExceededError extends LangSmithSandboxError { + constructor(message, quotaType) { + super(message); + Object.defineProperty(this, "quotaType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithQuotaExceededError"; + this.quotaType = quotaType; + } + }; + LangSmithResourceCreationError = class LangSmithResourceCreationError extends LangSmithSandboxError { + constructor(message, resourceType, errorType) { + super(message); + Object.defineProperty(this, "resourceType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "errorType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithResourceCreationError"; + this.resourceType = resourceType; + this.errorType = errorType; + } + toString() { + if (this.errorType) { + return `${super.toString()} [${this.errorType}]`; } - case "object": { - if (Array.isArray(data)) { - return "អារេ (Array)"; - } - if (data === null) { - return "គ្មានតម្លៃ (null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + return super.toString(); + } + }; + LangSmithSandboxCreationError = class LangSmithSandboxCreationError extends LangSmithSandboxError { + constructor(message, errorType) { + super(message); + Object.defineProperty(this, "errorType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithSandboxCreationError"; + this.errorType = errorType; + } + toString() { + if (this.errorType) { + return `${super.toString()} [${this.errorType}]`; } + return super.toString(); } - return t; }; - const Nouns = { - regex: "ទិន្នន័យបញ្ចូល", - email: "អាសយដ្ឋានអ៊ីមែល", - url: "URL", - emoji: "សញ្ញាអារម្មណ៍", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", - date: "កាលបរិច្ឆេទ ISO", - time: "ម៉ោង ISO", - duration: "រយៈពេល ISO", - ipv4: "អាសយដ្ឋាន IPv4", - ipv6: "អាសយដ្ឋាន IPv6", - cidrv4: "ដែនអាសយដ្ឋាន IPv4", - cidrv6: "ដែនអាសយដ្ឋាន IPv6", - base64: "ខ្សែអក្សរអ៊ិកូដ base64", - base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", - json_string: "ខ្សែអក្សរ JSON", - e164: "លេខ E.164", - jwt: "JWT", - template_literal: "ទិន្នន័យបញ្ចូល" + LangSmithDataplaneNotConfiguredError = class LangSmithDataplaneNotConfiguredError extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithDataplaneNotConfiguredError"; + } }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue3.expected} ប៉ុន្តែទទួលបាន ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive2(issue3.values[0])}`; - return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `ធំពេក៖ ត្រូវការ ${issue3.origin ?? "តម្លៃ"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; - return `ធំពេក៖ ត្រូវការ ${issue3.origin ?? "តម្លៃ"} ${adj} ${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`; - } - return `តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; - if (_issue.format === "regex") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; - return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue3.format}`; + LangSmithSandboxNotReadyError = class LangSmithSandboxNotReadyError extends LangSmithSandboxError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxNotReadyError"; + } + }; + LangSmithSandboxOperationError = class LangSmithSandboxOperationError extends LangSmithSandboxError { + constructor(message, operation, errorType) { + super(message); + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "errorType", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithSandboxOperationError"; + this.operation = operation; + this.errorType = errorType; + } + toString() { + if (this.errorType) { + return `${super.toString()} [${this.errorType}]`; } - case "not_multiple_of": - return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue3.divisor}`; - case "unrecognized_keys": - return `រកឃើញសោមិនស្គាល់៖ ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`; - case "invalid_union": - return `ទិន្នន័យមិនត្រឹមត្រូវ`; - case "invalid_element": - return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`; - default: - return `ទិន្នន័យមិនត្រឹមត្រូវ`; + return super.toString(); + } + }; + LangSmithCommandTimeoutError = class LangSmithCommandTimeoutError extends LangSmithSandboxOperationError { + constructor(message, timeout) { + super(message, "command", "CommandTimeout"); + Object.defineProperty(this, "timeout", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = "LangSmithCommandTimeoutError"; + this.timeout = timeout; + } + }; + LangSmithSandboxServerReloadError = class LangSmithSandboxServerReloadError extends LangSmithSandboxConnectionError { + constructor(message) { + super(message); + this.name = "LangSmithSandboxServerReloadError"; } }; -}; -var init_kh2 = __esm(() => { - init_util3(); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ko.js -function ko_default2() { - return { - localeError: error71() - }; +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/helpers.js +function validateTtl(value, name) { + if (value === undefined) { + return; + } + if (value < 0) { + throw new LangSmithValidationError(`${name} must be >= 0, got ${value}`, name); + } + if (value !== 0 && value % 60 !== 0) { + throw new LangSmithValidationError(`${name} must be a multiple of 60 seconds, got ${value}`, name); + } } -var error71 = () => { - const Sizable = { - string: { unit: "문자", verb: "to have" }, - file: { unit: "바이트", verb: "to have" }, - array: { unit: "개", verb: "to have" }, - set: { unit: "개", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +async function parseErrorResponse(response) { + try { + const data = await response.json(); + const detail = data?.detail; + if (detail && typeof detail === "object" && !Array.isArray(detail)) { + return { + errorType: detail.error, + message: detail.message || `HTTP ${response.status}: ${response.statusText}` + }; + } + if (Array.isArray(detail) && detail.length > 0) { + const messages = detail.filter((d) => typeof d === "object" && d !== null).map((d) => d.msg || String(d)).filter(Boolean); + return { + errorType: undefined, + message: messages.length > 0 ? messages.join("; ") : `HTTP ${response.status}: ${response.statusText}` + }; + } + return { + errorType: undefined, + message: detail || `HTTP ${response.status}: ${response.statusText}` + }; + } catch { + return { + errorType: undefined, + message: `HTTP ${response.status}: ${response.statusText}` + }; } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; +} +async function parseValidationError(response) { + try { + const data = await response.json(); + const detail = data?.detail; + if (Array.isArray(detail)) { + return detail; + } + return []; + } catch { + return []; + } +} +function extractQuotaType(message) { + const messageLower = message.toLowerCase(); + if (messageLower.includes("sandbox") && (messageLower.includes("count") || messageLower.includes("limit"))) { + return "sandbox_count"; + } else if (messageLower.includes("cpu")) { + return "cpu"; + } else if (messageLower.includes("memory")) { + return "memory"; + } else if (messageLower.includes("storage")) { + return "storage"; + } + return; +} +async function handleSandboxCreationError(response) { + const status = response.status; + const clonedResponse = response.clone(); + const data = await parseErrorResponse(response); + if (status === 408) { + throw new LangSmithResourceTimeoutError(data.message, "sandbox"); + } else if (status === 422) { + const details = await parseValidationError(clonedResponse); + if (details.length > 0 && details.some((d) => d.type === "value_error")) { + const field = details[0]?.loc?.slice(-1)[0]; + throw new LangSmithValidationError(data.message, field, details); + } else { + throw new LangSmithSandboxCreationError(data.message, data.errorType); + } + } else if (status === 429) { + const quotaType = extractQuotaType(data.message) ?? "unknown"; + throw new LangSmithQuotaExceededError(data.message, quotaType); + } else if (status === 503) { + throw new LangSmithSandboxCreationError(data.message, data.errorType || "Unschedulable"); + } + return handleClientHttpError(clonedResponse); +} +async function handleClientHttpError(response) { + const status = response.status; + const clonedResponse = status === 422 ? response.clone() : null; + const data = await parseErrorResponse(response); + const message = data.message; + const errorType = data.errorType; + if (status === 401 || status === 403) { + throw new LangSmithSandboxAuthenticationError(message); + } + if (status === 404) { + throw new LangSmithResourceNotFoundError(message); + } + if (status === 422 && clonedResponse) { + const details = await parseValidationError(clonedResponse); + const field = details[0]?.loc?.slice(-1)[0]; + throw new LangSmithValidationError(message, field, details); + } + if (status === 429) { + const quotaType = extractQuotaType(message); + throw new LangSmithQuotaExceededError(message, quotaType); + } + if (status === 502 && errorType === "ConnectionError") { + throw new LangSmithSandboxConnectionError(message); + } + if (status === 500) { + throw new LangSmithSandboxAPIError(message); + } + throw new LangSmithSandboxError(message); +} +async function handleSandboxHttpError(response) { + const data = await parseErrorResponse(response); + const message = data.message; + const errorType = data.errorType; + const status = response.status; + if (errorType === "WriteError") { + throw new LangSmithSandboxOperationError(message, "write", errorType); + } + if (errorType === "ReadError") { + throw new LangSmithSandboxOperationError(message, "read", errorType); + } + if (errorType === "CommandError") { + throw new LangSmithSandboxOperationError(message, "command", errorType); + } + if (status === 403) { + throw new LangSmithSandboxOperationError(message, undefined, "PermissionDenied"); + } + if (status === 502 && errorType === "ConnectionError") { + throw new LangSmithSandboxConnectionError(message); + } + if (status === 400 && errorType === "NotReady") { + throw new LangSmithSandboxNotReadyError(message); + } + if (status === 404 || errorType === "FileNotFound") { + throw new LangSmithResourceNotFoundError(message, "file"); + } + throw new LangSmithSandboxError(message); +} +var init_helpers2 = __esm(() => { + init_errors12(); +}); + +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/command_handle.js +var CommandHandle; +var init_command_handle = __esm(() => { + init_errors12(); + CommandHandle = class CommandHandle { + constructor(messageStream, control, sandbox, options) { + Object.defineProperty(this, "_stream", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_control", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_sandbox", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_commandId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_pid", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_result", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_stdoutParts", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "_stderrParts", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "_exhausted", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_lastStdoutOffset", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_lastStderrOffset", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_started", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this._stream = messageStream; + this._control = control; + this._sandbox = sandbox; + this._lastStdoutOffset = options?.stdoutOffset ?? 0; + this._lastStderrOffset = options?.stderrOffset ?? 0; + if (options?.commandId) { + this._commandId = options.commandId; + this._started = true; + } else { + this._started = false; } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + } + async _ensureStarted() { + if (this._started) + return; + const firstResult = await this._stream.next(); + if (firstResult.done) { + throw new LangSmithSandboxOperationError("Command stream ended before 'started' message", "command"); } + const firstMsg = firstResult.value; + if (firstMsg.type !== "started") { + throw new LangSmithSandboxOperationError(`Expected 'started' message, got '${firstMsg.type}'`, "command"); + } + this._commandId = firstMsg.command_id ?? null; + this._pid = firstMsg.pid ?? null; + this._started = true; } - return t; - }; - const Nouns = { - regex: "입력", - email: "이메일 주소", - url: "URL", - emoji: "이모지", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 날짜시간", - date: "ISO 날짜", - time: "ISO 시간", - duration: "ISO 기간", - ipv4: "IPv4 주소", - ipv6: "IPv6 주소", - cidrv4: "IPv4 범위", - cidrv6: "IPv6 범위", - base64: "base64 인코딩 문자열", - base64url: "base64url 인코딩 문자열", - json_string: "JSON 문자열", - e164: "E.164 번호", - jwt: "JWT", - template_literal: "입력" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `잘못된 입력: 예상 타입은 ${issue3.expected}, 받은 타입은 ${parsedType4(issue3.input)}입니다`; - case "invalid_value": - if (issue3.values.length === 1) - return `잘못된 입력: 값은 ${stringifyPrimitive2(issue3.values[0])} 이어야 합니다`; - return `잘못된 옵션: ${joinValues2(issue3.values, "또는 ")} 중 하나여야 합니다`; - case "too_big": { - const adj = issue3.inclusive ? "이하" : "미만"; - const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue3.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) - return `${issue3.origin ?? "값"}이 너무 큽니다: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`; - return `${issue3.origin ?? "값"}이 너무 큽니다: ${issue3.maximum.toString()} ${adj}${suffix}`; + get commandId() { + return this._commandId; + } + get pid() { + return this._pid; + } + get result() { + return this._getResult(); + } + async _getResult() { + if (this._result === null) { + for await (const _ of this) {} } - case "too_small": { - const adj = issue3.inclusive ? "이상" : "초과"; - const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue3.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) { - return `${issue3.origin ?? "값"}이 너무 작습니다: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`; + if (this._result === null) { + throw new LangSmithSandboxOperationError("Command stream ended without exit message", "command"); + } + return this._result; + } + async* _iterStream() { + await this._ensureStarted(); + if (this._exhausted) + return; + for await (const msg of this._stream) { + const msgType = msg.type; + if (msgType === "stdout" || msgType === "stderr") { + const chunk = { + stream: msgType, + data: msg.data, + offset: msg.offset ?? 0 + }; + if (msgType === "stdout") { + this._stdoutParts.push(msg.data); + } else { + this._stderrParts.push(msg.data); + } + yield chunk; + } else if (msgType === "exit") { + this._result = { + stdout: this._stdoutParts.join(""), + stderr: this._stderrParts.join(""), + exit_code: msg.exit_code ?? -1 + }; + this._exhausted = true; + return; } - return `${issue3.origin ?? "값"}이 너무 작습니다: ${issue3.minimum.toString()} ${adj}${suffix}`; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; + this._exhausted = true; + } + async* [Symbol.asyncIterator]() { + let reconnectAttempts = 0; + while (true) { + try { + for await (const chunk of this._iterStream()) { + reconnectAttempts = 0; + if (chunk.stream === "stdout") { + this._lastStdoutOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; + } else { + this._lastStderrOffset = chunk.offset + new TextEncoder().encode(chunk.data).length; + } + yield chunk; + } + return; + } catch (e) { + const eName = e != null && typeof e === "object" ? e.name : ""; + if (eName !== "LangSmithSandboxConnectionError" && eName !== "LangSmithSandboxServerReloadError") { + throw e; + } + if (this._control && this._control.killed) { + throw e; + } + reconnectAttempts++; + if (reconnectAttempts > CommandHandle.MAX_AUTO_RECONNECTS) { + throw new LangSmithSandboxConnectionError(`Lost connection ${reconnectAttempts} times in succession, giving up`); + } + const isHotReload = eName === "LangSmithSandboxServerReloadError"; + if (!isHotReload) { + const delay = Math.min(CommandHandle.BACKOFF_BASE * 2 ** (reconnectAttempts - 1), CommandHandle.BACKOFF_MAX); + await new Promise((r) => setTimeout(r, delay * 1000)); + } + if (this._commandId === null) { + throw e; + } + const newHandle = await this._sandbox.reconnect(this._commandId, { + stdoutOffset: this._lastStdoutOffset, + stderrOffset: this._lastStderrOffset + }); + this._stream = newHandle._stream; + this._control = newHandle._control; + this._exhausted = false; } - if (_issue.format === "ends_with") - return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; - if (_issue.format === "includes") - return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; - if (_issue.format === "regex") - return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; - return `잘못된 ${Nouns[_issue.format] ?? issue3.format}`; } - case "not_multiple_of": - return `잘못된 숫자: ${issue3.divisor}의 배수여야 합니다`; - case "unrecognized_keys": - return `인식할 수 없는 키: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `잘못된 키: ${issue3.origin}`; - case "invalid_union": - return `잘못된 입력`; - case "invalid_element": - return `잘못된 값: ${issue3.origin}`; - default: - return `잘못된 입력`; + } + kill() { + if (this._control) { + this._control.sendKill(); + } + } + sendInput(data) { + if (this._control) { + this._control.sendInput(data); + } + } + get lastStdoutOffset() { + return this._lastStdoutOffset; + } + get lastStderrOffset() { + return this._lastStderrOffset; + } + async reconnect() { + if (this._commandId === null) { + throw new LangSmithSandboxOperationError("Cannot reconnect: command ID not available", "reconnect"); + } + return this._sandbox.reconnect(this._commandId, { + stdoutOffset: this._lastStdoutOffset, + stderrOffset: this._lastStderrOffset + }); } }; -}; -var init_ko2 = __esm(() => { - init_util3(); + Object.defineProperty(CommandHandle, "MAX_AUTO_RECONNECTS", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(CommandHandle, "BACKOFF_BASE", { + enumerable: true, + configurable: true, + writable: true, + value: 0.5 + }); + Object.defineProperty(CommandHandle, "BACKOFF_MAX", { + enumerable: true, + configurable: true, + writable: true, + value: 8 + }); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/mk.js -function mk_default2() { - return { - localeError: error72() +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js +var require_constants4 = __commonJS((exports, module) => { + var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"]; + var hasBlob = typeof Blob !== "undefined"; + if (hasBlob) + BINARY_TYPES.push("blob"); + module.exports = { + BINARY_TYPES, + CLOSE_TIMEOUT: 30000, + EMPTY_BUFFER: Buffer.alloc(0), + GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", + hasBlob, + kForOnEventAttribute: Symbol("kIsForOnEventAttribute"), + kListener: Symbol("kListener"), + kStatusCode: Symbol("status-code"), + kWebSocket: Symbol("websocket"), + NOOP: () => {} }; -} -var error72 = () => { - const Sizable = { - string: { unit: "знаци", verb: "да имаат" }, - file: { unit: "бајти", verb: "да имаат" }, - array: { unit: "ставки", verb: "да имаат" }, - set: { unit: "ставки", verb: "да имаат" } +}); + +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js +var require_buffer_util = __commonJS((exports, module) => { + var { EMPTY_BUFFER } = require_constants4(); + var FastBuffer = Buffer[Symbol.species]; + function concat3(list, totalLength) { + if (list.length === 0) + return EMPTY_BUFFER; + if (list.length === 1) + return list[0]; + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + for (let i = 0;i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + return target; + } + function _mask(source, mask, output, offset, length) { + for (let i = 0;i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + } + function _unmask(buffer, mask) { + for (let i = 0;i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } + } + function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); + } + function toBuffer(data) { + toBuffer.readOnly = true; + if (Buffer.isBuffer(data)) + return data; + let buf; + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + return buf; + } + module.exports = { + concat: concat3, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask }; - function getSizing(origin) { - return Sizable[origin] ?? null; + if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})(); + module.exports.mask = function(source, mask, output, offset, length) { + if (length < 48) + _mask(source, mask, output, offset, length); + else + bufferUtil.mask(source, mask, output, offset, length); + }; + module.exports.unmask = function(buffer, mask) { + if (buffer.length < 32) + _unmask(buffer, mask); + else + bufferUtil.unmask(buffer, mask); + }; + } catch (e) {} } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "број"; +}); + +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js +var require_limiter = __commonJS((exports, module) => { + var kDone = Symbol("kDone"); + var kRun = Symbol("kRun"); + + class Limiter { + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + add(job) { + this.jobs.push(job); + this[kRun](); + } + [kRun]() { + if (this.pending === this.concurrency) + return; + if (this.jobs.length) { + const job = this.jobs.shift(); + this.pending++; + job(this[kDone]); } - case "object": { - if (Array.isArray(data)) { - return "низа"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + } + } + module.exports = Limiter; +}); + +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js +var require_permessage_deflate = __commonJS((exports, module) => { + var zlib = __require("zlib"); + var bufferUtil = require_buffer_util(); + var Limiter = require_limiter(); + var { kStatusCode } = require_constants4(); + var FastBuffer = Buffer[Symbol.species]; + var TRAILER = Buffer.from([0, 0, 255, 255]); + var kPerMessageDeflate = Symbol("permessage-deflate"); + var kTotalLength = Symbol("total-length"); + var kCallback = Symbol("callback"); + var kBuffers = Symbol("buffers"); + var kError = Symbol("error"); + var zlibLimiter; + + class PerMessageDeflate { + constructor(options) { + this._options = options || {}; + this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024; + this._maxPayload = this._options.maxPayload | 0; + this._isServer = !!this._options.isServer; + this._deflate = null; + this._inflate = null; + this.params = null; + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10; + zlibLimiter = new Limiter(concurrency); } } - return t; - }; - const Nouns = { - regex: "внес", - email: "адреса на е-пошта", - url: "URL", - emoji: "емоџи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO датум и време", - date: "ISO датум", - time: "ISO време", - duration: "ISO времетраење", - ipv4: "IPv4 адреса", - ipv6: "IPv6 адреса", - cidrv4: "IPv4 опсег", - cidrv6: "IPv6 опсег", - base64: "base64-енкодирана низа", - base64url: "base64url-енкодирана низа", - json_string: "JSON низа", - e164: "E.164 број", - jwt: "JWT", - template_literal: "внес" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Грешен внес: се очекува ${issue3.expected}, примено ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`; - return `Грешана опција: се очекува една ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Премногу голем: се очекува ${issue3.origin ?? "вредноста"} да има ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "елементи"}`; - return `Премногу голем: се очекува ${issue3.origin ?? "вредноста"} да биде ${adj}${issue3.maximum.toString()}`; + static get extensionName() { + return "permessage-deflate"; + } + offer() { + const params = {}; + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Премногу мал: се очекува ${issue3.origin} да има ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Премногу мал: се очекува ${issue3.origin} да биде ${adj}${issue3.minimum.toString()}`; + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неважечка низа: мора да вклучува "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue3.format}`; + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; } - case "not_multiple_of": - return `Грешен број: мора да биде делив со ${issue3.divisor}`; - case "unrecognized_keys": - return `${issue3.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Грешен клуч во ${issue3.origin}`; - case "invalid_union": - return "Грешен внес"; - case "invalid_element": - return `Грешна вредност во ${issue3.origin}`; - default: - return `Грешен внес`; + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + return params; } - }; -}; -var init_mk2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ms.js -function ms_default2() { - return { - localeError: error73() - }; -} -var error73 = () => { - const Sizable = { - string: { unit: "aksara", verb: "mempunyai" }, - file: { unit: "bait", verb: "mempunyai" }, - array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombor"; + accept(configurations) { + configurations = this.normalizeParams(configurations); + this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations); + return this.params; + } + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; + if (this._deflate) { + const callback = this._deflate[kCallback]; + this._deflate.close(); + this._deflate = null; + if (callback) { + callback(new Error("The deflate stream was closed while data was being processed")); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } + } + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) { + return false; } + return true; + }); + if (!accepted) { + throw new Error("None of the extension offers can be accepted"); + } + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === "number") { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === "number") { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) { + delete accepted.client_max_window_bits; } + return accepted; } - return t; - }; - const Nouns = { - regex: "input", - email: "alamat e-mel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tarikh masa ISO", - date: "tarikh ISO", - time: "masa ISO", - duration: "tempoh ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "julat IPv4", - cidrv6: "julat IPv6", - base64: "string dikodkan base64", - base64url: "string dikodkan base64url", - json_string: "string JSON", - e164: "nombor E.164", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Input tidak sah: dijangka ${issue3.expected}, diterima ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Input tidak sah: dijangka ${stringifyPrimitive2(issue3.values[0])}`; - return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} adalah ${adj}${issue3.maximum.toString()}`; + acceptAsClient(response) { + const params = response[0]; + if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === "number") { + params.client_max_window_bits = this._options.clientMaxWindowBits; } - return `Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`; + } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) { + throw new Error('Unexpected or invalid parameter "client_max_window_bits"'); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak sah: mesti mengandungi "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} tidak sah`; - } - case "not_multiple_of": - return `Nombor tidak sah: perlu gandaan ${issue3.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak sah dalam ${issue3.origin}`; - case "invalid_union": - return "Input tidak sah"; - case "invalid_element": - return `Nilai tidak sah dalam ${issue3.origin}`; - default: - return `Input tidak sah`; + return params; } - }; -}; -var init_ms2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/nl.js -function nl_default2() { - return { - localeError: error74() - }; -} -var error74 = () => { - const Sizable = { - string: { unit: "tekens" }, - file: { unit: "bytes" }, - array: { unit: "elementen" }, - set: { unit: "elementen" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "getal"; + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + value = value[0]; + if (key === "client_max_window_bits") { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError(`Invalid value for parameter "${key}": ${value}`); + } + value = num; + } else if (!this._isServer) { + throw new TypeError(`Invalid value for parameter "${key}": ${value}`); + } + } else if (key === "server_max_window_bits") { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError(`Invalid value for parameter "${key}": ${value}`); + } + value = num; + } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") { + if (value !== true) { + throw new TypeError(`Invalid value for parameter "${key}": ${value}`); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + params[key] = value; + }); + }); + return configurations; + } + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + _decompress(data, fin, callback) { + const endpoint = this._isServer ? "client" : "server"; + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on("error", inflateOnError); + this._inflate.on("data", inflateOnData); } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; + this._inflate[kCallback] = callback; + this._inflate.write(data); + if (fin) + this._inflate.write(TRAILER); + this._inflate.flush(() => { + const err = this._inflate[kError]; + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]); + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } } - } + callback(null, data2); + }); } - return t; - }; - const Nouns = { - regex: "invoer", - email: "emailadres", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum en tijd", - date: "ISO datum", - time: "ISO tijd", - duration: "ISO duur", - ipv4: "IPv4-adres", - ipv6: "IPv6-adres", - cidrv4: "IPv4-bereik", - cidrv6: "IPv6-bereik", - base64: "base64-gecodeerde tekst", - base64url: "base64 URL-gecodeerde tekst", - json_string: "JSON string", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "invoer" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Ongeldige invoer: verwacht ${issue3.expected}, ontving ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Ongeldige invoer: verwacht ${stringifyPrimitive2(issue3.values[0])}`; - return `Ongeldige optie: verwacht één van ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; - return `Te lang: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} is`; + _compress(data, fin, callback) { + const endpoint = this._isServer ? "server" : "client"; + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key]; + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + this._deflate.on("data", deflateOnData); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} bevat`; + this._deflate[kCallback] = callback; + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + return; } - return `Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]); + if (fin) { + data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4); } - if (_issue.format === "ends_with") - return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; - if (_issue.format === "includes") - return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; - if (_issue.format === "regex") - return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; - return `Ongeldig: ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`; - case "unrecognized_keys": - return `Onbekende key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Ongeldige key in ${issue3.origin}`; - case "invalid_union": - return "Ongeldige invoer"; - case "invalid_element": - return `Ongeldige waarde in ${issue3.origin}`; - default: - return `Ongeldige invoer`; + this._deflate[kCallback] = null; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + callback(null, data2); + }); } - }; -}; -var init_nl2 = __esm(() => { - init_util3(); + } + module.exports = PerMessageDeflate; + function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; + } + function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) { + this[kBuffers].push(chunk); + return; + } + this[kError] = new RangeError("Max payload size exceeded"); + this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"; + this[kError][kStatusCode] = 1009; + this.removeListener("data", inflateOnData); + this.reset(); + } + function inflateOnError(err) { + this[kPerMessageDeflate]._inflate = null; + if (this[kError]) { + this[kCallback](this[kError]); + return; + } + err[kStatusCode] = 1007; + this[kCallback](err); + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/no.js -function no_default2() { - return { - localeError: error75() - }; -} -var error75 = () => { - const Sizable = { - string: { unit: "tegn", verb: "å ha" }, - file: { unit: "bytes", verb: "å ha" }, - array: { unit: "elementer", verb: "å inneholde" }, - set: { unit: "elementer", verb: "å inneholde" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js +var require_validation = __commonJS((exports, module) => { + var { isUtf8 } = __require("buffer"); + var { hasBlob } = require_constants4(); + var tokenChars = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 0, + 1, + 0 + ]; + function isValidStatusCode(code) { + return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999; } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "tall"; - } - case "object": { - if (Array.isArray(data)) { - return "liste"; - } - if (data === null) { - return "null"; + function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + while (i < len) { + if ((buf[i] & 128) === 0) { + i++; + } else if ((buf[i] & 224) === 192) { + if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) { + return false; } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + i += 2; + } else if ((buf[i] & 240) === 224) { + if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) { + return false; } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "e-postadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslett", - date: "ISO-dato", - time: "ISO-klokkeslett", - duration: "ISO-varighet", - ipv4: "IPv4-område", - ipv6: "IPv6-område", - cidrv4: "IPv4-spekter", - cidrv6: "IPv6-spekter", - base64: "base64-enkodet streng", - base64url: "base64url-enkodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Ugyldig input: forventet ${issue3.expected}, fikk ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Ugyldig verdi: forventet ${stringifyPrimitive2(issue3.values[0])}`; - return `Ugyldig valg: forventet en av ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `For stor(t): forventet ${issue3.origin ?? "value"} til å ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor(t): forventet ${issue3.origin ?? "value"} til å ha ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + i += 3; + } else if ((buf[i] & 248) === 240) { + if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) { + return false; } - return `For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Ugyldig streng: må starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: må ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: må inneholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; - return `Ugyldig ${Nouns[_issue.format] ?? issue3.format}`; + i += 4; + } else { + return false; } - case "not_multiple_of": - return `Ugyldig tall: må være et multiplum av ${issue3.divisor}`; - case "unrecognized_keys": - return `${issue3.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Ugyldig nøkkel i ${issue3.origin}`; - case "invalid_union": - return "Ugyldig input"; - case "invalid_element": - return `Ugyldig verdi i ${issue3.origin}`; - default: - return `Ugyldig input`; } + return true; + } + function isBlob(value) { + return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File"); + } + module.exports = { + isBlob, + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars }; -}; -var init_no2 = __esm(() => { - init_util3(); + if (isUtf8) { + module.exports.isValidUTF8 = function(buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; + } else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})(); + module.exports.isValidUTF8 = function(buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) {} + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ota.js -function ota_default2() { - return { - localeError: error76() - }; -} -var error76 = () => { - const Sizable = { - string: { unit: "harf", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "unsur", verb: "olmalıdır" }, - set: { unit: "unsur", verb: "olmalıdır" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "numara"; - } - case "object": { - if (Array.isArray(data)) { - return "saf"; - } - if (data === null) { - return "gayb"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js +var require_receiver = __commonJS((exports, module) => { + var { Writable } = __require("stream"); + var PerMessageDeflate = require_permessage_deflate(); + var { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket + } = require_constants4(); + var { concat: concat3, toArrayBuffer, unmask } = require_buffer_util(); + var { isValidStatusCode, isValidUTF8 } = require_validation(); + var FastBuffer = Buffer[Symbol.species]; + var GET_INFO = 0; + var GET_PAYLOAD_LENGTH_16 = 1; + var GET_PAYLOAD_LENGTH_64 = 2; + var GET_MASK = 3; + var GET_DATA = 4; + var INFLATING = 5; + var DEFER_EVENT = 6; + + class Receiver extends Writable { + constructor(options = {}) { + super(); + this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true; + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxBufferedChunks = options.maxBufferedChunks | 0; + this._maxFragments = options.maxFragments | 0; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + this._bufferedBytes = 0; + this._buffers = []; + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + this._errored = false; + this._loop = false; + this._state = GET_INFO; + } + _write(chunk, encoding, cb) { + if (this._opcode === 8 && this._state == GET_INFO) + return cb(); + if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) { + cb(this.createError(RangeError, "Too many buffered chunks", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS")); + return; } + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); } - return t; - }; - const Nouns = { - regex: "giren", - email: "epostagâh", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO hengâmı", - date: "ISO tarihi", - time: "ISO zamanı", - duration: "ISO müddeti", - ipv4: "IPv4 nişânı", - ipv6: "IPv6 nişânı", - cidrv4: "IPv4 menzili", - cidrv6: "IPv6 menzili", - base64: "base64-şifreli metin", - base64url: "base64url-şifreli metin", - json_string: "JSON metin", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "giren" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Fâsit giren: umulan ${issue3.expected}, alınan ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Fâsit giren: umulan ${stringifyPrimitive2(issue3.values[0])}`; - return `Fâsit tercih: mûteberler ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Fazla büyük: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; - return `Fazla büyük: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} olmalıydı.`; + consume(n4) { + this._bufferedBytes -= n4; + if (n4 === this._buffers[0].length) + return this._buffers.shift(); + if (n4 < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n4, buf.length - n4); + return new FastBuffer(buf.buffer, buf.byteOffset, n4); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; + const dst = Buffer.allocUnsafe(n4); + do { + const buf = this._buffers[0]; + const offset = dst.length - n4; + if (n4 >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n4), offset); + this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n4, buf.length - n4); } - return `Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmalıydı.`; + n4 -= buf.length; + } while (n4 > 0); + return dst; + } + startLoop(cb) { + this._loop = true; + do { + switch (this._state) { + case GET_INFO: + this.getInfo(cb); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(cb); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(cb); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(cb); + break; + case INFLATING: + case DEFER_EVENT: + this._loop = false; + return; + } + } while (this._loop); + if (!this._errored) + cb(); + } + getInfo(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; - if (_issue.format === "ends_with") - return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; - if (_issue.format === "includes") - return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; - if (_issue.format === "regex") - return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; - return `Fâsit ${Nouns[_issue.format] ?? issue3.format}`; + const buf = this.consume(2); + if ((buf[0] & 48) !== 0) { + const error90 = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"); + cb(error90); + return; } - case "not_multiple_of": - return `Fâsit sayı: ${issue3.divisor} katı olmalıydı.`; - case "unrecognized_keys": - return `Tanınmayan anahtar ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `${issue3.origin} için tanınmayan anahtar var.`; - case "invalid_union": - return "Giren tanınamadı."; - case "invalid_element": - return `${issue3.origin} için tanınmayan kıymet var.`; - default: - return `Kıymet tanınamadı.`; - } - }; -}; -var init_ota2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ps.js -function ps_default2() { - return { - localeError: error77() - }; -} -var error77 = () => { - const Sizable = { - string: { unit: "توکي", verb: "ولري" }, - file: { unit: "بایټس", verb: "ولري" }, - array: { unit: "توکي", verb: "ولري" }, - set: { unit: "توکي", verb: "ولري" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "عدد"; + const compressed = (buf[0] & 64) === 64; + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + const error90 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); + cb(error90); + return; } - case "object": { - if (Array.isArray(data)) { - return "ارې"; + this._fin = (buf[0] & 128) === 128; + this._opcode = buf[0] & 15; + this._payloadLength = buf[1] & 127; + if (this._opcode === 0) { + if (compressed) { + const error90 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); + cb(error90); + return; } - if (data === null) { - return "null"; + if (!this._fragmented) { + const error90 = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"); + cb(error90); + return; } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + this._opcode = this._fragmented; + } else if (this._opcode === 1 || this._opcode === 2) { + if (this._fragmented) { + const error90 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"); + cb(error90); + return; } - } - } - return t; - }; - const Nouns = { - regex: "ورودي", - email: "بریښنالیک", - url: "یو آر ال", - emoji: "ایموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "نیټه او وخت", - date: "نېټه", - time: "وخت", - duration: "موده", - ipv4: "د IPv4 پته", - ipv6: "د IPv6 پته", - cidrv4: "د IPv4 ساحه", - cidrv6: "د IPv6 ساحه", - base64: "base64-encoded متن", - base64url: "base64url-encoded متن", - json_string: "JSON متن", - e164: "د E.164 شمېره", - jwt: "JWT", - template_literal: "ورودي" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `ناسم ورودي: باید ${issue3.expected} وای, مګر ${parsedType4(issue3.input)} ترلاسه شو`; - case "invalid_value": - if (issue3.values.length === 1) { - return `ناسم ورودي: باید ${stringifyPrimitive2(issue3.values[0])} وای`; + this._compressed = compressed; + } else if (this._opcode > 7 && this._opcode < 11) { + if (!this._fin) { + const error90 = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"); + cb(error90); + return; } - return `ناسم انتخاب: باید یو له ${joinValues2(issue3.values, "|")} څخه وای`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `ډیر لوی: ${issue3.origin ?? "ارزښت"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; + if (compressed) { + const error90 = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"); + cb(error90); + return; } - return `ډیر لوی: ${issue3.origin ?? "ارزښت"} باید ${adj}${issue3.maximum.toString()} وي`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} ولري`; + if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) { + const error90 = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"); + cb(error90); + return; } - return `ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} وي`; + } else { + const error90 = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"); + cb(error90); + return; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; - } - if (_issue.format === "ends_with") { - return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; - } - if (_issue.format === "includes") { - return `ناسم متن: باید "${_issue.includes}" ولري`; + if (!this._fin && !this._fragmented) + this._fragmented = this._opcode; + this._masked = (buf[1] & 128) === 128; + if (this._isServer) { + if (!this._masked) { + const error90 = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"); + cb(error90); + return; } - if (_issue.format === "regex") { - return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; + } else if (this._masked) { + const error90 = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"); + cb(error90); + return; + } + if (this._payloadLength === 126) + this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) + this._state = GET_PAYLOAD_LENGTH_64; + else + this.haveLength(cb); + } + getPayloadLength16(cb) { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + this._payloadLength = this.consume(2).readUInt16BE(0); + this.haveLength(cb); + } + getPayloadLength64(cb) { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + if (num > Math.pow(2, 53 - 32) - 1) { + const error90 = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"); + cb(error90); + return; + } + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + this.haveLength(cb); + } + haveLength(cb) { + if (this._payloadLength && this._opcode < 8) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + const error90 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"); + cb(error90); + return; } - return `${Nouns[_issue.format] ?? issue3.format} ناسم دی`; } - case "not_multiple_of": - return `ناسم عدد: باید د ${issue3.divisor} مضرب وي`; - case "unrecognized_keys": - return `ناسم ${issue3.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `ناسم کلیډ په ${issue3.origin} کې`; - case "invalid_union": - return `ناسمه ورودي`; - case "invalid_element": - return `ناسم عنصر په ${issue3.origin} کې`; - default: - return `ناسمه ورودي`; + if (this._masked) + this._state = GET_MASK; + else + this._state = GET_DATA; } - }; -}; -var init_ps2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pl.js -function pl_default2() { - return { - localeError: error78() - }; -} -var error78 = () => { - const Sizable = { - string: { unit: "znaków", verb: "mieć" }, - file: { unit: "bajtów", verb: "mieć" }, - array: { unit: "elementów", verb: "mieć" }, - set: { unit: "elementów", verb: "mieć" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "liczba"; + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; } - case "object": { - if (Array.isArray(data)) { - return "tablica"; + this._mask = this.consume(4); + this._state = GET_DATA; + } + getData(cb) { + let data = EMPTY_BUFFER; + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; } - if (data === null) { - return "null"; + data = this.consume(this._payloadLength); + if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) { + unmask(data, this._mask); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } + if (this._opcode > 7) { + this.controlMessage(data, cb); + return; + } + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + if (data.length) { + if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) { + const error90 = this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"); + cb(error90); + return; } + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); } + this.dataMessage(cb); } - return t; - }; - const Nouns = { - regex: "wyrażenie", - email: "adres email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i godzina w formacie ISO", - date: "data w formacie ISO", - time: "godzina w formacie ISO", - duration: "czas trwania ISO", - ipv4: "adres IPv4", - ipv6: "adres IPv6", - cidrv4: "zakres IPv4", - cidrv6: "zakres IPv6", - base64: "ciąg znaków zakodowany w formacie base64", - base64url: "ciąg znaków zakodowany w formacie base64url", - json_string: "ciąg znaków w formacie JSON", - e164: "liczba E.164", - jwt: "JWT", - template_literal: "wejście" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Nieprawidłowe dane wejściowe: oczekiwano ${issue3.expected}, otrzymano ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive2(issue3.values[0])}`; - return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Za duża wartość: oczekiwano, że ${issue3.origin ?? "wartość"} będzie mieć ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementów"}`; - } - return `Zbyt duż(y/a/e): oczekiwano, że ${issue3.origin ?? "wartość"} będzie wynosić ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Za mała wartość: oczekiwano, że ${issue3.origin ?? "wartość"} będzie mieć ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "elementów"}`; + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) + return cb(err); + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + const error90 = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"); + cb(error90); + return; + } + if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) { + const error90 = this.createError(RangeError, "Too many message fragments", false, 1008, "WS_ERR_TOO_MANY_BUFFERED_PARTS"); + cb(error90); + return; + } + this._fragments.push(buf); } - return `Zbyt mał(y/a/e): oczekiwano, że ${issue3.origin ?? "wartość"} będzie wynosić ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; - return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `Nieprawidłowa liczba: musi być wielokrotnością ${issue3.divisor}`; - case "unrecognized_keys": - return `Nierozpoznane klucze${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Nieprawidłowy klucz w ${issue3.origin}`; - case "invalid_union": - return "Nieprawidłowe dane wejściowe"; - case "invalid_element": - return `Nieprawidłowa wartość w ${issue3.origin}`; - default: - return `Nieprawidłowe dane wejściowe`; + this.dataMessage(cb); + if (this._state === GET_INFO) + this.startLoop(cb); + }); } - }; -}; -var init_pl2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/pt.js -function pt_default2() { - return { - localeError: error79() - }; -} -var error79 = () => { - const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "número"; + dataMessage(cb) { + if (!this._fin) { + this._state = GET_INFO; + return; } - case "object": { - if (Array.isArray(data)) { - return "array"; + const messageLength = this._messageLength; + const fragments = this._fragments; + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + if (this._opcode === 2) { + let data; + if (this._binaryType === "nodebuffer") { + data = concat3(fragments, messageLength); + } else if (this._binaryType === "arraybuffer") { + data = toArrayBuffer(concat3(fragments, messageLength)); + } else if (this._binaryType === "blob") { + data = new Blob(fragments); + } else { + data = fragments; } - if (data === null) { - return "nulo"; + if (this._allowSynchronousEvents) { + this.emit("message", data, true); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", data, true); + this._state = GET_INFO; + this.startLoop(cb); + }); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } else { + const buf = concat3(fragments, messageLength); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error90 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"); + cb(error90); + return; + } + if (this._state === INFLATING || this._allowSynchronousEvents) { + this.emit("message", buf, false); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit("message", buf, false); + this._state = GET_INFO; + this.startLoop(cb); + }); } } } - return t; - }; - const Nouns = { - regex: "padrão", - email: "endereço de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "duração ISO", - ipv4: "endereço IPv4", - ipv6: "endereço IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Tipo inválido: esperado ${issue3.expected}, recebido ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Entrada inválida: esperado ${stringifyPrimitive2(issue3.values[0])}`; - return `Opção inválida: esperada uma das ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Muito grande: esperado que ${issue3.origin ?? "valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue3.origin ?? "valor"} fosse ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + controlMessage(data, cb) { + if (this._opcode === 8) { + if (data.length === 0) { + this._loop = false; + this.emit("conclude", 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + if (!isValidStatusCode(code)) { + const error90 = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"); + cb(error90); + return; + } + const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2); + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + const error90 = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"); + cb(error90); + return; + } + this._loop = false; + this.emit("conclude", code, buf); + this.end(); } - return `Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`; + this._state = GET_INFO; + return; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Texto inválido: deve começar com "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Texto inválido: deve terminar com "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Texto inválido: deve incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} inválido`; + if (this._allowSynchronousEvents) { + this.emit(this._opcode === 9 ? "ping" : "pong", data); + this._state = GET_INFO; + } else { + this._state = DEFER_EVENT; + setImmediate(() => { + this.emit(this._opcode === 9 ? "ping" : "pong", data); + this._state = GET_INFO; + this.startLoop(cb); + }); } - case "not_multiple_of": - return `Número inválido: deve ser múltiplo de ${issue3.divisor}`; - case "unrecognized_keys": - return `Chave${issue3.keys.length > 1 ? "s" : ""} desconhecida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Chave inválida em ${issue3.origin}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido em ${issue3.origin}`; - default: - return `Campo inválido`; } - }; -}; -var init_pt2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ru.js -function getRussianPlural2(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -function ru_default2() { - return { - localeError: error80() - }; -} -var error80 = () => { - const Sizable = { - string: { - unit: { - one: "символ", - few: "символа", - many: "символов" - }, - verb: "иметь" - }, - file: { - unit: { - one: "байт", - few: "байта", - many: "байт" - }, - verb: "иметь" - }, - array: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов" - }, - verb: "иметь" - }, - set: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов" - }, - verb: "иметь" + createError(ErrorCtor, message, prefix, statusCode, errorCode) { + this._loop = false; + this._errored = true; + const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message); + Error.captureStackTrace(err, this.createError); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "число"; - } - case "object": { - if (Array.isArray(data)) { - return "массив"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + module.exports = Receiver; +}); + +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js +var require_sender = __commonJS((exports, module) => { + var { Duplex } = __require("stream"); + var { randomFillSync: randomFillSync2 } = __require("crypto"); + var { + types: { isUint8Array } + } = __require("util"); + var PerMessageDeflate = require_permessage_deflate(); + var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants4(); + var { isBlob, isValidStatusCode } = require_validation(); + var { mask: applyMask, toBuffer } = require_buffer_util(); + var kByteLength = Symbol("kByteLength"); + var maskBuffer = Buffer.alloc(4); + var RANDOM_POOL_SIZE = 8 * 1024; + var randomPool; + var randomPoolPointer = RANDOM_POOL_SIZE; + var DEFAULT = 0; + var DEFLATING = 1; + var GET_BLOB_DATA = 2; + + class Sender { + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); } + this._socket = socket; + this._firstFragment = true; + this._compress = false; + this._bufferedBytes = 0; + this._queue = []; + this._state = DEFAULT; + this.onerror = NOOP; + this[kWebSocket] = undefined; } - return t; - }; - const Nouns = { - regex: "ввод", - email: "email адрес", - url: "URL", - emoji: "эмодзи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата и время", - date: "ISO дата", - time: "ISO время", - duration: "ISO длительность", - ipv4: "IPv4 адрес", - ipv6: "IPv6 адрес", - cidrv4: "IPv4 диапазон", - cidrv6: "IPv6 диапазон", - base64: "строка в формате base64", - base64url: "строка в формате base64url", - json_string: "JSON строка", - e164: "номер E.164", - jwt: "JWT", - template_literal: "ввод" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Неверный ввод: ожидалось ${issue3.expected}, получено ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Неверный ввод: ожидалось ${stringifyPrimitive2(issue3.values[0])}`; - return `Неверный вариант: ожидалось одно из ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - const maxValue = Number(issue3.maximum); - const unit = getRussianPlural2(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком большое значение: ожидалось, что ${issue3.origin ?? "значение"} будет иметь ${adj}${issue3.maximum.toString()} ${unit}`; + static frame(data, options) { + let mask; + let merge3 = false; + let offset = 2; + let skipMasking = false; + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + if (options.generateMask) { + options.generateMask(mask); + } else { + if (randomPoolPointer === RANDOM_POOL_SIZE) { + if (randomPool === undefined) { + randomPool = Buffer.alloc(RANDOM_POOL_SIZE); + } + randomFillSync2(randomPool, 0, RANDOM_POOL_SIZE); + randomPoolPointer = 0; + } + mask[0] = randomPool[randomPoolPointer++]; + mask[1] = randomPool[randomPoolPointer++]; + mask[2] = randomPool[randomPoolPointer++]; + mask[3] = randomPool[randomPoolPointer++]; } - return `Слишком большое значение: ожидалось, что ${issue3.origin ?? "значение"} будет ${adj}${issue3.maximum.toString()}`; + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - const minValue = Number(issue3.minimum); - const unit = getRussianPlural2(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком маленькое значение: ожидалось, что ${issue3.origin} будет иметь ${adj}${issue3.minimum.toString()} ${unit}`; + let dataLength; + if (typeof data === "string") { + if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; } - return `Слишком маленькое значение: ожидалось, что ${issue3.origin} будет ${adj}${issue3.minimum.toString()}`; + } else { + dataLength = data.length; + merge3 = options.mask && options.readOnly && !skipMasking; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Неверная строка: должна начинаться с "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неверная строка: должна содержать "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; - return `Неверный ${Nouns[_issue.format] ?? issue3.format}`; + let payloadLength = dataLength; + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; } - case "not_multiple_of": - return `Неверное число: должно быть кратным ${issue3.divisor}`; - case "unrecognized_keys": - return `Нераспознанн${issue3.keys.length > 1 ? "ые" : "ый"} ключ${issue3.keys.length > 1 ? "и" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Неверный ключ в ${issue3.origin}`; - case "invalid_union": - return "Неверные входные данные"; - case "invalid_element": - return `Неверное значение в ${issue3.origin}`; - default: - return `Неверные входные данные`; - } - }; -}; -var init_ru2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sl.js -function sl_default2() { - return { - localeError: error81() - }; -} -var error81 = () => { - const Sizable = { - string: { unit: "znakov", verb: "imeti" }, - file: { unit: "bajtov", verb: "imeti" }, - array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "število"; + const target = Buffer.allocUnsafe(merge3 ? dataLength + offset : offset); + target[0] = options.fin ? options.opcode | 128 : options.opcode; + if (options.rsv1) + target[0] |= 64; + target[1] = payloadLength; + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); } - case "object": { - if (Array.isArray(data)) { - return "tabela"; - } - if (data === null) { - return "null"; + if (!options.mask) + return [target, data]; + target[1] |= 128; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + if (skipMasking) + return [target, data]; + if (merge3) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + close(code, data, mask, cb) { + let buf; + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== "number" || !isValidStatusCode(code)) { + throw new TypeError("First argument must be a valid error code number"); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + if (length > 123) { + throw new RangeError("The message must not be greater than 123 bytes"); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + if (typeof data === "string") { + buf.write(data, 2); + } else if (isUint8Array(data)) { + buf.set(data, 2); + } else { + throw new TypeError("Second argument must be a string or a Uint8Array"); } } + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 8, + readOnly: false, + rsv1: false + }; + if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } } - return t; - }; - const Nouns = { - regex: "vnos", - email: "e-poštni naslov", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum in čas", - date: "ISO datum", - time: "ISO čas", - duration: "ISO trajanje", - ipv4: "IPv4 naslov", - ipv6: "IPv6 naslov", - cidrv4: "obseg IPv4", - cidrv6: "obseg IPv6", - base64: "base64 kodiran niz", - base64url: "base64url kodiran niz", - json_string: "JSON niz", - e164: "E.164 številka", - jwt: "JWT", - template_literal: "vnos" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Neveljaven vnos: pričakovano ${issue3.expected}, prejeto ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Neveljaven vnos: pričakovano ${stringifyPrimitive2(issue3.values[0])}`; - return `Neveljavna možnost: pričakovano eno izmed ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Preveliko: pričakovano, da bo ${issue3.origin ?? "vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementov"}`; - return `Preveliko: pričakovano, da bo ${issue3.origin ?? "vrednost"} ${adj}${issue3.maximum.toString()}`; + ping(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Premajhno: pričakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Premajhno: pričakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 9, + readOnly, + rsv1: false + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); } - if (_issue.format === "ends_with") - return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; - return `Neveljaven ${Nouns[_issue.format] ?? issue3.format}`; + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); } - case "not_multiple_of": - return `Neveljavno število: mora biti večkratnik ${issue3.divisor}`; - case "unrecognized_keys": - return `Neprepoznan${issue3.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Neveljaven ključ v ${issue3.origin}`; - case "invalid_union": - return "Neveljaven vnos"; - case "invalid_element": - return `Neveljavna vrednost v ${issue3.origin}`; - default: - return "Neveljaven vnos"; } - }; -}; -var init_sl2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/sv.js -function sv_default2() { - return { - localeError: error82() - }; -} -var error82 = () => { - const Sizable = { - string: { unit: "tecken", verb: "att ha" }, - file: { unit: "bytes", verb: "att ha" }, - array: { unit: "objekt", verb: "att innehålla" }, - set: { unit: "objekt", verb: "att innehålla" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "antal"; + pong(data, mask, cb) { + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; } - case "object": { - if (Array.isArray(data)) { - return "lista"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + if (byteLength > 125) { + throw new RangeError("The data size must not be greater than 125 bytes"); + } + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 10, + readOnly, + rsv1: false + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, false, options, cb]); + } else { + this.getBlobData(data, false, options, cb); } + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); } } - return t; - }; - const Nouns = { - regex: "reguljärt uttryck", - email: "e-postadress", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datum och tid", - date: "ISO-datum", - time: "ISO-tid", - duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodad sträng", - base64url: "base64url-kodad sträng", - json_string: "JSON-sträng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "mall-literal" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Ogiltig inmatning: förväntat ${issue3.expected}, fick ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Ogiltig inmatning: förväntat ${stringifyPrimitive2(issue3.values[0])}`; - return `Ogiltigt val: förväntade en av ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `För stor(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`; - } - return `För stor(t): förväntat ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.maximum.toString()}`; + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + let byteLength; + let readOnly; + if (typeof data === "string") { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else if (isBlob(data)) { + byteLength = data.size; + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `För lite(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) { + rsv1 = byteLength >= perMessageDeflate._threshold; } - return `För lite(t): förväntade ${issue3.origin ?? "värdet"} att ha ${adj}${issue3.minimum.toString()}`; + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; + if (options.fin) + this._firstFragment = true; + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + if (isBlob(data)) { + if (this._state !== DEFAULT) { + this.enqueue([this.getBlobData, data, this._compress, opts, cb]); + } else { + this.getBlobData(data, this._compress, opts, cb); } - if (_issue.format === "ends_with") - return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; - return `Ogiltig(t) ${Nouns[_issue.format] ?? issue3.format}`; + } else if (this._state !== DEFAULT) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); } - case "not_multiple_of": - return `Ogiltigt tal: måste vara en multipel av ${issue3.divisor}`; - case "unrecognized_keys": - return `${issue3.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Ogiltig nyckel i ${issue3.origin ?? "värdet"}`; - case "invalid_union": - return "Ogiltig input"; - case "invalid_element": - return `Ogiltigt värde i ${issue3.origin ?? "värdet"}`; - default: - return `Ogiltig input`; } - }; -}; -var init_sv2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ta.js -function ta_default2() { - return { - localeError: error83() - }; -} -var error83 = () => { - const Sizable = { - string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, - file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, - array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, - set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; - } - case "object": { - if (Array.isArray(data)) { - return "அணி"; + getBlobData(blob, compress, options, cb) { + this._bufferedBytes += options[kByteLength]; + this._state = GET_BLOB_DATA; + blob.arrayBuffer().then((arrayBuffer) => { + if (this._socket.destroyed) { + const err = new Error("The socket was closed while the blob was being read"); + process.nextTick(callCallbacks, this, err, cb); + return; } - if (data === null) { - return "வெறுமை"; + this._bufferedBytes -= options[kByteLength]; + const data = toBuffer(arrayBuffer); + if (!compress) { + this._state = DEFAULT; + this.sendFrame(Sender.frame(data, options), cb); + this.dequeue(); + } else { + this.dispatch(data, compress, options, cb); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + }).catch((err) => { + process.nextTick(onError2, this, err, cb); + }); + } + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + this._bufferedBytes += options[kByteLength]; + this._state = DEFLATING; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error("The socket was closed while data was being compressed"); + callCallbacks(this, err, cb); + return; } + this._bufferedBytes -= options[kByteLength]; + this._state = DEFAULT; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + dequeue() { + while (this._state === DEFAULT && this._queue.length) { + const params = this._queue.shift(); + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); } } - return t; - }; - const Nouns = { - regex: "உள்ளீடு", - email: "மின்னஞ்சல் முகவரி", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO தேதி நேரம்", - date: "ISO தேதி", - time: "ISO நேரம்", - duration: "ISO கால அளவு", - ipv4: "IPv4 முகவரி", - ipv6: "IPv6 முகவரி", - cidrv4: "IPv4 வரம்பு", - cidrv6: "IPv6 வரம்பு", - base64: "base64-encoded சரம்", - base64url: "base64url-encoded சரம்", - json_string: "JSON சரம்", - e164: "E.164 எண்", - jwt: "JWT", - template_literal: "input" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue3.expected}, பெறப்பட்டது ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive2(issue3.values[0])}`; - return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues2(issue3.values, "|")} இல் ஒன்று`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin ?? "மதிப்பு"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; - } - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin ?? "மதிப்பு"} ${adj}${issue3.maximum.toString()} ஆக இருக்க வேண்டும்`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; - } - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ஆக இருக்க வேண்டும்`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; - if (_issue.format === "ends_with") - return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; - if (_issue.format === "includes") - return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; - if (_issue.format === "regex") - return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; - return `தவறான ${Nouns[_issue.format] ?? issue3.format}`; + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); } - case "not_multiple_of": - return `தவறான எண்: ${issue3.divisor} இன் பலமாக இருக்க வேண்டும்`; - case "unrecognized_keys": - return `அடையாளம் தெரியாத விசை${issue3.keys.length > 1 ? "கள்" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `${issue3.origin} இல் தவறான விசை`; - case "invalid_union": - return "தவறான உள்ளீடு"; - case "invalid_element": - return `${issue3.origin} இல் தவறான மதிப்பு`; - default: - return `தவறான உள்ளீடு`; } - }; -}; -var init_ta2 = __esm(() => { - init_util3(); + } + module.exports = Sender; + function callCallbacks(sender, err, cb) { + if (typeof cb === "function") + cb(err); + for (let i = 0;i < sender._queue.length; i++) { + const params = sender._queue[i]; + const callback = params[params.length - 1]; + if (typeof callback === "function") + callback(err); + } + } + function onError2(sender, err, cb) { + callCallbacks(sender, err, cb); + sender.onerror(err); + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/th.js -function th_default2() { - return { - localeError: error84() - }; -} -var error84 = () => { - const Sizable = { - string: { unit: "ตัวอักษร", verb: "ควรมี" }, - file: { unit: "ไบต์", verb: "ควรมี" }, - array: { unit: "รายการ", verb: "ควรมี" }, - set: { unit: "รายการ", verb: "ควรมี" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js +var require_event_target = __commonJS((exports, module) => { + var { kForOnEventAttribute, kListener } = require_constants4(); + var kCode = Symbol("kCode"); + var kData = Symbol("kData"); + var kError = Symbol("kError"); + var kMessage = Symbol("kMessage"); + var kReason = Symbol("kReason"); + var kTarget = Symbol("kTarget"); + var kType = Symbol("kType"); + var kWasClean = Symbol("kWasClean"); + + class Event { + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + get target() { + return this[kTarget]; + } + get type() { + return this[kType]; + } } - const parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; - } - case "object": { - if (Array.isArray(data)) { - return "อาร์เรย์ (Array)"; - } - if (data === null) { - return "ไม่มีค่า (null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } + Object.defineProperty(Event.prototype, "target", { enumerable: true }); + Object.defineProperty(Event.prototype, "type", { enumerable: true }); + + class CloseEvent extends Event { + constructor(type, options = {}) { + super(type); + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? "" : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; } - return t; - }; - const Nouns = { - regex: "ข้อมูลที่ป้อน", - email: "ที่อยู่อีเมล", - url: "URL", - emoji: "อิโมจิ", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "วันที่เวลาแบบ ISO", - date: "วันที่แบบ ISO", - time: "เวลาแบบ ISO", - duration: "ช่วงเวลาแบบ ISO", - ipv4: "ที่อยู่ IPv4", - ipv6: "ที่อยู่ IPv6", - cidrv4: "ช่วง IP แบบ IPv4", - cidrv6: "ช่วง IP แบบ IPv6", - base64: "ข้อความแบบ Base64", - base64url: "ข้อความแบบ Base64 สำหรับ URL", - json_string: "ข้อความแบบ JSON", - e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", - jwt: "โทเคน JWT", - template_literal: "ข้อมูลที่ป้อน" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue3.expected} แต่ได้รับ ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive2(issue3.values[0])}`; - return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "ไม่เกิน" : "น้อยกว่า"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `เกินกำหนด: ${issue3.origin ?? "ค่า"} ควรมี${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "รายการ"}`; - return `เกินกำหนด: ${issue3.origin ?? "ค่า"} ควรมี${adj} ${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? "อย่างน้อย" : "มากกว่า"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()} ${sizing.unit}`; - } - return `น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; - if (_issue.format === "includes") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; - if (_issue.format === "regex") - return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; - return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue3.format}`; - } - case "not_multiple_of": - return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue3.divisor} ได้ลงตัว`; - case "unrecognized_keys": - return `พบคีย์ที่ไม่รู้จัก: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `คีย์ไม่ถูกต้องใน ${issue3.origin}`; - case "invalid_union": - return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; - case "invalid_element": - return `ข้อมูลไม่ถูกต้องใน ${issue3.origin}`; - default: - return `ข้อมูลไม่ถูกต้อง`; + get code() { + return this[kCode]; } - }; -}; -var init_th2 = __esm(() => { - init_util3(); -}); + get reason() { + return this[kReason]; + } + get wasClean() { + return this[kWasClean]; + } + } + Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true }); + Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/tr.js -function tr_default2() { - return { - localeError: error85() - }; -} -var parsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; + class ErrorEvent extends Event { + constructor(type, options = {}) { + super(type); + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? "" : options.message; } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + get error() { + return this[kError]; + } + get message() { + return this[kMessage]; } } - return t; -}, error85 = () => { - const Sizable = { - string: { unit: "karakter", verb: "olmalı" }, - file: { unit: "bayt", verb: "olmalı" }, - array: { unit: "öğe", verb: "olmalı" }, - set: { unit: "öğe", verb: "olmalı" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; + Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true }); + Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true }); + + class MessageEvent extends Event { + constructor(type, options = {}) { + super(type); + this[kData] = options.data === undefined ? null : options.data; + } + get data() { + return this[kData]; + } } - const Nouns = { - regex: "girdi", - email: "e-posta adresi", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO tarih ve saat", - date: "ISO tarih", - time: "ISO saat", - duration: "ISO süre", - ipv4: "IPv4 adresi", - ipv6: "IPv6 adresi", - cidrv4: "IPv4 aralığı", - cidrv6: "IPv6 aralığı", - base64: "base64 ile şifrelenmiş metin", - base64url: "base64url ile şifrelenmiş metin", - json_string: "JSON dizesi", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "Şablon dizesi" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Geçersiz değer: beklenen ${issue3.expected}, alınan ${parsedType4(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Geçersiz değer: beklenen ${stringifyPrimitive2(issue3.values[0])}`; - return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Çok büyük: beklenen ${issue3.origin ?? "değer"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "öğe"}`; - return `Çok büyük: beklenen ${issue3.origin ?? "değer"} ${adj}${issue3.maximum.toString()}`; + Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true }); + var EventTarget = { + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) { + return; + } } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - return `Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + let wrapper; + if (type === "message") { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent("message", { + data: isBinary ? data : data.toString() + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "close") { + wrapper = function onClose(code, message) { + const event = new CloseEvent("close", { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "error") { + wrapper = function onError2(error90) { + const event = new ErrorEvent("error", { + error: error90, + message: error90.message + }); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === "open") { + wrapper = function onOpen() { + const event = new Event("open"); + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; - if (_issue.format === "ends_with") - return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; - if (_issue.format === "includes") - return `Geçersiz metin: "${_issue.includes}" içermeli`; - if (_issue.format === "regex") - return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; - return `Geçersiz ${Nouns[_issue.format] ?? issue3.format}`; + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } } - case "not_multiple_of": - return `Geçersiz sayı: ${issue3.divisor} ile tam bölünebilmeli`; - case "unrecognized_keys": - return `Tanınmayan anahtar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `${issue3.origin} içinde geçersiz anahtar`; - case "invalid_union": - return "Geçersiz değer"; - case "invalid_element": - return `${issue3.origin} içinde geçersiz değer`; - default: - return `Geçersiz değer`; } }; -}; -var init_tr2 = __esm(() => { - init_util3(); + module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent + }; + function callListener(listener, thisArg, event) { + if (typeof listener === "object" && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ua.js -function ua_default2() { - return { - localeError: error86() - }; -} -var error86 = () => { - const Sizable = { - string: { unit: "символів", verb: "матиме" }, - file: { unit: "байтів", verb: "матиме" }, - array: { unit: "елементів", verb: "матиме" }, - set: { unit: "елементів", verb: "матиме" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js +var require_extension = __commonJS((exports, module) => { + var { tokenChars } = require_validation(); + function push2(dest, name, elem) { + if (dest[name] === undefined) + dest[name] = [elem]; + else + dest[name].push(elem); } - const parsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "число"; - } - case "object": { - if (Array.isArray(data)) { - return "масив"; + function parse16(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + for (;i < header.length; i++) { + code = header.charCodeAt(i); + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + const name = header.slice(start, end); + if (code === 44) { + push2(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); } - if (data === null) { - return "null"; + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (code === 32 || code === 9) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + push2(params, header.slice(start, end), true); + if (code === 44) { + push2(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + start = end = -1; + } else if (code === 61 && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } else { + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) + start = i; + else if (!mustUnescape) + mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (code === 34 && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 92) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 34 && header.charCodeAt(i - 1) === 61) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (start !== -1 && (code === 32 || code === 9)) { + if (end === -1) + end = i; + } else if (code === 59 || code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ""); + mustUnescape = false; + } + push2(params, paramName, value); + if (code === 44) { + push2(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); } } } - return t; - }; - const Nouns = { - regex: "вхідні дані", - email: "адреса електронної пошти", - url: "URL", - emoji: "емодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "дата та час ISO", - date: "дата ISO", - time: "час ISO", - duration: "тривалість ISO", - ipv4: "адреса IPv4", - ipv6: "адреса IPv6", - cidrv4: "діапазон IPv4", - cidrv6: "діапазон IPv6", - base64: "рядок у кодуванні base64", - base64url: "рядок у кодуванні base64url", - json_string: "рядок JSON", - e164: "номер E.164", - jwt: "JWT", - template_literal: "вхідні дані" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Неправильні вхідні дані: очікується ${issue3.expected}, отримано ${parsedType5(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Неправильні вхідні дані: очікується ${stringifyPrimitive2(issue3.values[0])}`; - return `Неправильна опція: очікується одне з ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Занадто велике: очікується, що ${issue3.origin ?? "значення"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "елементів"}`; - return `Занадто велике: очікується, що ${issue3.origin ?? "значення"} буде ${adj}${issue3.maximum.toString()}`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Занадто мале: очікується, що ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Занадто мале: очікується, що ${issue3.origin} буде ${adj}${issue3.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неправильний рядок: повинен містити "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; - return `Неправильний ${Nouns[_issue.format] ?? issue3.format}`; + if (start === -1 || inQuotes || code === 32 || code === 9) { + throw new SyntaxError("Unexpected end of input"); + } + if (end === -1) + end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push2(offers, token, params); + } else { + if (paramName === undefined) { + push2(params, token, true); + } else if (mustUnescape) { + push2(params, paramName, token.replace(/\\/g, "")); + } else { + push2(params, paramName, token); } - case "not_multiple_of": - return `Неправильне число: повинно бути кратним ${issue3.divisor}`; - case "unrecognized_keys": - return `Нерозпізнаний ключ${issue3.keys.length > 1 ? "і" : ""}: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Неправильний ключ у ${issue3.origin}`; - case "invalid_union": - return "Неправильні вхідні дані"; - case "invalid_element": - return `Неправильне значення у ${issue3.origin}`; - default: - return `Неправильні вхідні дані`; + push2(offers, extensionName, params); } - }; -}; -var init_ua2 = __esm(() => { - init_util3(); + return offers; + } + function format3(extensions) { + return Object.keys(extensions).map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) + configurations = [configurations]; + return configurations.map((params) => { + return [extension].concat(Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) + values = [values]; + return values.map((v) => v === true ? k : `${k}=${v}`).join("; "); + })).join("; "); + }).join(", "); + }).join(", "); + } + module.exports = { format: format3, parse: parse16 }; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/ur.js -function ur_default2() { - return { - localeError: error87() - }; -} -var error87 = () => { - const Sizable = { - string: { unit: "حروف", verb: "ہونا" }, - file: { unit: "بائٹس", verb: "ہونا" }, - array: { unit: "آئٹمز", verb: "ہونا" }, - set: { unit: "آئٹمز", verb: "ہونا" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "نمبر"; - } - case "object": { - if (Array.isArray(data)) { - return "آرے"; - } - if (data === null) { - return "نل"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js +var require_websocket = __commonJS((exports, module) => { + var EventEmitter2 = __require("events"); + var https = __require("https"); + var http = __require("http"); + var net = __require("net"); + var tls = __require("tls"); + var { randomBytes, createHash: createHash4 } = __require("crypto"); + var { Duplex, Readable: Readable2 } = __require("stream"); + var { URL: URL5 } = __require("url"); + var PerMessageDeflate = require_permessage_deflate(); + var Receiver = require_receiver(); + var Sender = require_sender(); + var { isBlob } = require_validation(); + var { + BINARY_TYPES, + CLOSE_TIMEOUT, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP + } = require_constants4(); + var { + EventTarget: { addEventListener: addEventListener2, removeEventListener } + } = require_event_target(); + var { format: format3, parse: parse16 } = require_extension(); + var { toBuffer } = require_buffer_util(); + var kAborted = Symbol("kAborted"); + var protocolVersions = [8, 13]; + var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"]; + var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + + class WebSocket2 extends EventEmitter2 { + constructor(address, protocols, options) { + super(); + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._errorEmitted = false; + this._extensions = {}; + this._paused = false; + this._protocol = ""; + this._readyState = WebSocket2.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === "object" && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } } + initAsClient(this, address, protocols, options); + } else { + this._autoPong = options.autoPong; + this._closeTimeout = options.closeTimeout; + this._isServer = true; } } - return t; - }; - const Nouns = { - regex: "ان پٹ", - email: "ای میل ایڈریس", - url: "یو آر ایل", - emoji: "ایموجی", - uuid: "یو یو آئی ڈی", - uuidv4: "یو یو آئی ڈی وی 4", - uuidv6: "یو یو آئی ڈی وی 6", - nanoid: "نینو آئی ڈی", - guid: "جی یو آئی ڈی", - cuid: "سی یو آئی ڈی", - cuid2: "سی یو آئی ڈی 2", - ulid: "یو ایل آئی ڈی", - xid: "ایکس آئی ڈی", - ksuid: "کے ایس یو آئی ڈی", - datetime: "آئی ایس او ڈیٹ ٹائم", - date: "آئی ایس او تاریخ", - time: "آئی ایس او وقت", - duration: "آئی ایس او مدت", - ipv4: "آئی پی وی 4 ایڈریس", - ipv6: "آئی پی وی 6 ایڈریس", - cidrv4: "آئی پی وی 4 رینج", - cidrv6: "آئی پی وی 6 رینج", - base64: "بیس 64 ان کوڈڈ سٹرنگ", - base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", - json_string: "جے ایس او این سٹرنگ", - e164: "ای 164 نمبر", - jwt: "جے ڈبلیو ٹی", - template_literal: "ان پٹ" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `غلط ان پٹ: ${issue3.expected} متوقع تھا، ${parsedType5(issue3.input)} موصول ہوا`; - case "invalid_value": - if (issue3.values.length === 1) - return `غلط ان پٹ: ${stringifyPrimitive2(issue3.values[0])} متوقع تھا`; - return `غلط آپشن: ${joinValues2(issue3.values, "|")} میں سے ایک متوقع تھا`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `بہت بڑا: ${issue3.origin ?? "ویلیو"} کے ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; - return `بہت بڑا: ${issue3.origin ?? "ویلیو"} کا ${adj}${issue3.maximum.toString()} ہونا متوقع تھا`; - } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `بہت چھوٹا: ${issue3.origin} کے ${adj}${issue3.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; - } - return `بہت چھوٹا: ${issue3.origin} کا ${adj}${issue3.minimum.toString()} ہونا متوقع تھا`; + get binaryType() { + return this._binaryType; + } + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) + return; + this._binaryType = type; + if (this._receiver) + this._receiver._binaryType = type; + } + get bufferedAmount() { + if (!this._socket) + return this._bufferedAmount; + return this._socket._writableState.length + this._sender._bufferedBytes; + } + get extensions() { + return Object.keys(this._extensions).join(); + } + get isPaused() { + return this._paused; + } + get onclose() { + return null; + } + get onerror() { + return null; + } + get onopen() { + return null; + } + get onmessage() { + return null; + } + get protocol() { + return this._protocol; + } + get readyState() { + return this._readyState; + } + get url() { + return this._url; + } + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowSynchronousEvents: options.allowSynchronousEvents, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxBufferedChunks: options.maxBufferedChunks, + maxFragments: options.maxFragments, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + const sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._sender = sender; + this._socket = socket; + receiver[kWebSocket] = this; + sender[kWebSocket] = this; + socket[kWebSocket] = this; + receiver.on("conclude", receiverOnConclude); + receiver.on("drain", receiverOnDrain); + receiver.on("error", receiverOnError); + receiver.on("message", receiverOnMessage); + receiver.on("ping", receiverOnPing); + receiver.on("pong", receiverOnPong); + sender.onerror = senderOnError; + if (socket.setTimeout) + socket.setTimeout(0); + if (socket.setNoDelay) + socket.setNoDelay(); + if (head.length > 0) + socket.unshift(head); + socket.on("close", socketOnClose); + socket.on("data", socketOnData); + socket.on("end", socketOnEnd); + socket.on("error", socketOnError); + this._readyState = WebSocket2.OPEN; + this.emit("open"); + } + emitClose() { + if (!this._socket) { + this._readyState = WebSocket2.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); + return; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; - } - if (_issue.format === "ends_with") - return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; - if (_issue.format === "includes") - return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; - if (_issue.format === "regex") - return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; - return `غلط ${Nouns[_issue.format] ?? issue3.format}`; + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); } - case "not_multiple_of": - return `غلط نمبر: ${issue3.divisor} کا مضاعف ہونا چاہیے`; - case "unrecognized_keys": - return `غیر تسلیم شدہ کی${issue3.keys.length > 1 ? "ز" : ""}: ${joinValues2(issue3.keys, "، ")}`; - case "invalid_key": - return `${issue3.origin} میں غلط کی`; - case "invalid_union": - return "غلط ان پٹ"; - case "invalid_element": - return `${issue3.origin} میں غلط ویلیو`; - default: - return `غلط ان پٹ`; + this._receiver.removeAllListeners(); + this._readyState = WebSocket2.CLOSED; + this.emit("close", this._closeCode, this._closeMessage); } - }; -}; -var init_ur2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/vi.js -function vi_default2() { - return { - localeError: error88() - }; -} -var error88 = () => { - const Sizable = { - string: { unit: "ký tự", verb: "có" }, - file: { unit: "byte", verb: "có" }, - array: { unit: "phần tử", verb: "có" }, - set: { unit: "phần tử", verb: "có" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "số"; + close(code, data) { + if (this.readyState === WebSocket2.CLOSED) + return; + if (this.readyState === WebSocket2.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; } - case "object": { - if (Array.isArray(data)) { - return "mảng"; - } - if (data === null) { - return "null"; + if (this.readyState === WebSocket2.CLOSING) { + if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) { + this._socket.end(); } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + return; + } + this._readyState = WebSocket2.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + if (err) + return; + this._closeFrameSent = true; + if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) { + this._socket.end(); } + }); + setCloseTimer(this); + } + pause() { + if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) { + return; } + this._paused = true; + this._socket.pause(); } - return t; - }; - const Nouns = { - regex: "đầu vào", - email: "địa chỉ email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ngày giờ ISO", - date: "ngày ISO", - time: "giờ ISO", - duration: "khoảng thời gian ISO", - ipv4: "địa chỉ IPv4", - ipv6: "địa chỉ IPv6", - cidrv4: "dải IPv4", - cidrv6: "dải IPv6", - base64: "chuỗi mã hóa base64", - base64url: "chuỗi mã hóa base64url", - json_string: "chuỗi JSON", - e164: "số E.164", - jwt: "JWT", - template_literal: "đầu vào" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `Đầu vào không hợp lệ: mong đợi ${issue3.expected}, nhận được ${parsedType5(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive2(issue3.values[0])}`; - return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `Quá lớn: mong đợi ${issue3.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "phần tử"}`; - return `Quá lớn: mong đợi ${issue3.origin ?? "giá trị"} ${adj}${issue3.maximum.toString()}`; + ping(data, mask, cb) { + if (this.readyState === WebSocket2.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `Quá nhỏ: mong đợi ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `Quá nhỏ: mong đợi ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + if (typeof data === "function") { + cb = data; + data = mask = undefined; + } else if (typeof mask === "function") { + cb = mask; + mask = undefined; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue3.format} không hợp lệ`; + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket2.OPEN) { + sendAfterClose(this, data, cb); + return; } - case "not_multiple_of": - return `Số không hợp lệ: phải là bội số của ${issue3.divisor}`; - case "unrecognized_keys": - return `Khóa không được nhận dạng: ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `Khóa không hợp lệ trong ${issue3.origin}`; - case "invalid_union": - return "Đầu vào không hợp lệ"; - case "invalid_element": - return `Giá trị không hợp lệ trong ${issue3.origin}`; - default: - return `Đầu vào không hợp lệ`; + if (mask === undefined) + mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); } - }; -}; -var init_vi2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-CN.js -function zh_CN_default2() { - return { - localeError: error89() - }; -} -var error89 = () => { - const Sizable = { - string: { unit: "字符", verb: "包含" }, - file: { unit: "字节", verb: "包含" }, - array: { unit: "项", verb: "包含" }, - set: { unit: "项", verb: "包含" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "非数字(NaN)" : "数字"; + pong(data, mask, cb) { + if (this.readyState === WebSocket2.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } - case "object": { - if (Array.isArray(data)) { - return "数组"; - } - if (data === null) { - return "空值(null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } + if (typeof data === "function") { + cb = data; + data = mask = undefined; + } else if (typeof mask === "function") { + cb = mask; + mask = undefined; + } + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket2.OPEN) { + sendAfterClose(this, data, cb); + return; } + if (mask === undefined) + mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); } - return t; - }; - const Nouns = { - regex: "输入", - email: "电子邮件", - url: "URL", - emoji: "表情符号", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日期时间", - date: "ISO日期", - time: "ISO时间", - duration: "ISO时长", - ipv4: "IPv4地址", - ipv6: "IPv6地址", - cidrv4: "IPv4网段", - cidrv6: "IPv6网段", - base64: "base64编码字符串", - base64url: "base64url编码字符串", - json_string: "JSON字符串", - e164: "E.164号码", - jwt: "JWT", - template_literal: "输入" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `无效输入:期望 ${issue3.expected},实际接收 ${parsedType5(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `无效输入:期望 ${stringifyPrimitive2(issue3.values[0])}`; - return `无效选项:期望以下之一 ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `数值过大:期望 ${issue3.origin ?? "值"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "个元素"}`; - return `数值过大:期望 ${issue3.origin ?? "值"} ${adj}${issue3.maximum.toString()}`; + resume() { + if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) { + return; } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`; - } - return `数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()}`; + this._paused = false; + if (!this._receiver._writableState.needDrain) + this._socket.resume(); + } + send(data, options, cb) { + if (this.readyState === WebSocket2.CONNECTING) { + throw new Error("WebSocket is not open: readyState 0 (CONNECTING)"); } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") - return `无效字符串:必须以 "${_issue.prefix}" 开头`; - if (_issue.format === "ends_with") - return `无效字符串:必须以 "${_issue.suffix}" 结尾`; - if (_issue.format === "includes") - return `无效字符串:必须包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; - return `无效${Nouns[_issue.format] ?? issue3.format}`; + if (typeof options === "function") { + cb = options; + options = {}; + } + if (typeof data === "number") + data = data.toString(); + if (this.readyState !== WebSocket2.OPEN) { + sendAfterClose(this, data, cb); + return; + } + const opts = { + binary: typeof data !== "string", + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + terminate() { + if (this.readyState === WebSocket2.CLOSED) + return; + if (this.readyState === WebSocket2.CONNECTING) { + const msg = "WebSocket was closed before the connection was established"; + abortHandshake(this, this._req, msg); + return; + } + if (this._socket) { + this._readyState = WebSocket2.CLOSING; + this._socket.destroy(); } - case "not_multiple_of": - return `无效数字:必须是 ${issue3.divisor} 的倍数`; - case "unrecognized_keys": - return `出现未知的键(key): ${joinValues2(issue3.keys, ", ")}`; - case "invalid_key": - return `${issue3.origin} 中的键(key)无效`; - case "invalid_union": - return "无效输入"; - case "invalid_element": - return `${issue3.origin} 中包含无效值(value)`; - default: - return `无效输入`; } - }; -}; -var init_zh_CN2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/zh-TW.js -function zh_TW_default2() { - return { - localeError: error90() - }; -} -var error90 = () => { - const Sizable = { - string: { unit: "字元", verb: "擁有" }, - file: { unit: "位元組", verb: "擁有" }, - array: { unit: "項目", verb: "擁有" }, - set: { unit: "項目", verb: "擁有" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; } - const parsedType5 = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; + Object.defineProperty(WebSocket2, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket2.prototype, "CONNECTING", { + enumerable: true, + value: readyStates.indexOf("CONNECTING") + }); + Object.defineProperty(WebSocket2, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket2.prototype, "OPEN", { + enumerable: true, + value: readyStates.indexOf("OPEN") + }); + Object.defineProperty(WebSocket2, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket2.prototype, "CLOSING", { + enumerable: true, + value: readyStates.indexOf("CLOSING") + }); + Object.defineProperty(WebSocket2, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + Object.defineProperty(WebSocket2.prototype, "CLOSED", { + enumerable: true, + value: readyStates.indexOf("CLOSED") + }); + [ + "binaryType", + "bufferedAmount", + "extensions", + "isPaused", + "protocol", + "readyState", + "url" + ].forEach((property) => { + Object.defineProperty(WebSocket2.prototype, property, { enumerable: true }); + }); + ["open", "error", "close", "message"].forEach((method) => { + Object.defineProperty(WebSocket2.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) + return listener[kListener]; + } + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + if (typeof handler !== "function") + return; + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); } - case "object": { - if (Array.isArray(data)) { - return "array"; + }); + }); + WebSocket2.prototype.addEventListener = addEventListener2; + WebSocket2.prototype.removeEventListener = removeEventListener; + module.exports = WebSocket2; + function initAsClient(websocket, address, protocols, options) { + const opts = { + allowSynchronousEvents: true, + autoPong: true, + closeTimeout: CLOSE_TIMEOUT, + protocolVersion: protocolVersions[1], + maxBufferedChunks: 1024 * 1024, + maxFragments: 128 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: "GET", + host: undefined, + path: undefined, + port: undefined + }; + websocket._autoPong = opts.autoPong; + websocket._closeTimeout = opts.closeTimeout; + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`); + } + let parsedUrl; + if (address instanceof URL5) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL5(address); + } catch { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + if (parsedUrl.protocol === "http:") { + parsedUrl.protocol = "ws:"; + } else if (parsedUrl.protocol === "https:") { + parsedUrl.protocol = "wss:"; + } + websocket._url = parsedUrl.href; + const isSecure = parsedUrl.protocol === "wss:"; + const isIpcUrl = parsedUrl.protocol === "ws+unix:"; + let invalidUrlMessage; + if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) { + invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = "The URL contains a fragment identifier"; + } + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString("base64"); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set; + let perMessageDeflate; + opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect); + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + "Sec-WebSocket-Version": opts.protocolVersion, + "Sec-WebSocket-Key": key, + Connection: "Upgrade", + Upgrade: "websocket" + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate({ + ...opts.perMessageDeflate, + isServer: false, + maxPayload: opts.maxPayload + }); + opts.headers["Sec-WebSocket-Extensions"] = format3({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) { + throw new SyntaxError("An invalid or duplicated subprotocol was specified"); } - if (data === null) { - return "null"; + protocolSet.add(protocol); + } + opts.headers["Sec-WebSocket-Protocol"] = protocols.join(","); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers["Sec-WebSocket-Origin"] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + if (isIpcUrl) { + const parts = opts.path.split(":"); + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + let req; + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host; + const headers = options && options.headers; + options = { ...options, headers: {} }; + if (headers) { + for (const [key2, value] of Object.entries(headers)) { + options.headers[key2.toLowerCase()] = value; + } } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; + } else if (websocket.listenerCount("redirect") === 0) { + const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath; + if (!isSameHost || websocket._originalSecure && !isSecure) { + delete opts.headers.authorization; + delete opts.headers.cookie; + if (!isSameHost) + delete opts.headers.host; + opts.auth = undefined; } } + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64"); + } + req = websocket._req = request(opts); + if (websocket._redirects) { + websocket.emit("redirect", websocket.url, req); + } + } else { + req = websocket._req = request(opts); } - return t; - }; - const Nouns = { - regex: "輸入", - email: "郵件地址", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 日期時間", - date: "ISO 日期", - time: "ISO 時間", - duration: "ISO 期間", - ipv4: "IPv4 位址", - ipv6: "IPv6 位址", - cidrv4: "IPv4 範圍", - cidrv6: "IPv6 範圍", - base64: "base64 編碼字串", - base64url: "base64url 編碼字串", - json_string: "JSON 字串", - e164: "E.164 數值", - jwt: "JWT", - template_literal: "輸入" - }; - return (issue3) => { - switch (issue3.code) { - case "invalid_type": - return `無效的輸入值:預期為 ${issue3.expected},但收到 ${parsedType5(issue3.input)}`; - case "invalid_value": - if (issue3.values.length === 1) - return `無效的輸入值:預期為 ${stringifyPrimitive2(issue3.values[0])}`; - return `無效的選項:預期為以下其中之一 ${joinValues2(issue3.values, "|")}`; - case "too_big": { - const adj = issue3.inclusive ? "<=" : "<"; - const sizing = getSizing(issue3.origin); - if (sizing) - return `數值過大:預期 ${issue3.origin ?? "值"} 應為 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "個元素"}`; - return `數值過大:預期 ${issue3.origin ?? "值"} 應為 ${adj}${issue3.maximum.toString()}`; + if (opts.timeout) { + req.on("timeout", () => { + abortHandshake(websocket, req, "Opening handshake has timed out"); + }); + } + req.on("error", (err) => { + if (req === null || req[kAborted]) + return; + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + req.on("response", (res) => { + const location2 = res.headers.location; + const statusCode = res.statusCode; + if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, "Maximum redirects exceeded"); + return; + } + req.abort(); + let addr; + try { + addr = new URL5(location2, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location2}`); + emitErrorAndClose(websocket, err); + return; + } + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit("unexpected-response", req, res)) { + abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`); } - case "too_small": { - const adj = issue3.inclusive ? ">=" : ">"; - const sizing = getSizing(issue3.origin); - if (sizing) { - return `數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()} ${sizing.unit}`; + }); + req.on("upgrade", (res, socket, head) => { + websocket.emit("upgrade", res); + if (websocket.readyState !== WebSocket2.CONNECTING) + return; + req = websocket._req = null; + const upgrade = res.headers.upgrade; + if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") { + abortHandshake(websocket, socket, "Invalid Upgrade header"); + return; + } + const digest = createHash4("sha1").update(key + GUID).digest("base64"); + if (res.headers["sec-websocket-accept"] !== digest) { + abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header"); + return; + } + const serverProt = res.headers["sec-websocket-protocol"]; + let protError; + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = "Server sent a subprotocol but none was requested"; + } else if (!protocolSet.has(serverProt)) { + protError = "Server sent an invalid subprotocol"; } - return `數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()}`; + } else if (protocolSet.size) { + protError = "Server sent no subprotocol"; } - case "invalid_format": { - const _issue = issue3; - if (_issue.format === "starts_with") { - return `無效的字串:必須以 "${_issue.prefix}" 開頭`; + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + if (serverProt) + websocket._protocol = serverProt; + const secWebSocketExtensions = res.headers["sec-websocket-extensions"]; + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested"; + abortHandshake(websocket, socket, message); + return; } - if (_issue.format === "ends_with") - return `無效的字串:必須以 "${_issue.suffix}" 結尾`; - if (_issue.format === "includes") - return `無效的字串:必須包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `無效的字串:必須符合格式 ${_issue.pattern}`; - return `無效的 ${Nouns[_issue.format] ?? issue3.format}`; + let extensions; + try { + extensions = parse16(secWebSocketExtensions); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + const extensionNames = Object.keys(extensions); + if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) { + const message = "Server indicated an extension that was not requested"; + abortHandshake(websocket, socket, message); + return; + } + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = "Invalid Sec-WebSocket-Extensions header"; + abortHandshake(websocket, socket, message); + return; + } + websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; } - case "not_multiple_of": - return `無效的數字:必須為 ${issue3.divisor} 的倍數`; - case "unrecognized_keys": - return `無法識別的鍵值${issue3.keys.length > 1 ? "們" : ""}:${joinValues2(issue3.keys, "、")}`; - case "invalid_key": - return `${issue3.origin} 中有無效的鍵值`; - case "invalid_union": - return "無效的輸入值"; - case "invalid_element": - return `${issue3.origin} 中有無效的值`; - default: - return `無效的輸入值`; + websocket.setSocket(socket, head, { + allowSynchronousEvents: opts.allowSynchronousEvents, + generateMask: opts.generateMask, + maxBufferedChunks: opts.maxBufferedChunks, + maxFragments: opts.maxFragments, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); } - }; -}; -var init_zh_TW2 = __esm(() => { - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/index.js -var exports_locales2 = {}; -__export(exports_locales2, { - zhTW: () => zh_TW_default2, - zhCN: () => zh_CN_default2, - vi: () => vi_default2, - ur: () => ur_default2, - ua: () => ua_default2, - tr: () => tr_default2, - th: () => th_default2, - ta: () => ta_default2, - sv: () => sv_default2, - sl: () => sl_default2, - ru: () => ru_default2, - pt: () => pt_default2, - ps: () => ps_default2, - pl: () => pl_default2, - ota: () => ota_default2, - no: () => no_default2, - nl: () => nl_default2, - ms: () => ms_default2, - mk: () => mk_default2, - ko: () => ko_default2, - kh: () => kh_default2, - ja: () => ja_default2, - it: () => it_default2, - id: () => id_default2, - hu: () => hu_default2, - he: () => he_default2, - frCA: () => fr_CA_default2, - fr: () => fr_default2, - fi: () => fi_default2, - fa: () => fa_default2, - es: () => es_default2, - eo: () => eo_default2, - en: () => en_default3, - de: () => de_default2, - cs: () => cs_default2, - ca: () => ca_default2, - be: () => be_default2, - az: () => az_default2, - ar: () => ar_default2 -}); -var init_locales2 = __esm(() => { - init_ar2(); - init_az2(); - init_be2(); - init_ca2(); - init_cs2(); - init_de2(); - init_en3(); - init_eo2(); - init_es2(); - init_fa2(); - init_fi2(); - init_fr2(); - init_fr_CA2(); - init_he2(); - init_hu2(); - init_id3(); - init_it2(); - init_ja2(); - init_kh2(); - init_ko2(); - init_mk2(); - init_ms2(); - init_nl2(); - init_no2(); - init_ota2(); - init_ps2(); - init_pl2(); - init_pt2(); - init_ru2(); - init_sl2(); - init_sv2(); - init_ta2(); - init_th2(); - init_tr2(); - init_ua2(); - init_ur2(); - init_vi2(); - init_zh_CN2(); - init_zh_TW2(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js -class $ZodRegistry2 { - constructor() { - this._map = new Map; - this._idmap = new Map; } - add(schema, ..._meta) { - const meta3 = _meta[0]; - this._map.set(schema, meta3); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - if (this._idmap.has(meta3.id)) { - throw new Error(`ID ${meta3.id} already exists in the registry`); + function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket2.CLOSING; + websocket._errorEmitted = true; + websocket.emit("error", err); + websocket.emitClose(); + } + function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); + } + function tlsConnect(options) { + options.path = undefined; + if (!options.servername && options.servername !== "") { + options.servername = net.isIP(options.host) ? "" : options.host; + } + return tls.connect(options); + } + function abortHandshake(websocket, stream2, message) { + websocket._readyState = WebSocket2.CLOSING; + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + if (stream2.setHeader) { + stream2[kAborted] = true; + stream2.abort(); + if (stream2.socket && !stream2.socket.destroyed) { + stream2.socket.destroy(); } - this._idmap.set(meta3.id, schema); + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream2.destroy(err); + stream2.once("error", websocket.emit.bind(websocket, "error")); + stream2.once("close", websocket.emitClose.bind(websocket)); } - return this; } - clear() { - this._map = new Map; - this._idmap = new Map; - return this; + function sendAfterClose(websocket, data, cb) { + if (data) { + const length = isBlob(data) ? data.size : toBuffer(data).length; + if (websocket._socket) + websocket._sender._bufferedBytes += length; + else + websocket._bufferedAmount += length; + } + if (cb) { + const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`); + process.nextTick(cb, err); + } } - remove(schema) { - const meta3 = this._map.get(schema); - if (meta3 && typeof meta3 === "object" && "id" in meta3) { - this._idmap.delete(meta3.id); + function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + if (websocket._socket[kWebSocket] === undefined) + return; + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + if (code === 1005) + websocket.close(); + else + websocket.close(code, reason); + } + function receiverOnDrain() { + const websocket = this[kWebSocket]; + if (!websocket.isPaused) + websocket._socket.resume(); + } + function receiverOnError(err) { + const websocket = this[kWebSocket]; + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener("data", socketOnData); + process.nextTick(resume, websocket._socket); + websocket.close(err[kStatusCode]); + } + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); } - this._map.delete(schema); - return this; } - get(schema) { - const p = schema._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - return { ...pm, ...this._map.get(schema) }; + function receiverOnFinish() { + this[kWebSocket].emitClose(); + } + function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit("message", data, isBinary); + } + function receiverOnPing(data) { + const websocket = this[kWebSocket]; + if (websocket._autoPong) + websocket.pong(data, !this._isServer, NOOP); + websocket.emit("ping", data); + } + function receiverOnPong(data) { + this[kWebSocket].emit("pong", data); + } + function resume(stream2) { + stream2.resume(); + } + function senderOnError(err) { + const websocket = this[kWebSocket]; + if (websocket.readyState === WebSocket2.CLOSED) + return; + if (websocket.readyState === WebSocket2.OPEN) { + websocket._readyState = WebSocket2.CLOSING; + setCloseTimer(websocket); + } + this._socket.end(); + if (!websocket._errorEmitted) { + websocket._errorEmitted = true; + websocket.emit("error", err); } - return this._map.get(schema); } - has(schema) { - return this._map.has(schema); + function setCloseTimer(websocket) { + websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout); + } + function socketOnClose() { + const websocket = this[kWebSocket]; + this.removeListener("close", socketOnClose); + this.removeListener("data", socketOnData); + this.removeListener("end", socketOnEnd); + websocket._readyState = WebSocket2.CLOSING; + if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) { + const chunk = this.read(this._readableState.length); + websocket._receiver.write(chunk); + } + websocket._receiver.end(); + this[kWebSocket] = undefined; + clearTimeout(websocket._closeTimer); + if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) { + websocket.emitClose(); + } else { + websocket._receiver.on("error", receiverOnFinish); + websocket._receiver.on("finish", receiverOnFinish); + } + } + function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } + } + function socketOnEnd() { + const websocket = this[kWebSocket]; + websocket._readyState = WebSocket2.CLOSING; + websocket._receiver.end(); + this.end(); + } + function socketOnError() { + const websocket = this[kWebSocket]; + this.removeListener("error", socketOnError); + this.on("error", NOOP); + if (websocket) { + websocket._readyState = WebSocket2.CLOSING; + this.destroy(); + } } -} -function registry3() { - return new $ZodRegistry2; -} -var $output2, $input2, globalRegistry2; -var init_registries2 = __esm(() => { - $output2 = Symbol("ZodOutput"); - $input2 = Symbol("ZodInput"); - globalRegistry2 = /* @__PURE__ */ registry3(); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js -function _string2(Class3, params) { - return new Class3({ - type: "string", - ...normalizeParams2(params) - }); -} -function _coercedString2(Class3, params) { - return new Class3({ - type: "string", - coerce: true, - ...normalizeParams2(params) - }); -} -function _email2(Class3, params) { - return new Class3({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _guid2(Class3, params) { - return new Class3({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _uuid2(Class3, params) { - return new Class3({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _uuidv42(Class3, params) { - return new Class3({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams2(params) - }); -} -function _uuidv62(Class3, params) { - return new Class3({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams2(params) - }); -} -function _uuidv72(Class3, params) { - return new Class3({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams2(params) - }); -} -function _url2(Class3, params) { - return new Class3({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _emoji4(Class3, params) { - return new Class3({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _nanoid2(Class3, params) { - return new Class3({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _cuid3(Class3, params) { - return new Class3({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _cuid22(Class3, params) { - return new Class3({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _ulid2(Class3, params) { - return new Class3({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _xid2(Class3, params) { - return new Class3({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _ksuid2(Class3, params) { - return new Class3({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _ipv42(Class3, params) { - return new Class3({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _ipv62(Class3, params) { - return new Class3({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _cidrv42(Class3, params) { - return new Class3({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _cidrv62(Class3, params) { - return new Class3({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _base642(Class3, params) { - return new Class3({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _base64url2(Class3, params) { - return new Class3({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _e1642(Class3, params) { - return new Class3({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _jwt2(Class3, params) { - return new Class3({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams2(params) - }); -} -function _isoDateTime2(Class3, params) { - return new Class3({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams2(params) - }); -} -function _isoDate2(Class3, params) { - return new Class3({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams2(params) - }); -} -function _isoTime2(Class3, params) { - return new Class3({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams2(params) - }); -} -function _isoDuration2(Class3, params) { - return new Class3({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams2(params) - }); -} -function _number2(Class3, params) { - return new Class3({ - type: "number", - checks: [], - ...normalizeParams2(params) - }); -} -function _coercedNumber2(Class3, params) { - return new Class3({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams2(params) - }); -} -function _int2(Class3, params) { - return new Class3({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams2(params) - }); -} -function _float322(Class3, params) { - return new Class3({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams2(params) - }); -} -function _float642(Class3, params) { - return new Class3({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams2(params) - }); -} -function _int322(Class3, params) { - return new Class3({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams2(params) - }); -} -function _uint322(Class3, params) { - return new Class3({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams2(params) - }); -} -function _boolean2(Class3, params) { - return new Class3({ - type: "boolean", - ...normalizeParams2(params) - }); -} -function _coercedBoolean2(Class3, params) { - return new Class3({ - type: "boolean", - coerce: true, - ...normalizeParams2(params) - }); -} -function _bigint2(Class3, params) { - return new Class3({ - type: "bigint", - ...normalizeParams2(params) - }); -} -function _coercedBigint2(Class3, params) { - return new Class3({ - type: "bigint", - coerce: true, - ...normalizeParams2(params) - }); -} -function _int642(Class3, params) { - return new Class3({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams2(params) - }); -} -function _uint642(Class3, params) { - return new Class3({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams2(params) - }); -} -function _symbol2(Class3, params) { - return new Class3({ - type: "symbol", - ...normalizeParams2(params) - }); -} -function _undefined5(Class3, params) { - return new Class3({ - type: "undefined", - ...normalizeParams2(params) - }); -} -function _null5(Class3, params) { - return new Class3({ - type: "null", - ...normalizeParams2(params) - }); -} -function _any2(Class3) { - return new Class3({ - type: "any" - }); -} -function _unknown2(Class3) { - return new Class3({ - type: "unknown" - }); -} -function _never2(Class3, params) { - return new Class3({ - type: "never", - ...normalizeParams2(params) - }); -} -function _void3(Class3, params) { - return new Class3({ - type: "void", - ...normalizeParams2(params) - }); -} -function _date2(Class3, params) { - return new Class3({ - type: "date", - ...normalizeParams2(params) - }); -} -function _coercedDate2(Class3, params) { - return new Class3({ - type: "date", - coerce: true, - ...normalizeParams2(params) - }); -} -function _nan2(Class3, params) { - return new Class3({ - type: "nan", - ...normalizeParams2(params) - }); -} -function _lt2(value, params) { - return new $ZodCheckLessThan2({ - check: "less_than", - ...normalizeParams2(params), - value, - inclusive: false - }); -} -function _lte2(value, params) { - return new $ZodCheckLessThan2({ - check: "less_than", - ...normalizeParams2(params), - value, - inclusive: true - }); -} -function _gt2(value, params) { - return new $ZodCheckGreaterThan2({ - check: "greater_than", - ...normalizeParams2(params), - value, - inclusive: false - }); -} -function _gte2(value, params) { - return new $ZodCheckGreaterThan2({ - check: "greater_than", - ...normalizeParams2(params), - value, - inclusive: true - }); -} -function _positive2(params) { - return _gt2(0, params); -} -function _negative2(params) { - return _lt2(0, params); -} -function _nonpositive2(params) { - return _lte2(0, params); -} -function _nonnegative2(params) { - return _gte2(0, params); -} -function _multipleOf2(value, params) { - return new $ZodCheckMultipleOf2({ - check: "multiple_of", - ...normalizeParams2(params), - value - }); -} -function _maxSize2(maximum, params) { - return new $ZodCheckMaxSize2({ - check: "max_size", - ...normalizeParams2(params), - maximum - }); -} -function _minSize2(minimum, params) { - return new $ZodCheckMinSize2({ - check: "min_size", - ...normalizeParams2(params), - minimum - }); -} -function _size2(size, params) { - return new $ZodCheckSizeEquals2({ - check: "size_equals", - ...normalizeParams2(params), - size - }); -} -function _maxLength2(maximum, params) { - const ch = new $ZodCheckMaxLength2({ - check: "max_length", - ...normalizeParams2(params), - maximum - }); - return ch; -} -function _minLength2(minimum, params) { - return new $ZodCheckMinLength2({ - check: "min_length", - ...normalizeParams2(params), - minimum - }); -} -function _length2(length, params) { - return new $ZodCheckLengthEquals2({ - check: "length_equals", - ...normalizeParams2(params), - length - }); -} -function _regex2(pattern, params) { - return new $ZodCheckRegex2({ - check: "string_format", - format: "regex", - ...normalizeParams2(params), - pattern - }); -} -function _lowercase2(params) { - return new $ZodCheckLowerCase2({ - check: "string_format", - format: "lowercase", - ...normalizeParams2(params) - }); -} -function _uppercase2(params) { - return new $ZodCheckUpperCase2({ - check: "string_format", - format: "uppercase", - ...normalizeParams2(params) - }); -} -function _includes2(includes, params) { - return new $ZodCheckIncludes2({ - check: "string_format", - format: "includes", - ...normalizeParams2(params), - includes - }); -} -function _startsWith2(prefix, params) { - return new $ZodCheckStartsWith2({ - check: "string_format", - format: "starts_with", - ...normalizeParams2(params), - prefix - }); -} -function _endsWith2(suffix, params) { - return new $ZodCheckEndsWith2({ - check: "string_format", - format: "ends_with", - ...normalizeParams2(params), - suffix - }); -} -function _property2(property, schema, params) { - return new $ZodCheckProperty2({ - check: "property", - property, - schema, - ...normalizeParams2(params) - }); -} -function _mime2(types3, params) { - return new $ZodCheckMimeType2({ - check: "mime_type", - mime: types3, - ...normalizeParams2(params) - }); -} -function _overwrite2(tx) { - return new $ZodCheckOverwrite2({ - check: "overwrite", - tx - }); -} -function _normalize2(form) { - return _overwrite2((input) => input.normalize(form)); -} -function _trim2() { - return _overwrite2((input) => input.trim()); -} -function _toLowerCase2() { - return _overwrite2((input) => input.toLowerCase()); -} -function _toUpperCase2() { - return _overwrite2((input) => input.toUpperCase()); -} -function _array2(Class3, element, params) { - return new Class3({ - type: "array", - element, - ...normalizeParams2(params) - }); -} -function _union2(Class3, options, params) { - return new Class3({ - type: "union", - options, - ...normalizeParams2(params) - }); -} -function _discriminatedUnion2(Class3, discriminator, options, params) { - return new Class3({ - type: "union", - options, - discriminator, - ...normalizeParams2(params) - }); -} -function _intersection2(Class3, left, right) { - return new Class3({ - type: "intersection", - left, - right - }); -} -function _tuple2(Class3, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType2; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class3({ - type: "tuple", - items, - rest, - ...normalizeParams2(params) - }); -} -function _record2(Class3, keyType, valueType, params) { - return new Class3({ - type: "record", - keyType, - valueType, - ...normalizeParams2(params) - }); -} -function _map2(Class3, keyType, valueType, params) { - return new Class3({ - type: "map", - keyType, - valueType, - ...normalizeParams2(params) - }); -} -function _set2(Class3, valueType, params) { - return new Class3({ - type: "set", - valueType, - ...normalizeParams2(params) - }); -} -function _enum3(Class3, values2, params) { - const entries = Array.isArray(values2) ? Object.fromEntries(values2.map((v) => [v, v])) : values2; - return new Class3({ - type: "enum", - entries, - ...normalizeParams2(params) - }); -} -function _nativeEnum2(Class3, entries, params) { - return new Class3({ - type: "enum", - entries, - ...normalizeParams2(params) - }); -} -function _literal2(Class3, value, params) { - return new Class3({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams2(params) - }); -} -function _file2(Class3, params) { - return new Class3({ - type: "file", - ...normalizeParams2(params) - }); -} -function _transform2(Class3, fn) { - return new Class3({ - type: "transform", - transform: fn - }); -} -function _optional2(Class3, innerType) { - return new Class3({ - type: "optional", - innerType - }); -} -function _nullable2(Class3, innerType) { - return new Class3({ - type: "nullable", - innerType - }); -} -function _default4(Class3, innerType, defaultValue) { - return new Class3({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js +var require_stream5 = __commonJS((exports, module) => { + var WebSocket2 = require_websocket(); + var { Duplex } = __require("stream"); + function emitClose(stream2) { + stream2.emit("close"); + } + function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); } - }); -} -function _nonoptional2(Class3, innerType, params) { - return new Class3({ - type: "nonoptional", - innerType, - ...normalizeParams2(params) - }); -} -function _success2(Class3, innerType) { - return new Class3({ - type: "success", - innerType - }); -} -function _catch3(Class3, innerType, catchValue) { - return new Class3({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); -} -function _pipe2(Class3, in_, out) { - return new Class3({ - type: "pipe", - in: in_, - out - }); -} -function _readonly2(Class3, innerType) { - return new Class3({ - type: "readonly", - innerType - }); -} -function _templateLiteral2(Class3, parts, params) { - return new Class3({ - type: "template_literal", - parts, - ...normalizeParams2(params) - }); -} -function _lazy2(Class3, getter) { - return new Class3({ - type: "lazy", - getter - }); -} -function _promise2(Class3, innerType) { - return new Class3({ - type: "promise", - innerType - }); -} -function _custom2(Class3, fn, _params) { - const norm = normalizeParams2(_params); - norm.abort ?? (norm.abort = true); - const schema = new Class3({ - type: "custom", - check: "custom", - fn, - ...norm - }); - return schema; -} -function _refine2(Class3, fn, _params) { - const schema = new Class3({ - type: "custom", - check: "custom", - fn, - ...normalizeParams2(_params) - }); - return schema; -} -function _stringbool2(Classes, _params) { - const params = normalizeParams2(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); - falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v); } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Pipe = Classes.Pipe ?? $ZodPipe2; - const _Boolean = Classes.Boolean ?? $ZodBoolean2; - const _String = Classes.String ?? $ZodString2; - const _Transform = Classes.Transform ?? $ZodTransform2; - const tx = new _Transform({ - type: "transform", - transform: (input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } else if (falsySet.has(data)) { - return false; + function duplexOnError(err) { + this.removeListener("error", duplexOnError); + this.destroy(); + if (this.listenerCount("error") === 0) { + this.emit("error", err); + } + } + function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + ws.on("message", function message(msg, isBinary) { + const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + if (!duplex.push(data)) + ws.pause(); + }); + ws.once("error", function error90(err) { + if (duplex.destroyed) + return; + terminateOnDestroy = false; + duplex.destroy(err); + }); + ws.once("close", function close() { + if (duplex.destroyed) + return; + duplex.push(null); + }); + duplex._destroy = function(err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + let called = false; + ws.once("error", function error90(err2) { + called = true; + callback(err2); + }); + ws.once("close", function close() { + if (!called) + callback(err); + process.nextTick(emitClose, duplex); + }); + if (terminateOnDestroy) + ws.terminate(); + }; + duplex._final = function(callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._final(callback); + }); + return; + } + if (ws._socket === null) + return; + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) + duplex.destroy(); } else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: tx + ws._socket.once("finish", function finish() { + callback(); }); - return {}; + ws.close(); } - }, - error: params.error - }); - const innerPipe = new _Pipe({ - type: "pipe", - in: new _String({ type: "string", error: params.error }), - out: tx, - error: params.error - }); - const outerPipe = new _Pipe({ - type: "pipe", - in: innerPipe, - out: new _Boolean({ - type: "boolean", - error: params.error - }), - error: params.error - }); - return outerPipe; -} -function _stringFormat2(Class3, format3, fnOrRegex, _params = {}) { - const params = normalizeParams2(_params); - const def = { - ...normalizeParams2(_params), - check: "string_format", - type: "string", - format: format3, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; + }; + duplex._read = function() { + if (ws.isPaused) + ws.resume(); + }; + duplex._write = function(chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once("open", function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + ws.send(chunk, callback); + }; + duplex.on("end", duplexOnEnd); + duplex.on("error", duplexOnError); + return duplex; } - const inst = new Class3(def); - return inst; -} -var TimePrecision2; -var init_api2 = __esm(() => { - init_checks3(); - init_schemas3(); - init_util3(); - TimePrecision2 = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6 - }; + module.exports = createWebSocketStream; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/function.js -class $ZodFunction2 { - constructor(def) { - this._def = def; - this.def = def; - } - implement(func) { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - const impl = (...args) => { - const parsedArgs = this._def.input ? parse11(this._def.input, args, undefined, { callee: impl }) : args; - if (!Array.isArray(parsedArgs)) { - throw new Error("Invalid arguments schema: not an array or tuple schema."); +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js +var require_subprotocol = __commonJS((exports, module) => { + var { tokenChars } = require_validation(); + function parse16(header) { + const protocols = new Set; + let start = -1; + let end = -1; + let i = 0; + for (i;i < header.length; i++) { + const code = header.charCodeAt(i); + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) + start = i; + } else if (i !== 0 && (code === 32 || code === 9)) { + if (end === -1 && start !== -1) + end = i; + } else if (code === 44) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (end === -1) + end = i; + const protocol2 = header.slice(start, end); + if (protocols.has(protocol2)) { + throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`); + } + protocols.add(protocol2); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); } - const output = func(...parsedArgs); - return this._def.output ? parse11(this._def.output, output, undefined, { callee: impl }) : output; - }; - return impl; - } - implementAsync(func) { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); } - const impl = async (...args) => { - const parsedArgs = this._def.input ? await parseAsync3(this._def.input, args, undefined, { callee: impl }) : args; - if (!Array.isArray(parsedArgs)) { - throw new Error("Invalid arguments schema: not an array or tuple schema."); - } - const output = await func(...parsedArgs); - return this._def.output ? parseAsync3(this._def.output, output, undefined, { callee: impl }) : output; - }; - return impl; - } - input(...args) { - const F = this.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple2({ - type: "tuple", - items: args[0], - rest: args[1] - }), - output: this._def.output - }); + if (start === -1 || end !== -1) { + throw new SyntaxError("Unexpected end of input"); } - return new F({ - type: "function", - input: args[0], - output: this._def.output - }); - } - output(output) { - const F = this.constructor; - return new F({ - type: "function", - input: this._def.input, - output - }); + const protocol = header.slice(start, i); + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + protocols.add(protocol); + return protocols; } -} -function _function2(params) { - return new $ZodFunction2({ - type: "function", - input: Array.isArray(params?.input) ? _tuple2($ZodTuple2, params?.input) : params?.input ?? _array2($ZodArray2, _unknown2($ZodUnknown2)), - output: params?.output ?? _unknown2($ZodUnknown2) - }); -} -var init_function2 = __esm(() => { - init_api2(); - init_parse6(); - init_schemas3(); - init_schemas3(); + module.exports = { parse: parse16 }; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js -class JSONSchemaGenerator2 { - constructor(params) { - this.counter = 0; - this.metadataRegistry = params?.metadata ?? globalRegistry2; - this.target = params?.target ?? "draft-2020-12"; - this.unrepresentable = params?.unrepresentable ?? "throw"; - this.override = params?.override ?? (() => {}); - this.io = params?.io ?? "output"; - this.seen = new Map; - } - process(schema, _params = { path: [], schemaPath: [] }) { - var _a4; - const def = schema._zod.def; - const formatMap2 = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" - }; - const seen = this.seen.get(schema); - if (seen) { - seen.count++; - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - this.seen.set(schema, result); - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path - }; - const parent = schema._zod.parent; - if (parent) { - result.ref = parent; - this.process(parent, params); - this.seen.get(parent).isParent = true; - } else { - const _json = result.schema; - switch (def.type) { - case "string": { - const json2 = _json; - json2.type = "string"; - const { minimum, maximum, format: format3, patterns, contentEncoding } = schema._zod.bag; - if (typeof minimum === "number") - json2.minLength = minimum; - if (typeof maximum === "number") - json2.maxLength = maximum; - if (format3) { - json2.format = formatMap2[format3] ?? format3; - if (json2.format === "") - delete json2.format; - } - if (contentEncoding) - json2.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json2.pattern = regexes[0].source; - else if (regexes.length > 1) { - result.schema.allOf = [ - ...regexes.map((regex2) => ({ - ...this.target === "draft-7" ? { type: "string" } : {}, - pattern: regex2.source - })) - ]; - } - } - break; - } - case "number": { - const json2 = _json; - const { minimum, maximum, format: format3, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format3 === "string" && format3.includes("int")) - json2.type = "integer"; - else - json2.type = "number"; - if (typeof exclusiveMinimum === "number") - json2.exclusiveMinimum = exclusiveMinimum; - if (typeof minimum === "number") { - json2.minimum = minimum; - if (typeof exclusiveMinimum === "number") { - if (exclusiveMinimum >= minimum) - delete json2.minimum; - else - delete json2.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") - json2.exclusiveMaximum = exclusiveMaximum; - if (typeof maximum === "number") { - json2.maximum = maximum; - if (typeof exclusiveMaximum === "number") { - if (exclusiveMaximum <= maximum) - delete json2.maximum; - else - delete json2.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json2.multipleOf = multipleOf; - break; - } - case "boolean": { - const json2 = _json; - json2.type = "boolean"; - break; - } - case "bigint": { - if (this.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - break; - } - case "symbol": { - if (this.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - break; - } - case "null": { - _json.type = "null"; - break; - } - case "any": { - break; - } - case "unknown": { - break; - } - case "undefined": { - if (this.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - break; - } - case "void": { - if (this.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - break; - } - case "never": { - _json.not = {}; - break; - } - case "date": { - if (this.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - break; - } - case "array": { - const json2 = _json; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - json2.type = "array"; - json2.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); - break; - } - case "object": { - const json2 = _json; - json2.type = "object"; - json2.properties = {}; - const shape = def.shape; - for (const key in shape) { - json2.properties[key] = this.process(shape[key], { - ...params, - path: [...params.path, "properties", key] - }); - } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (this.io === "input") { - return v.optin === undefined; - } else { - return v.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json2.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json2.additionalProperties = false; - } else if (!def.catchall) { - if (this.io === "output") - json2.additionalProperties = false; - } else if (def.catchall) { - json2.additionalProperties = this.process(def.catchall, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - break; - } - case "union": { - const json2 = _json; - json2.anyOf = def.options.map((x, i) => this.process(x, { - ...params, - path: [...params.path, "anyOf", i] - })); - break; - } - case "intersection": { - const json2 = _json; - const a = this.process(def.left, { - ...params, - path: [...params.path, "allOf", 0] - }); - const b = this.process(def.right, { - ...params, - path: [...params.path, "allOf", 1] - }); - const isSimpleIntersection = (val) => ("allOf" in val) && Object.keys(val).length === 1; - const allOf = [ - ...isSimpleIntersection(a) ? a.allOf : [a], - ...isSimpleIntersection(b) ? b.allOf : [b] - ]; - json2.allOf = allOf; - break; - } - case "tuple": { - const json2 = _json; - json2.type = "array"; - const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); - if (this.target === "draft-2020-12") { - json2.prefixItems = prefixItems; - } else { - json2.items = prefixItems; - } - if (def.rest) { - const rest = this.process(def.rest, { - ...params, - path: [...params.path, "items"] - }); - if (this.target === "draft-2020-12") { - json2.items = rest; - } else { - json2.additionalItems = rest; - } - } - if (def.rest) { - json2.items = this.process(def.rest, { - ...params, - path: [...params.path, "items"] - }); - } - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - break; - } - case "record": { - const json2 = _json; - json2.type = "object"; - json2.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); - json2.additionalProperties = this.process(def.valueType, { - ...params, - path: [...params.path, "additionalProperties"] - }); - break; - } - case "map": { - if (this.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - break; - } - case "set": { - if (this.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - break; - } - case "enum": { - const json2 = _json; - const values2 = getEnumValues2(def.entries); - if (values2.every((v) => typeof v === "number")) - json2.type = "number"; - if (values2.every((v) => typeof v === "string")) - json2.type = "string"; - json2.enum = values2; - break; - } - case "literal": { - const json2 = _json; - const vals = []; - for (const val of def.values) { - if (val === undefined) { - if (this.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else {} - } else if (typeof val === "bigint") { - if (this.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } - } else { - vals.push(val); - } - } - if (vals.length === 0) {} else if (vals.length === 1) { - const val = vals[0]; - json2.type = val === null ? "null" : typeof val; - json2.const = val; - } else { - if (vals.every((v) => typeof v === "number")) - json2.type = "number"; - if (vals.every((v) => typeof v === "string")) - json2.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json2.type = "string"; - if (vals.every((v) => v === null)) - json2.type = "null"; - json2.enum = vals; - } - break; - } - case "file": { - const json2 = _json; - const file2 = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file2.minLength = minimum; - if (maximum !== undefined) - file2.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file2.contentMediaType = mime[0]; - Object.assign(json2, file2); - } else { - json2.anyOf = mime.map((m) => { - const mFile = { ...file2, contentMediaType: m }; - return mFile; - }); - } - } else { - Object.assign(json2, file2); - } - break; - } - case "transform": { - if (this.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - break; - } - case "nullable": { - const inner = this.process(def.innerType, params); - _json.anyOf = [inner, { type: "null" }]; - break; - } - case "nonoptional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "success": { - const json2 = _json; - json2.type = "boolean"; - break; - } - case "default": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.default = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "prefault": { - this.process(def.innerType, params); - result.ref = def.innerType; - if (this.io === "input") - _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "catch": { - this.process(def.innerType, params); - result.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - _json.default = catchValue; - break; - } - case "nan": { - if (this.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - break; - } - case "template_literal": { - const json2 = _json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - json2.type = "string"; - json2.pattern = pattern.source; - break; - } - case "pipe": { - const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "readonly": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.readOnly = true; - break; - } - case "promise": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "optional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "lazy": { - const innerType = schema._zod.innerType; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "custom": { - if (this.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - break; +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js +var require_websocket_server = __commonJS((exports, module) => { + var EventEmitter2 = __require("events"); + var http = __require("http"); + var { Duplex } = __require("stream"); + var { createHash: createHash4 } = __require("crypto"); + var extension = require_extension(); + var PerMessageDeflate = require_permessage_deflate(); + var subprotocol = require_subprotocol(); + var WebSocket2 = require_websocket(); + var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants4(); + var keyRegex = /^[+/0-9A-Za-z]{22}==$/; + var RUNNING = 0; + var CLOSING = 1; + var CLOSED = 2; + + class WebSocketServer extends EventEmitter2 { + constructor(options, callback) { + super(); + options = { + allowSynchronousEvents: true, + autoPong: true, + maxBufferedChunks: 1024 * 1024, + maxFragments: 128 * 1024, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + closeTimeout: CLOSE_TIMEOUT, + verifyClient: null, + noServer: false, + backlog: null, + server: null, + host: null, + path: null, + port: null, + WebSocket: WebSocket2, + ...options + }; + if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) { + throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified"); + } + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + res.writeHead(426, { + "Content-Length": body.length, + "Content-Type": "text/plain" + }); + res.end(body); + }); + this._server.listen(options.port, options.host, options.backlog, callback); + } else if (options.server) { + this._server = options.server; + } + if (this._server) { + const emitConnection = this.emit.bind(this, "connection"); + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, "listening"), + error: this.emit.bind(this, "error"), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); } - default: {} - } + }); + } + if (options.perMessageDeflate === true) + options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set; + this._shouldEmitClose = false; } + this.options = options; + this._state = RUNNING; } - const meta3 = this.metadataRegistry.get(schema); - if (meta3) - Object.assign(result.schema, meta3); - if (this.io === "input" && isTransforming2(schema)) { - delete result.schema.examples; - delete result.schema.default; + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + if (!this._server) + return null; + return this._server.address(); } - if (this.io === "input" && result.schema._prefault) - (_a4 = result.schema).default ?? (_a4.default = result.schema._prefault); - delete result.schema._prefault; - const _result = this.seen.get(schema); - return _result.schema; - } - emit(schema, _params) { - const params = { - cycles: _params?.cycles ?? "ref", - reused: _params?.reused ?? "inline", - external: _params?.external ?? undefined - }; - const root = this.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const makeURI = (entry) => { - const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; - if (params.external) { - const externalId = params.external.registry.get(entry[0])?.id; - const uriGenerator = params.external.uri ?? ((id2) => id2); - if (externalId) { - return { ref: uriGenerator(externalId) }; + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once("close", () => { + cb(new Error("The server is not running")); + }); } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${this.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { + process.nextTick(emitClose, this); return; } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema2 = seen.schema; - for (const key in schema2) { - delete schema2[key]; - } - schema2.$ref = ref; - }; - if (params.cycles === "throw") { - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + if (cb) + this.once("close", cb); + if (this._state === CLOSING) + return; + this._state = CLOSING; + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); } + } else { + const server = this._server; + this._removeListeners(); + this._removeListeners = this._server = null; + server.close(() => { + emitClose(this); + }); } } - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (schema === entry[0]) { - extractToDef(entry); - continue; + shouldHandle(req) { + if (this.options.path) { + const index2 = req.url.indexOf("?"); + const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url; + if (pathname !== this.options.path) + return false; } - if (params.external) { - const ext = params.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } + return true; + } + handleUpgrade(req, socket, head, cb) { + socket.on("error", socketOnError); + const key = req.headers["sec-websocket-key"]; + const upgrade = req.headers.upgrade; + const version6 = +req.headers["sec-websocket-version"]; + if (req.method !== "GET") { + const message = "Invalid HTTP method"; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; } - const id = this.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; + if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") { + const message = "Invalid Upgrade header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; } - if (seen.cycle) { - extractToDef(entry); - continue; + if (key === undefined || !keyRegex.test(key)) { + const message = "Missing or invalid Sec-WebSocket-Key header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; } - if (seen.count > 1) { - if (params.reused === "ref") { - extractToDef(entry); - continue; - } + if (version6 !== 13 && version6 !== 8) { + const message = "Missing or invalid Sec-WebSocket-Version header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, { + "Sec-WebSocket-Version": "13, 8" + }); + return; } - } - const flattenRef = (zodSchema, params2) => { - const seen = this.seen.get(zodSchema); - const schema2 = seen.def ?? seen.schema; - const _cached = { ...schema2 }; - if (seen.ref === null) { + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); return; } - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref, params2); - const refSchema = this.seen.get(ref).schema; - if (refSchema.$ref && params2.target === "draft-7") { - schema2.allOf = schema2.allOf ?? []; - schema2.allOf.push(refSchema); - } else { - Object.assign(schema2, refSchema); - Object.assign(schema2, _cached); + const secWebSocketProtocol = req.headers["sec-websocket-protocol"]; + let protocols = new Set; + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = "Invalid Sec-WebSocket-Protocol header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; } } - if (!seen.isParent) - this.override({ - zodSchema, - jsonSchema: schema2, - path: seen.path ?? [] + const secWebSocketExtensions = req.headers["sec-websocket-extensions"]; + const extensions = {}; + if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) { + const perMessageDeflate = new PerMessageDeflate({ + ...this.options.perMessageDeflate, + isServer: true, + maxPayload: this.options.maxPayload }); - }; - for (const entry of [...this.seen.entries()].reverse()) { - flattenRef(entry[0], { target: this.target }); - } - const result = {}; - if (this.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } else if (this.target === "draft-7") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } else { - console.warn(`Invalid target: ${this.target}`); - } - if (params.external?.uri) { - const id = params.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = params.external.uri(id); - } - Object.assign(result, root.def); - const defs = params.external?.defs ?? {}; - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; + try { + const offers = extension.parse(secWebSocketExtensions); + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = "Invalid or unacceptable Sec-WebSocket-Extensions header"; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } } - } - if (params.external) {} else { - if (Object.keys(defs).length > 0) { - if (this.target === "draft-2020-12") { - result.$defs = defs; - } else { - result.definitions = defs; + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version6 === 8 ? "sec-websocket-origin" : "origin"}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + }); + return; } + if (!this.options.verifyClient(info)) + return abortHandshake(socket, 401); } + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); } - try { - return JSON.parse(JSON.stringify(result)); - } catch (_err) { - throw new Error("Error converting schema to JSON."); + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + if (!socket.readable || !socket.writable) + return socket.destroy(); + if (socket[kWebSocket]) { + throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration"); + } + if (this._state > RUNNING) + return abortHandshake(socket, 503); + const digest = createHash4("sha1").update(key + GUID).digest("base64"); + const headers = [ + "HTTP/1.1 101 Switching Protocols", + "Upgrade: websocket", + "Connection: Upgrade", + `Sec-WebSocket-Accept: ${digest}` + ]; + const ws = new this.options.WebSocket(null, undefined, this.options); + if (protocols.size) { + const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value; + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + this.emit("headers", headers, req); + socket.write(headers.concat(`\r +`).join(`\r +`)); + socket.removeListener("error", socketOnError); + ws.setSocket(socket, head, { + allowSynchronousEvents: this.options.allowSynchronousEvents, + maxBufferedChunks: this.options.maxBufferedChunks, + maxFragments: this.options.maxFragments, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + if (this.clients) { + this.clients.add(ws); + ws.on("close", () => { + this.clients.delete(ws); + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + cb(ws, req); } } -} -function toJSONSchema2(input, _params) { - if (input instanceof $ZodRegistry2) { - const gen2 = new JSONSchemaGenerator2(_params); - const defs = {}; - for (const entry of input._idmap.entries()) { - const [_, schema] = entry; - gen2.process(schema); - } - const schemas3 = {}; - const external4 = { - registry: input, - uri: _params?.uri, - defs + module.exports = WebSocketServer; + function addListeners(server, map3) { + for (const event of Object.keys(map3)) + server.on(event, map3[event]); + return function removeListeners() { + for (const event of Object.keys(map3)) { + server.removeListener(event, map3[event]); + } }; - for (const entry of input._idmap.entries()) { - const [key, schema] = entry; - schemas3[key] = gen2.emit(schema, { - ..._params, - external: external4 - }); - } - if (Object.keys(defs).length > 0) { - const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas3.__shared = { - [defsSegment]: defs - }; + } + function emitClose(server) { + server._state = CLOSED; + server.emit("close"); + } + function socketOnError() { + this.destroy(); + } + function abortHandshake(socket, code, message, headers) { + message = message || http.STATUS_CODES[code]; + headers = { + Connection: "close", + "Content-Type": "text/html", + "Content-Length": Buffer.byteLength(message), + ...headers + }; + socket.once("finish", socket.destroy); + socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r +` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r +`) + `\r +\r +` + message); + } + function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) { + if (server.listenerCount("wsClientError")) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + server.emit("wsClientError", err, socket, req); + } else { + abortHandshake(socket, code, message, headers); } - return { schemas: schemas3 }; } - const gen = new JSONSchemaGenerator2(_params); - gen.process(input); - return gen.emit(input, _params); +}); + +// ../../node_modules/.pnpm/ws@8.21.0/node_modules/ws/wrapper.mjs +var exports_wrapper = {}; +__export(exports_wrapper, { + subprotocol: () => import_subprotocol.default, + extension: () => import_extension3.default, + default: () => wrapper_default, + createWebSocketStream: () => import_stream45.default, + WebSocketServer: () => import_websocket_server.default, + WebSocket: () => import_websocket7.default, + Sender: () => import_sender.default, + Receiver: () => import_receiver.default, + PerMessageDeflate: () => import_permessage_deflate.default +}); +var import_stream45, import_extension3, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket7, import_websocket_server, wrapper_default; +var init_wrapper2 = __esm(() => { + import_stream45 = __toESM(require_stream5(), 1); + import_extension3 = __toESM(require_extension(), 1); + import_permessage_deflate = __toESM(require_permessage_deflate(), 1); + import_receiver = __toESM(require_receiver(), 1); + import_sender = __toESM(require_sender(), 1); + import_subprotocol = __toESM(require_subprotocol(), 1); + import_websocket7 = __toESM(require_websocket(), 1); + import_websocket_server = __toESM(require_websocket_server(), 1); + wrapper_default = import_websocket7.default; +}); + +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/ws_execute.js +async function ensureWs() { + try { + const ws = await Promise.resolve().then(() => (init_wrapper2(), exports_wrapper)); + return { WebSocket: ws.default || ws.WebSocket || ws }; + } catch { + throw new Error("WebSocket-based execution requires the 'ws' package. Install it with: npm install ws"); + } } -function isTransforming2(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const schema = _schema; - const def = schema._zod.def; - switch (def.type) { - case "string": - case "number": - case "bigint": - case "boolean": - case "date": - case "symbol": - case "undefined": - case "null": - case "any": - case "unknown": - case "never": - case "void": - case "literal": - case "enum": - case "nan": - case "file": - case "template_literal": - return false; - case "array": { - return isTransforming2(def.element, ctx); - } - case "object": { - for (const key in def.shape) { - if (isTransforming2(def.shape[key], ctx)) - return true; - } - return false; +function buildWsUrl(dataplaneUrl) { + const wsUrl = dataplaneUrl.replace("https://", "wss://").replace("http://", "ws://"); + return `${wsUrl}/execute/ws`; +} +function buildAuthHeaders(apiKey, extraHeaders) { + const headers = {}; + if (apiKey) { + headers["X-Api-Key"] = apiKey; + } + if (extraHeaders) { + Object.assign(headers, extraHeaders); + } + return headers; +} + +class WSStreamControl { + constructor() { + Object.defineProperty(this, "_ws", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "_closed", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_killed", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + _bind(ws) { + this._ws = ws; + } + _unbind() { + this._closed = true; + this._ws = null; + } + get killed() { + return this._killed; + } + sendKill() { + this._killed = true; + if (this._ws && !this._closed && this._ws.readyState === 1) { + this._ws.send(JSON.stringify({ type: "kill" })); } - case "union": { - for (const option of def.options) { - if (isTransforming2(option, ctx)) - return true; - } - return false; + } + sendInput(data) { + if (this._ws && !this._closed && this._ws.readyState === 1) { + this._ws.send(JSON.stringify({ type: "input", data })); } - case "intersection": { - return isTransforming2(def.left, ctx) || isTransforming2(def.right, ctx); + } +} +function raiseForWsError(msg, commandId = "") { + const errorType = msg.error_type ?? "CommandError"; + const errorMsg = msg.error ?? "Unknown error"; + if (errorType === "CommandTimeout") { + throw new LangSmithCommandTimeoutError(errorMsg); + } + if (errorType === "CommandNotFound") { + throw new LangSmithSandboxOperationError(commandId ? `Command not found: ${commandId}` : errorMsg, commandId ? "reconnect" : "command", errorType); + } + if (errorType === "SessionExpired") { + throw new LangSmithSandboxOperationError(commandId ? `Session expired: ${commandId}` : errorMsg, commandId ? "reconnect" : "command", errorType); + } + throw new LangSmithSandboxOperationError(errorMsg, commandId ? "reconnect" : "command", errorType); +} +async function connectWs(url3, headers) { + const { WebSocket: WS } = await ensureWs(); + return new Promise((resolve2, reject) => { + const ws = new WS(url3, { headers }); + ws.on("open", () => { + ws.removeAllListeners("error"); + resolve2(ws); + }); + ws.on("error", (err) => { + ws.removeAllListeners("open"); + reject(new LangSmithSandboxConnectionError(`Failed to connect to sandbox WebSocket: ${err.message}`)); + }); + }); +} +async function* readWsMessages(ws) { + const messageQueue = []; + let resolve2 = null; + let error90 = null; + let done = false; + const onMessage = (data) => { + const raw2 = typeof data === "string" ? data : data.toString(); + const msg = JSON.parse(raw2); + messageQueue.push(msg); + if (resolve2) { + const r = resolve2; + resolve2 = null; + r(); } - case "tuple": { - for (const item of def.items) { - if (isTransforming2(item, ctx)) - return true; - } - if (def.rest && isTransforming2(def.rest, ctx)) - return true; - return false; + }; + const onClose = (code, reason) => { + done = true; + if (code === 1001) { + error90 = new LangSmithSandboxServerReloadError("Server is reloading, reconnect to resume"); + } else if (code !== 1000) { + error90 = new LangSmithSandboxConnectionError(`WebSocket connection closed unexpectedly (code: ${code}, reason: ${reason.toString()})`); } - case "record": { - return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); + if (resolve2) { + const r = resolve2; + resolve2 = null; + r(); } - case "map": { - return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx); + }; + const onError2 = (err) => { + done = true; + if (!error90) { + error90 = new LangSmithSandboxConnectionError(`WebSocket connection error: ${err.message}`); } - case "set": { - return isTransforming2(def.valueType, ctx); + if (resolve2) { + const r = resolve2; + resolve2 = null; + r(); } - case "promise": - case "optional": - case "nonoptional": - case "nullable": - case "readonly": - return isTransforming2(def.innerType, ctx); - case "lazy": - return isTransforming2(def.getter(), ctx); - case "default": { - return isTransforming2(def.innerType, ctx); - } - case "prefault": { - return isTransforming2(def.innerType, ctx); - } - case "custom": { - return false; - } - case "transform": { - return true; - } - case "pipe": { - return isTransforming2(def.in, ctx) || isTransforming2(def.out, ctx); - } - case "success": { - return false; - } - case "catch": { - return false; + }; + ws.on("message", onMessage); + ws.on("close", onClose); + ws.on("error", onError2); + try { + while (true) { + while (messageQueue.length > 0) { + yield messageQueue.shift(); + } + if (done) { + if (error90) { + throw error90; + } + return; + } + await new Promise((r) => { + resolve2 = r; + }); } - default: + } finally { + ws.removeListener("message", onMessage); + ws.removeListener("close", onClose); + ws.removeListener("error", onError2); } - throw new Error(`Unknown schema type: ${def.type}`); -} -var init_to_json_schema2 = __esm(() => { - init_registries2(); - init_util3(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/json-schema.js -var exports_json_schema2 = {}; -var init_json_schema3 = () => {}; - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/index.js -var exports_core4 = {}; -__export(exports_core4, { - version: () => version4, - util: () => exports_util2, - treeifyError: () => treeifyError2, - toJSONSchema: () => toJSONSchema2, - toDotPath: () => toDotPath2, - safeParseAsync: () => safeParseAsync3, - safeParse: () => safeParse3, - registry: () => registry3, - regexes: () => exports_regexes2, - prettifyError: () => prettifyError2, - parseAsync: () => parseAsync3, - parse: () => parse11, - locales: () => exports_locales2, - isValidJWT: () => isValidJWT3, - isValidBase64URL: () => isValidBase64URL2, - isValidBase64: () => isValidBase642, - globalRegistry: () => globalRegistry2, - globalConfig: () => globalConfig2, - function: () => _function2, - formatError: () => formatError3, - flattenError: () => flattenError2, - config: () => config2, - clone: () => clone2, - _xid: () => _xid2, - _void: () => _void3, - _uuidv7: () => _uuidv72, - _uuidv6: () => _uuidv62, - _uuidv4: () => _uuidv42, - _uuid: () => _uuid2, - _url: () => _url2, - _uppercase: () => _uppercase2, - _unknown: () => _unknown2, - _union: () => _union2, - _undefined: () => _undefined5, - _ulid: () => _ulid2, - _uint64: () => _uint642, - _uint32: () => _uint322, - _tuple: () => _tuple2, - _trim: () => _trim2, - _transform: () => _transform2, - _toUpperCase: () => _toUpperCase2, - _toLowerCase: () => _toLowerCase2, - _templateLiteral: () => _templateLiteral2, - _symbol: () => _symbol2, - _success: () => _success2, - _stringbool: () => _stringbool2, - _stringFormat: () => _stringFormat2, - _string: () => _string2, - _startsWith: () => _startsWith2, - _size: () => _size2, - _set: () => _set2, - _safeParseAsync: () => _safeParseAsync2, - _safeParse: () => _safeParse2, - _regex: () => _regex2, - _refine: () => _refine2, - _record: () => _record2, - _readonly: () => _readonly2, - _property: () => _property2, - _promise: () => _promise2, - _positive: () => _positive2, - _pipe: () => _pipe2, - _parseAsync: () => _parseAsync2, - _parse: () => _parse2, - _overwrite: () => _overwrite2, - _optional: () => _optional2, - _number: () => _number2, - _nullable: () => _nullable2, - _null: () => _null5, - _normalize: () => _normalize2, - _nonpositive: () => _nonpositive2, - _nonoptional: () => _nonoptional2, - _nonnegative: () => _nonnegative2, - _never: () => _never2, - _negative: () => _negative2, - _nativeEnum: () => _nativeEnum2, - _nanoid: () => _nanoid2, - _nan: () => _nan2, - _multipleOf: () => _multipleOf2, - _minSize: () => _minSize2, - _minLength: () => _minLength2, - _min: () => _gte2, - _mime: () => _mime2, - _maxSize: () => _maxSize2, - _maxLength: () => _maxLength2, - _max: () => _lte2, - _map: () => _map2, - _lte: () => _lte2, - _lt: () => _lt2, - _lowercase: () => _lowercase2, - _literal: () => _literal2, - _length: () => _length2, - _lazy: () => _lazy2, - _ksuid: () => _ksuid2, - _jwt: () => _jwt2, - _isoTime: () => _isoTime2, - _isoDuration: () => _isoDuration2, - _isoDateTime: () => _isoDateTime2, - _isoDate: () => _isoDate2, - _ipv6: () => _ipv62, - _ipv4: () => _ipv42, - _intersection: () => _intersection2, - _int64: () => _int642, - _int32: () => _int322, - _int: () => _int2, - _includes: () => _includes2, - _guid: () => _guid2, - _gte: () => _gte2, - _gt: () => _gt2, - _float64: () => _float642, - _float32: () => _float322, - _file: () => _file2, - _enum: () => _enum3, - _endsWith: () => _endsWith2, - _emoji: () => _emoji4, - _email: () => _email2, - _e164: () => _e1642, - _discriminatedUnion: () => _discriminatedUnion2, - _default: () => _default4, - _date: () => _date2, - _custom: () => _custom2, - _cuid2: () => _cuid22, - _cuid: () => _cuid3, - _coercedString: () => _coercedString2, - _coercedNumber: () => _coercedNumber2, - _coercedDate: () => _coercedDate2, - _coercedBoolean: () => _coercedBoolean2, - _coercedBigint: () => _coercedBigint2, - _cidrv6: () => _cidrv62, - _cidrv4: () => _cidrv42, - _catch: () => _catch3, - _boolean: () => _boolean2, - _bigint: () => _bigint2, - _base64url: () => _base64url2, - _base64: () => _base642, - _array: () => _array2, - _any: () => _any2, - TimePrecision: () => TimePrecision2, - NEVER: () => NEVER3, - JSONSchemaGenerator: () => JSONSchemaGenerator2, - JSONSchema: () => exports_json_schema2, - Doc: () => Doc2, - $output: () => $output2, - $input: () => $input2, - $constructor: () => $constructor2, - $brand: () => $brand2, - $ZodXID: () => $ZodXID2, - $ZodVoid: () => $ZodVoid2, - $ZodUnknown: () => $ZodUnknown2, - $ZodUnion: () => $ZodUnion2, - $ZodUndefined: () => $ZodUndefined2, - $ZodUUID: () => $ZodUUID2, - $ZodURL: () => $ZodURL2, - $ZodULID: () => $ZodULID2, - $ZodType: () => $ZodType2, - $ZodTuple: () => $ZodTuple2, - $ZodTransform: () => $ZodTransform2, - $ZodTemplateLiteral: () => $ZodTemplateLiteral2, - $ZodSymbol: () => $ZodSymbol2, - $ZodSuccess: () => $ZodSuccess2, - $ZodStringFormat: () => $ZodStringFormat2, - $ZodString: () => $ZodString2, - $ZodSet: () => $ZodSet2, - $ZodRegistry: () => $ZodRegistry2, - $ZodRecord: () => $ZodRecord2, - $ZodRealError: () => $ZodRealError2, - $ZodReadonly: () => $ZodReadonly2, - $ZodPromise: () => $ZodPromise2, - $ZodPrefault: () => $ZodPrefault2, - $ZodPipe: () => $ZodPipe2, - $ZodOptional: () => $ZodOptional2, - $ZodObject: () => $ZodObject2, - $ZodNumberFormat: () => $ZodNumberFormat2, - $ZodNumber: () => $ZodNumber2, - $ZodNullable: () => $ZodNullable2, - $ZodNull: () => $ZodNull2, - $ZodNonOptional: () => $ZodNonOptional2, - $ZodNever: () => $ZodNever2, - $ZodNanoID: () => $ZodNanoID2, - $ZodNaN: () => $ZodNaN2, - $ZodMap: () => $ZodMap2, - $ZodLiteral: () => $ZodLiteral2, - $ZodLazy: () => $ZodLazy2, - $ZodKSUID: () => $ZodKSUID2, - $ZodJWT: () => $ZodJWT2, - $ZodIntersection: () => $ZodIntersection2, - $ZodISOTime: () => $ZodISOTime2, - $ZodISODuration: () => $ZodISODuration2, - $ZodISODateTime: () => $ZodISODateTime2, - $ZodISODate: () => $ZodISODate2, - $ZodIPv6: () => $ZodIPv62, - $ZodIPv4: () => $ZodIPv42, - $ZodGUID: () => $ZodGUID2, - $ZodFunction: () => $ZodFunction2, - $ZodFile: () => $ZodFile2, - $ZodError: () => $ZodError2, - $ZodEnum: () => $ZodEnum2, - $ZodEmoji: () => $ZodEmoji2, - $ZodEmail: () => $ZodEmail2, - $ZodE164: () => $ZodE1642, - $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion2, - $ZodDefault: () => $ZodDefault2, - $ZodDate: () => $ZodDate2, - $ZodCustomStringFormat: () => $ZodCustomStringFormat2, - $ZodCustom: () => $ZodCustom2, - $ZodCheckUpperCase: () => $ZodCheckUpperCase2, - $ZodCheckStringFormat: () => $ZodCheckStringFormat2, - $ZodCheckStartsWith: () => $ZodCheckStartsWith2, - $ZodCheckSizeEquals: () => $ZodCheckSizeEquals2, - $ZodCheckRegex: () => $ZodCheckRegex2, - $ZodCheckProperty: () => $ZodCheckProperty2, - $ZodCheckOverwrite: () => $ZodCheckOverwrite2, - $ZodCheckNumberFormat: () => $ZodCheckNumberFormat2, - $ZodCheckMultipleOf: () => $ZodCheckMultipleOf2, - $ZodCheckMinSize: () => $ZodCheckMinSize2, - $ZodCheckMinLength: () => $ZodCheckMinLength2, - $ZodCheckMimeType: () => $ZodCheckMimeType2, - $ZodCheckMaxSize: () => $ZodCheckMaxSize2, - $ZodCheckMaxLength: () => $ZodCheckMaxLength2, - $ZodCheckLowerCase: () => $ZodCheckLowerCase2, - $ZodCheckLessThan: () => $ZodCheckLessThan2, - $ZodCheckLengthEquals: () => $ZodCheckLengthEquals2, - $ZodCheckIncludes: () => $ZodCheckIncludes2, - $ZodCheckGreaterThan: () => $ZodCheckGreaterThan2, - $ZodCheckEndsWith: () => $ZodCheckEndsWith2, - $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat2, - $ZodCheck: () => $ZodCheck2, - $ZodCatch: () => $ZodCatch2, - $ZodCUID2: () => $ZodCUID22, - $ZodCUID: () => $ZodCUID3, - $ZodCIDRv6: () => $ZodCIDRv62, - $ZodCIDRv4: () => $ZodCIDRv42, - $ZodBoolean: () => $ZodBoolean2, - $ZodBigIntFormat: () => $ZodBigIntFormat2, - $ZodBigInt: () => $ZodBigInt2, - $ZodBase64URL: () => $ZodBase64URL2, - $ZodBase64: () => $ZodBase642, - $ZodAsyncError: () => $ZodAsyncError2, - $ZodArray: () => $ZodArray2, - $ZodAny: () => $ZodAny2 -}); -var init_core5 = __esm(() => { - init_util3(); - init_regexes2(); - init_locales2(); - init_json_schema3(); - init_core4(); - init_parse6(); - init_errors11(); - init_schemas3(); - init_checks3(); - init_versions4(); - init_registries2(); - init_function2(); - init_api2(); - init_to_json_schema2(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/checks.js -var init_checks4 = __esm(() => { - init_core5(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js -var exports_iso2 = {}; -__export(exports_iso2, { - time: () => time5, - duration: () => duration4, - datetime: () => datetime4, - date: () => date7, - ZodISOTime: () => ZodISOTime2, - ZodISODuration: () => ZodISODuration2, - ZodISODateTime: () => ZodISODateTime2, - ZodISODate: () => ZodISODate2 -}); -function datetime4(params) { - return _isoDateTime2(ZodISODateTime2, params); -} -function date7(params) { - return _isoDate2(ZodISODate2, params); } -function time5(params) { - return _isoTime2(ZodISOTime2, params); +async function runWsStream(dataplaneUrl, apiKey, command, options = {}) { + const { timeout = 60, env, cwd, shell = "/bin/bash", onStdout, onStderr, commandId, idleTimeout = 300, killOnDisconnect = false, ttlSeconds = 600, pty, headers: extraHeaders } = options; + const wsUrl = buildWsUrl(dataplaneUrl); + const headers = buildAuthHeaders(apiKey, extraHeaders); + const control = new WSStreamControl; + async function* stream2() { + let ws; + try { + ws = await connectWs(wsUrl, headers); + control._bind(ws); + const payload = { + type: "execute", + command, + timeout_seconds: timeout, + shell, + idle_timeout_seconds: idleTimeout, + kill_on_disconnect: killOnDisconnect, + ttl_seconds: ttlSeconds + }; + if (env) + payload.env = env; + if (cwd) + payload.cwd = cwd; + if (commandId) + payload.command_id = commandId; + if (pty) + payload.pty = true; + ws.send(JSON.stringify(payload)); + for await (const msg of readWsMessages(ws)) { + const msgType = msg.type; + if (msgType === "started") { + yield msg; + } else if (msgType === "stdout") { + if (onStdout) + onStdout(msg.data); + yield msg; + } else if (msgType === "stderr") { + if (onStderr) + onStderr(msg.data); + yield msg; + } else if (msgType === "exit") { + yield msg; + return; + } else if (msgType === "error") { + raiseForWsError(msg); + } + } + } finally { + control._unbind(); + if (ws && ws.readyState === 1) { + ws.close(); + } + } + } + return [stream2(), control]; } -function duration4(params) { - return _isoDuration2(ZodISODuration2, params); +async function reconnectWsStream(dataplaneUrl, apiKey, commandId, options = {}) { + const { stdoutOffset = 0, stderrOffset = 0, headers: extraHeaders } = options; + const wsUrl = buildWsUrl(dataplaneUrl); + const headers = buildAuthHeaders(apiKey, extraHeaders); + const control = new WSStreamControl; + async function* stream2() { + let ws; + try { + ws = await connectWs(wsUrl, headers); + control._bind(ws); + ws.send(JSON.stringify({ + type: "reconnect", + command_id: commandId, + stdout_offset: stdoutOffset, + stderr_offset: stderrOffset + })); + for await (const msg of readWsMessages(ws)) { + const msgType = msg.type; + if (msgType === "stdout" || msgType === "stderr") { + yield msg; + } else if (msgType === "exit") { + yield msg; + return; + } else if (msgType === "error") { + raiseForWsError(msg, commandId); + } + } + } finally { + control._unbind(); + if (ws && ws.readyState === 1) { + ws.close(); + } + } + } + return [stream2(), control]; } -var ZodISODateTime2, ZodISODate2, ZodISOTime2, ZodISODuration2; -var init_iso2 = __esm(() => { - init_core5(); - init_schemas4(); - ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => { - $ZodISODateTime2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => { - $ZodISODate2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => { - $ZodISOTime2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => { - $ZodISODuration2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); +var init_ws_execute = __esm(() => { + init_errors12(); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js -var initializer4 = (inst, issues) => { - $ZodError2.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError3(inst, mapper) - }, - flatten: { - value: (mapper) => flattenError2(inst, mapper) - }, - addIssue: { - value: (issue3) => inst.issues.push(issue3) - }, - addIssues: { - value: (issues2) => inst.issues.push(...issues2) - }, - isEmpty: { - get() { - return inst.issues.length === 0; +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/sandbox.js +class Sandbox { + constructor(data, client2) { + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "dataplane_url", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "status_message", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "created_at", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "updated_at", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "idle_ttl_seconds", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "delete_after_stop_seconds", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "stopped_at", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "snapshot_id", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "vCpus", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "mem_bytes", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "fs_capacity_bytes", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_client", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.name = data.name; + this.dataplane_url = data.dataplane_url; + this.status = data.status; + this.status_message = data.status_message; + this.id = data.id; + this.created_at = data.created_at; + this.updated_at = data.updated_at; + this.idle_ttl_seconds = data.idle_ttl_seconds; + this.delete_after_stop_seconds = data.delete_after_stop_seconds; + this.stopped_at = data.stopped_at ?? undefined; + this.snapshot_id = data.snapshot_id; + this.vCpus = data.vcpus; + this.mem_bytes = data.mem_bytes; + this.fs_capacity_bytes = data.fs_capacity_bytes; + this._client = client2; + } + requireDataplaneUrl() { + if (this.status && this.status !== "ready") { + throw new LangSmithSandboxNotReadyError(`Sandbox '${this.name}' is not ready (status: ${this.status}). ` + "Use waitForSandbox() to wait for the sandbox to become ready."); + } + if (!this.dataplane_url) { + throw new LangSmithDataplaneNotConfiguredError(`Sandbox '${this.name}' does not have a dataplane_url configured. ` + "Runtime operations require a dataplane URL."); + } + return this.dataplane_url; + } + async run(command, options = {}) { + const { wait = true, onStdout, onStderr, idleTimeout, killOnDisconnect, ttlSeconds, pty, ...restOptions } = options; + const hasCallbacks = onStdout !== undefined || onStderr !== undefined; + if (!wait || hasCallbacks) { + const handle = await this._runWs(command, { + ...restOptions, + idleTimeout, + killOnDisconnect, + ttlSeconds, + pty, + onStdout, + onStderr + }); + if (!wait) { + return handle; } + return handle.result; } - }); -}, ZodError4, ZodRealError2; -var init_errors12 = __esm(() => { - init_core5(); - init_core5(); - ZodError4 = $constructor2("ZodError", initializer4); - ZodRealError2 = $constructor2("ZodError", initializer4, { - Parent: Error - }); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js -var parse13, parseAsync4, safeParse4, safeParseAsync4; -var init_parse7 = __esm(() => { - init_core5(); + try { + const handle = await this._runWs(command, { + ...restOptions, + idleTimeout, + killOnDisconnect, + ttlSeconds, + pty + }); + return await handle.result; + } catch (e) { + const name = e != null && typeof e === "object" ? e.name : ""; + const message = e != null && typeof e === "object" ? e.message ?? "" : ""; + if (name === "LangSmithSandboxConnectionError" || name === "LangSmithSandboxServerReloadError" || message.includes("'ws' package")) { + return this._runHttp(command, restOptions); + } + throw e; + } + } + async _runWs(command, options = {}) { + const { timeout = 60, env, cwd, shell = "/bin/bash", onStdout, onStderr, idleTimeout, killOnDisconnect, ttlSeconds, pty } = options; + const dataplaneUrl = this.requireDataplaneUrl(); + const clientHeaders = this._client.getDefaultHeaders(); + const [stream2, control] = await runWsStream(dataplaneUrl, this._client.getApiKey(), command, { + timeout, + env, + cwd, + shell, + onStdout, + onStderr, + idleTimeout, + killOnDisconnect, + ttlSeconds, + pty, + ...Object.keys(clientHeaders).length > 0 ? { headers: clientHeaders } : {} + }); + const handle = new CommandHandle(stream2, control, this); + await handle._ensureStarted(); + return handle; + } + async _runHttp(command, options = {}) { + const { timeout = 60, env, cwd, shell = "/bin/bash" } = options; + const dataplaneUrl = this.requireDataplaneUrl(); + const url3 = `${dataplaneUrl}/execute`; + const payload = { + command, + timeout, + shell + }; + if (env !== undefined) { + payload.env = env; + } + if (cwd !== undefined) { + payload.cwd = cwd; + } + const response = await this._client._fetch(url3, { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout((timeout + 10) * 1000) + }); + if (!response.ok) { + await handleSandboxHttpError(response); + } + const data = await response.json(); + return { + stdout: data.stdout ?? "", + stderr: data.stderr ?? "", + exit_code: data.exit_code ?? -1 + }; + } + async reconnect(commandId, options = {}) { + const { stdoutOffset = 0, stderrOffset = 0 } = options; + const dataplaneUrl = this.requireDataplaneUrl(); + const clientHeaders = this._client.getDefaultHeaders(); + const [stream2, control] = await reconnectWsStream(dataplaneUrl, this._client.getApiKey(), commandId, { + stdoutOffset, + stderrOffset, + ...Object.keys(clientHeaders).length > 0 ? { headers: clientHeaders } : {} + }); + return new CommandHandle(stream2, control, this, { + commandId, + stdoutOffset, + stderrOffset + }); + } + async write(path2, content, timeout = 60) { + const dataplaneUrl = this.requireDataplaneUrl(); + const url3 = `${dataplaneUrl}/upload?path=${encodeURIComponent(path2)}`; + const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content; + const formData = new FormData; + const buffer = new Uint8Array(bytes).buffer; + const blob = new Blob([buffer], { type: "application/octet-stream" }); + formData.append("file", blob, "file"); + const response = await this._client._fetch(url3, { + method: "POST", + body: formData, + signal: AbortSignal.timeout(timeout * 1000) + }); + if (!response.ok) { + await handleSandboxHttpError(response); + } + } + async read(path2, timeout = 60) { + const dataplaneUrl = this.requireDataplaneUrl(); + const url3 = `${dataplaneUrl}/download?path=${encodeURIComponent(path2)}`; + const response = await this._client._fetch(url3, { + method: "GET", + signal: AbortSignal.timeout(timeout * 1000) + }); + if (!response.ok) { + await handleSandboxHttpError(response); + } + const buffer = await response.arrayBuffer(); + return new Uint8Array(buffer); + } + async delete() { + await this._client.deleteSandbox(this.name); + } + async start(options = {}) { + const refreshed = await this._client.startSandbox(this.name, options); + this.status = refreshed.status; + this.dataplane_url = refreshed.dataplane_url; + } + async stop() { + await this._client.stopSandbox(this.name); + this.status = "stopped"; + this.dataplane_url = undefined; + } + async captureSnapshot(name, options = {}) { + return this._client.captureSnapshot(this.name, name, options); + } +} +var init_sandbox = __esm(() => { init_errors12(); - parse13 = /* @__PURE__ */ _parse2(ZodRealError2); - parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2); - safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2); - safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2); + init_helpers2(); + init_command_handle(); + init_ws_execute(); }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js -function string5(params) { - return _string2(ZodString3, params); -} -function email4(params) { - return _email2(ZodEmail2, params); -} -function guid4(params) { - return _guid2(ZodGUID2, params); -} -function uuid11(params) { - return _uuid2(ZodUUID2, params); -} -function uuidv42(params) { - return _uuidv42(ZodUUID2, params); -} -function uuidv62(params) { - return _uuidv62(ZodUUID2, params); -} -function uuidv72(params) { - return _uuidv72(ZodUUID2, params); -} -function url2(params) { - return _url2(ZodURL2, params); -} -function emoji4(params) { - return _emoji4(ZodEmoji2, params); -} -function nanoid4(params) { - return _nanoid2(ZodNanoID2, params); -} -function cuid6(params) { - return _cuid3(ZodCUID3, params); -} -function cuid24(params) { - return _cuid22(ZodCUID22, params); -} -function ulid4(params) { - return _ulid2(ZodULID2, params); -} -function xid4(params) { - return _xid2(ZodXID2, params); -} -function ksuid4(params) { - return _ksuid2(ZodKSUID2, params); -} -function ipv44(params) { - return _ipv42(ZodIPv42, params); -} -function ipv64(params) { - return _ipv62(ZodIPv62, params); -} -function cidrv44(params) { - return _cidrv42(ZodCIDRv42, params); -} -function cidrv64(params) { - return _cidrv62(ZodCIDRv62, params); -} -function base646(params) { - return _base642(ZodBase642, params); -} -function base64url4(params) { - return _base64url2(ZodBase64URL2, params); -} -function e1644(params) { - return _e1642(ZodE1642, params); -} -function jwt2(params) { - return _jwt2(ZodJWT2, params); -} -function stringFormat2(format3, fnOrRegex, _params = {}) { - return _stringFormat2(ZodCustomStringFormat2, format3, fnOrRegex, _params); -} -function number5(params) { - return _number2(ZodNumber3, params); -} -function int2(params) { - return _int2(ZodNumberFormat2, params); -} -function float322(params) { - return _float322(ZodNumberFormat2, params); -} -function float642(params) { - return _float642(ZodNumberFormat2, params); -} -function int322(params) { - return _int322(ZodNumberFormat2, params); -} -function uint322(params) { - return _uint322(ZodNumberFormat2, params); -} -function boolean5(params) { - return _boolean2(ZodBoolean3, params); -} -function bigint5(params) { - return _bigint2(ZodBigInt3, params); -} -function int642(params) { - return _int642(ZodBigIntFormat2, params); -} -function uint642(params) { - return _uint642(ZodBigIntFormat2, params); -} -function symbol2(params) { - return _symbol2(ZodSymbol3, params); -} -function _undefined6(params) { - return _undefined5(ZodUndefined3, params); -} -function _null6(params) { - return _null5(ZodNull3, params); -} -function any2() { - return _any2(ZodAny3); -} -function unknown2() { - return _unknown2(ZodUnknown3); -} -function never2(params) { - return _never2(ZodNever3, params); -} -function _void4(params) { - return _void3(ZodVoid3, params); -} -function date8(params) { - return _date2(ZodDate3, params); -} -function array2(element, params) { - return _array2(ZodArray3, element, params); -} -function keyof2(schema) { - const shape = schema._zod.def.shape; - return literal2(Object.keys(shape)); -} -function object2(shape, params) { - const def = { - type: "object", - get shape() { - exports_util2.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - ...exports_util2.normalizeParams(params) - }; - return new ZodObject3(def); -} -function strictObject2(shape, params) { - return new ZodObject3({ - type: "object", - get shape() { - exports_util2.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - catchall: never2(), - ...exports_util2.normalizeParams(params) - }); -} -function looseObject2(shape, params) { - return new ZodObject3({ - type: "object", - get shape() { - exports_util2.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - catchall: unknown2(), - ...exports_util2.normalizeParams(params) - }); -} -function union2(options, params) { - return new ZodUnion3({ - type: "union", - options, - ...exports_util2.normalizeParams(params) - }); -} -function discriminatedUnion2(discriminator, options, params) { - return new ZodDiscriminatedUnion3({ - type: "union", - options, - discriminator, - ...exports_util2.normalizeParams(params) - }); -} -function intersection2(left, right) { - return new ZodIntersection3({ - type: "intersection", - left, - right - }); -} -function tuple2(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType2; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple3({ - type: "tuple", - items, - rest, - ...exports_util2.normalizeParams(params) - }); -} -function record2(keyType, valueType, params) { - return new ZodRecord3({ - type: "record", - keyType, - valueType, - ...exports_util2.normalizeParams(params) - }); -} -function partialRecord2(keyType, valueType, params) { - return new ZodRecord3({ - type: "record", - keyType: union2([keyType, never2()]), - valueType, - ...exports_util2.normalizeParams(params) - }); -} -function map2(keyType, valueType, params) { - return new ZodMap3({ - type: "map", - keyType, - valueType, - ...exports_util2.normalizeParams(params) - }); -} -function set2(valueType, params) { - return new ZodSet3({ - type: "set", - valueType, - ...exports_util2.normalizeParams(params) - }); -} -function _enum4(values2, params) { - const entries = Array.isArray(values2) ? Object.fromEntries(values2.map((v) => [v, v])) : values2; - return new ZodEnum3({ - type: "enum", - entries, - ...exports_util2.normalizeParams(params) - }); -} -function nativeEnum2(entries, params) { - return new ZodEnum3({ - type: "enum", - entries, - ...exports_util2.normalizeParams(params) - }); -} -function literal2(value, params) { - return new ZodLiteral3({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...exports_util2.normalizeParams(params) +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/client.js +function sleepWithSignal(ms, signal) { + if (!signal) { + return new Promise((resolve2) => setTimeout(resolve2, ms)); + } + signal.throwIfAborted(); + return new Promise((resolve2, reject) => { + const timer = setTimeout(() => { + signal.removeEventListener("abort", onAbort); + resolve2(); + }, ms); + function onAbort() { + clearTimeout(timer); + reject(signal.reason); + } + signal.addEventListener("abort", onAbort, { once: true }); }); } -function file2(params) { - return _file2(ZodFile2, params); -} -function transform2(fn) { - return new ZodTransform2({ - type: "transform", - transform: fn - }); +function getDefaultApiEndpoint() { + const base = getLangSmithEnvironmentVariable("ENDPOINT") ?? "https://api.smith.langchain.com"; + return `${base.replace(/\/$/, "")}/v2/sandboxes`; } -function optional2(innerType) { - return new ZodOptional3({ - type: "optional", - innerType - }); +function getDefaultApiKey() { + return getLangSmithEnvironmentVariable("API_KEY"); } -function nullable2(innerType) { - return new ZodNullable3({ - type: "nullable", - innerType - }); +var SandboxClient; +var init_client4 = __esm(() => { + init_env2(); + init_fetch(); + init_async_caller(); + init_sandbox(); + init_errors12(); + init_helpers2(); + SandboxClient = class SandboxClient { + constructor(config3 = {}) { + Object.defineProperty(this, "_baseUrl", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_defaultHeaders", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_fetchImpl", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "_caller", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this._baseUrl = (config3.apiEndpoint ?? getDefaultApiEndpoint()).replace(/\/$/, ""); + this._apiKey = config3.apiKey ?? getDefaultApiKey(); + this._defaultHeaders = { ...config3.headers ?? {} }; + this._fetchImpl = _getFetchImplementation(); + this._caller = new AsyncCaller({ + maxRetries: config3.maxRetries ?? 3, + maxConcurrency: config3.maxConcurrency ?? Infinity + }); + } + async _fetch(url3, init = {}) { + const headers = new Headers(init.headers); + if (this._apiKey) { + headers.set("X-Api-Key", this._apiKey); + } + for (const [name, value] of Object.entries(this._defaultHeaders)) { + if (!headers.has(name)) { + headers.set(name, value); + } + } + return this._caller.call(() => this._fetchImpl(url3, { + ...init, + headers + })); + } + getApiKey() { + return this._apiKey; + } + getDefaultHeaders() { + return { ...this._defaultHeaders }; + } + async _postJson(url3, body, options) { + const response = await this._fetch(url3, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: options?.signal + }); + if (!response.ok) { + await handleClientHttpError(response); + } + return response; + } + async createSandbox(snapshotIdOrOptions, options = {}) { + const snapshotId = typeof snapshotIdOrOptions === "string" ? snapshotIdOrOptions : undefined; + const resolvedOptions = typeof snapshotIdOrOptions === "object" && snapshotIdOrOptions !== null ? snapshotIdOrOptions : options; + const { snapshotName, name, timeout = 30, waitForReady = true, idleTtlSeconds, deleteAfterStopSeconds, vCpus, memBytes, fsCapacityBytes, proxyConfig } = resolvedOptions; + if (snapshotId && snapshotName) { + throw new LangSmithValidationError("At most one of snapshotId or options.snapshotName may be set", "snapshotId"); + } + validateTtl(idleTtlSeconds, "idleTtlSeconds"); + validateTtl(deleteAfterStopSeconds, "deleteAfterStopSeconds"); + const url3 = `${this._baseUrl}/boxes`; + const payload = { + wait_for_ready: waitForReady + }; + if (snapshotId) { + payload.snapshot_id = snapshotId; + } + if (snapshotName) { + payload.snapshot_name = snapshotName; + } + if (waitForReady) { + payload.timeout = timeout; + } + if (name) { + payload.name = name; + } + if (idleTtlSeconds !== undefined) { + payload.idle_ttl_seconds = idleTtlSeconds; + } + if (deleteAfterStopSeconds !== undefined) { + payload.delete_after_stop_seconds = deleteAfterStopSeconds; + } + if (vCpus !== undefined) { + payload.vcpus = vCpus; + } + if (memBytes !== undefined) { + payload.mem_bytes = memBytes; + } + if (fsCapacityBytes !== undefined) { + payload.fs_capacity_bytes = fsCapacityBytes; + } + if (proxyConfig !== undefined) { + payload.proxy_config = proxyConfig; + } + const httpTimeout = waitForReady ? (timeout + 30) * 1000 : 30 * 1000; + const response = await this._fetch(url3, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(httpTimeout) + }); + if (!response.ok) { + await handleSandboxCreationError(response); + } + const data = await response.json(); + return new Sandbox(data, this); + } + async getSandbox(name, options) { + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; + const response = await this._fetch(url3, { signal: options?.signal }); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + } + await handleClientHttpError(response); + } + const data = await response.json(); + return new Sandbox(data, this); + } + async listSandboxes() { + const url3 = `${this._baseUrl}/boxes`; + const response = await this._fetch(url3); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithSandboxAPIError(`API endpoint not found: ${url3}. Check that apiEndpoint is correct.`); + } + await handleClientHttpError(response); + } + const data = await response.json(); + return (data.sandboxes ?? []).map((s) => new Sandbox(s, this)); + } + async updateSandbox(name, newNameOrOptions) { + const options = typeof newNameOrOptions === "string" ? { newName: newNameOrOptions } : newNameOrOptions; + const { newName, idleTtlSeconds, deleteAfterStopSeconds } = options; + validateTtl(idleTtlSeconds, "idleTtlSeconds"); + validateTtl(deleteAfterStopSeconds, "deleteAfterStopSeconds"); + if (newName === undefined && idleTtlSeconds === undefined && deleteAfterStopSeconds === undefined) { + return this.getSandbox(name); + } + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; + const payload = {}; + if (newName !== undefined) { + payload.name = newName; + } + if (idleTtlSeconds !== undefined) { + payload.idle_ttl_seconds = idleTtlSeconds; + } + if (deleteAfterStopSeconds !== undefined) { + payload.delete_after_stop_seconds = deleteAfterStopSeconds; + } + const response = await this._fetch(url3, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload) + }); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + } + if (response.status === 409) { + throw new LangSmithResourceNameConflictError(newName !== undefined ? `Sandbox name '${newName}' already in use` : "Sandbox update conflict (name may already be in use)", "sandbox"); + } + await handleClientHttpError(response); + } + const data = await response.json(); + return new Sandbox(data, this); + } + async deleteSandbox(name) { + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}`; + const response = await this._fetch(url3, { method: "DELETE" }); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + } + await handleClientHttpError(response); + } + } + async getSandboxStatus(name, options) { + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/status`; + const response = await this._fetch(url3, { signal: options?.signal }); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithResourceNotFoundError(`Sandbox '${name}' not found`, "sandbox"); + } + await handleClientHttpError(response); + } + return await response.json(); + } + async waitForSandbox(name, options = {}) { + const { timeout = 120, pollInterval = 1, signal } = options; + const deadline = Date.now() + timeout * 1000; + let lastStatus = "provisioning"; + while (Date.now() < deadline) { + signal?.throwIfAborted(); + const statusResult = await this.getSandboxStatus(name, { signal }); + lastStatus = statusResult.status; + if (statusResult.status === "ready") { + return this.getSandbox(name, { signal }); + } + if (statusResult.status === "failed") { + throw new LangSmithResourceCreationError(statusResult.status_message ?? `Sandbox '${name}' creation failed`, "sandbox"); + } + const remaining = deadline - Date.now(); + const jitter = pollInterval * 200 * (Math.random() - 0.5); + const delay = Math.min(pollInterval * 1000 + jitter, remaining); + if (delay > 0) { + await sleepWithSignal(delay, signal); + } + } + throw new LangSmithResourceTimeoutError(`Sandbox '${name}' did not become ready within ${timeout}s`, "sandbox", lastStatus); + } + async startSandbox(name, options = {}) { + const { timeout = 120, signal } = options; + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/start`; + await this._postJson(url3, {}, { signal }); + return this.waitForSandbox(name, { timeout, signal }); + } + async stopSandbox(name) { + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(name)}/stop`; + await this._postJson(url3, {}); + } + async createSnapshot(name, dockerImage, fsCapacityBytes, options = {}) { + const { registryId, registryUrl, registryUsername, registryPassword, timeout = 60, signal } = options; + const url3 = `${this._baseUrl}/snapshots`; + const payload = { + name, + docker_image: dockerImage, + fs_capacity_bytes: fsCapacityBytes + }; + if (registryId !== undefined) { + payload.registry_id = registryId; + } + if (registryUrl !== undefined) { + payload.registry_url = registryUrl; + } + if (registryUsername !== undefined) { + payload.registry_username = registryUsername; + } + if (registryPassword !== undefined) { + payload.registry_password = registryPassword; + } + const response = await this._postJson(url3, payload, { signal }); + const snapshot = await response.json(); + return this.waitForSnapshot(snapshot.id, { timeout, signal }); + } + async captureSnapshot(sandboxName, name, options = {}) { + const { timeout = 60, signal } = options; + const url3 = `${this._baseUrl}/boxes/${encodeURIComponent(sandboxName)}/snapshot`; + const payload = { name }; + const response = await this._postJson(url3, payload, { signal }); + const snapshot = await response.json(); + return this.waitForSnapshot(snapshot.id, { timeout, signal }); + } + async getSnapshot(snapshotId, options) { + const url3 = `${this._baseUrl}/snapshots/${encodeURIComponent(snapshotId)}`; + const response = await this._fetch(url3, { signal: options?.signal }); + if (!response.ok) { + if (response.status === 404) { + throw new LangSmithResourceNotFoundError(`Snapshot '${snapshotId}' not found`, "snapshot"); + } + await handleClientHttpError(response); + } + return await response.json(); + } + async listSnapshots(options = {}) { + const { nameContains, limit, offset, signal } = options; + const params = new URLSearchParams; + if (nameContains !== undefined) { + params.set("name_contains", nameContains); + } + if (limit !== undefined) { + params.set("limit", String(limit)); + } + if (offset !== undefined) { + params.set("offset", String(offset)); + } + const query3 = params.toString(); + const url3 = query3 ? `${this._baseUrl}/snapshots?${query3}` : `${this._baseUrl}/snapshots`; + const response = await this._fetch(url3, { signal }); + if (!response.ok) { + await handleClientHttpError(response); + } + const data = await response.json(); + return data.snapshots ?? []; + } + async deleteSnapshot(snapshotId) { + const url3 = `${this._baseUrl}/snapshots/${encodeURIComponent(snapshotId)}`; + const response = await this._fetch(url3, { method: "DELETE" }); + if (!response.ok) { + await handleClientHttpError(response); + } + } + async waitForSnapshot(snapshotId, options = {}) { + const { timeout = 300, pollInterval = 2, signal } = options; + const deadline = Date.now() + timeout * 1000; + let lastStatus = "building"; + while (Date.now() < deadline) { + signal?.throwIfAborted(); + const snapshot = await this.getSnapshot(snapshotId, { signal }); + lastStatus = snapshot.status; + if (snapshot.status === "ready") { + return snapshot; + } + if (snapshot.status === "failed") { + throw new LangSmithResourceCreationError(snapshot.status_message ?? `Snapshot '${snapshotId}' build failed`, "snapshot"); + } + const remaining = deadline - Date.now(); + const jitter = pollInterval * 200 * (Math.random() - 0.5); + const delay = Math.min(pollInterval * 1000 + jitter, remaining); + if (delay > 0) { + await sleepWithSignal(delay, signal); + } + } + throw new LangSmithResourceTimeoutError(`Snapshot '${snapshotId}' did not become ready within ${timeout}s`, "snapshot", lastStatus); + } + toString() { + return `[LangSmithSandboxClient apiEndpoint=${JSON.stringify(this._baseUrl)}]`; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return this.toString(); + } + }; +}); + +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/dist/sandbox/index.js +var init_sandbox2 = __esm(() => { + init_client4(); + init_sandbox(); + init_command_handle(); + init_errors12(); +}); + +// ../../node_modules/.pnpm/langsmith@0.7.3_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetry+_a6j4gps2d3qeqz7uxss4arr3ry/node_modules/langsmith/experimental/sandbox.js +var init_sandbox3 = __esm(() => { + init_sandbox2(); +}); + +// ../../node_modules/.pnpm/deepagents@1.10.2_@opentelemetry+api@1.9.1_@opentelemetry+sdk-trace-base@1.30.1_@opentelemetr_vekmjlcrdues43c23rbrt4lfii/node_modules/deepagents/dist/index.js +var exports_dist2 = {}; +__export(exports_dist2, { + serializeProfile: () => serializeProfile, + resolveBackend: () => resolveBackend, + registerHarnessProfile: () => registerHarnessProfile, + parseSkillMetadata: () => parseSkillMetadata, + parseHarnessProfileConfig: () => parseHarnessProfileConfig, + listSkills: () => listSkills, + isSandboxProtocol: () => isSandboxProtocol, + isSandboxBackend: () => isSandboxBackend, + isAsyncSubAgent: () => isAsyncSubAgent, + harnessProfileConfigSchema: () => harnessProfileConfigSchema, + getHarnessProfile: () => getHarnessProfile, + generalPurposeSubagentConfigSchema: () => generalPurposeSubagentConfigSchema, + findProjectRoot: () => findProjectRoot, + filesValue: () => filesValue, + createSummarizationMiddleware: () => createSummarizationMiddleware, + createSubagentTransformer: () => createSubagentTransformer, + createSubAgentMiddleware: () => createSubAgentMiddleware, + createSkillsMiddleware: () => createSkillsMiddleware, + createSettings: () => createSettings, + createPatchToolCallsMiddleware: () => createPatchToolCallsMiddleware, + createMemoryMiddleware: () => createMemoryMiddleware, + createHarnessProfile: () => createHarnessProfile, + createFilesystemMiddleware: () => createFilesystemMiddleware, + createDeepAgent: () => createDeepAgent, + createCompletionCallbackMiddleware: () => createCompletionCallbackMiddleware, + createAsyncSubAgentMiddleware: () => createAsyncSubAgentMiddleware, + createAgentMemoryMiddleware: () => createAgentMemoryMiddleware, + computeSummarizationDefaults: () => computeSummarizationDefaults, + adaptSandboxProtocol: () => adaptSandboxProtocol, + adaptBackendProtocol: () => adaptBackendProtocol, + TASK_SYSTEM_PROMPT: () => TASK_SYSTEM_PROMPT, + StoreBackend: () => StoreBackend, + StateBackend: () => StateBackend, + SandboxError: () => SandboxError, + REQUIRED_MIDDLEWARE_NAMES: () => REQUIRED_MIDDLEWARE_NAMES, + MAX_SKILL_NAME_LENGTH: () => MAX_SKILL_NAME_LENGTH, + MAX_SKILL_FILE_SIZE: () => MAX_SKILL_FILE_SIZE, + MAX_SKILL_DESCRIPTION_LENGTH: () => MAX_SKILL_DESCRIPTION_LENGTH, + LocalShellBackend: () => LocalShellBackend, + LangSmithSandbox: () => LangSmithSandbox, + GENERAL_PURPOSE_SUBAGENT: () => GENERAL_PURPOSE_SUBAGENT, + FilesystemBackend: () => FilesystemBackend, + EMPTY_HARNESS_PROFILE: () => EMPTY_HARNESS_PROFILE, + DEFAULT_SUBAGENT_PROMPT: () => DEFAULT_SUBAGENT_PROMPT, + DEFAULT_GENERAL_PURPOSE_DESCRIPTION: () => DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + ContextHubBackend: () => ContextHubBackend, + ConfigurationError: () => ConfigurationError, + CompositeBackend: () => CompositeBackend, + BaseSandbox: () => BaseSandbox +}); +import path2, { basename } from "path"; +import fs from "node:fs/promises"; +import fs$1 from "node:fs"; +import path$1 from "node:path"; +import cp, { spawn } from "node:child_process"; +import os from "node:os"; +function sanitizeToolCallId(toolCallId) { + return toolCallId.replace(/\./g, "_").replace(/\//g, "_").replace(/\\/g, "_"); } -function nullish4(innerType) { - return optional2(nullable2(innerType)); +function formatContentWithLineNumbers(content, startLine = 1) { + let lines; + if (typeof content === "string") { + lines = content.split(` +`); + if (lines.length > 0 && lines[lines.length - 1] === "") + lines = lines.slice(0, -1); + } else + lines = content; + const resultLines = []; + for (let i = 0;i < lines.length; i++) { + const line = lines[i]; + const lineNum = i + startLine; + if (line.length <= 5000) + resultLines.push(`${lineNum.toString().padStart(6)} ${line}`); + else { + const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH); + for (let chunkIdx = 0;chunkIdx < numChunks; chunkIdx++) { + const start = chunkIdx * MAX_LINE_LENGTH; + const end = Math.min(start + MAX_LINE_LENGTH, line.length); + const chunk = line.substring(start, end); + if (chunkIdx === 0) + resultLines.push(`${lineNum.toString().padStart(6)} ${chunk}`); + else { + const continuationMarker = `${lineNum}.${chunkIdx}`; + resultLines.push(`${continuationMarker.padStart(6)} ${chunk}`); + } + } + } + } + return resultLines.join(` +`); } -function _default5(innerType, defaultValue) { - return new ZodDefault3({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; +function checkEmptyContent(content) { + if (!content || content.trim() === "") + return EMPTY_CONTENT_WARNING; + return null; +} +function fileDataToString(fileData) { + if (Array.isArray(fileData.content)) + return fileData.content.join(` +`); + if (typeof fileData.content === "string") + return fileData.content; + throw new Error("Cannot convert binary FileData to string"); +} +function isFileDataBinary(data) { + return ArrayBuffer.isView(data.content); +} +function createFileData(content, createdAt, fileFormat = "v2", mimeType) { + const now = (/* @__PURE__ */ new Date()).toISOString(); + if (fileFormat === "v1" && ArrayBuffer.isView(content)) + throw new Error("Binary data is not supported with v1 file formats. Please use v2 file format"); + if (fileFormat === "v2") { + if (ArrayBuffer.isView(content)) + return { + content: new Uint8Array(content.buffer, content.byteOffset, content.byteLength), + mimeType: mimeType ?? "application/octet-stream", + created_at: createdAt || now, + modified_at: now + }; + return { + content, + mimeType: mimeType ?? "text/plain", + created_at: createdAt || now, + modified_at: now + }; + } + return { + content: typeof content === "string" ? content.split(` +`) : content, + created_at: createdAt || now, + modified_at: now + }; +} +function updateFileData(fileData, content) { + const now = (/* @__PURE__ */ new Date()).toISOString(); + if (isFileDataV1(fileData)) + return { + content: typeof content === "string" ? content.split(` +`) : content, + created_at: fileData.created_at, + modified_at: now + }; + return { + content, + mimeType: fileData.mimeType, + created_at: fileData.created_at, + modified_at: now + }; +} +function performStringReplacement(content, oldString, newString, replaceAll) { + if (content === "" && oldString === "") + return [newString, 0]; + if (oldString === "") + return "Error: oldString cannot be empty when file has content"; + const occurrences = content.split(oldString).length - 1; + if (occurrences === 0) + return `Error: String not found in file: '${oldString}'`; + if (occurrences > 1 && !replaceAll) + return `Error: String '${oldString}' has multiple occurrences (appears ${occurrences} times) in file. Use replace_all=True to replace all instances, or provide a more specific string with surrounding context.`; + return [content.split(oldString).join(newString), occurrences]; +} +function truncateIfTooLong(result) { + if (Array.isArray(result)) { + const totalChars = result.reduce((sum, item) => sum + item.length, 0); + if (totalChars > 20000 * 4) { + const truncateAt = Math.floor(result.length * TOOL_RESULT_TOKEN_LIMIT * 4 / totalChars); + return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE]; } - }); + return result; + } + if (result.length > 20000 * 4) + return result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4) + ` +... [results truncated, try being more specific with your parameters]`; + return result; } -function prefault2(innerType, defaultValue) { - return new ZodPrefault2({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; +function validatePath$1(path3) { + const pathStr = path3 || "/"; + if (!pathStr || pathStr.trim() === "") + throw new Error("Path cannot be empty"); + let normalized = pathStr.startsWith("/") ? pathStr : "/" + pathStr; + if (!normalized.endsWith("/")) + normalized += "/"; + return normalized; +} +function globSearchFiles(files, pattern, path3 = "/") { + let normalizedPath; + try { + normalizedPath = validatePath$1(path3); + } catch { + return "No files found"; + } + const filtered = Object.fromEntries(Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath))); + const effectivePattern = pattern; + const matches = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + let relative2 = filePath.substring(normalizedPath.length); + if (relative2.startsWith("/")) + relative2 = relative2.substring(1); + if (!relative2) { + const parts = filePath.split("/"); + relative2 = parts[parts.length - 1] || ""; } - }); + if (import_micromatch.default.isMatch(relative2, effectivePattern, { + dot: true, + nobrace: false + })) + matches.push([filePath, fileData.modified_at]); + } + matches.sort((a, b) => b[1].localeCompare(a[1])); + if (matches.length === 0) + return "No files found"; + return matches.map(([fp]) => fp).join(` +`); } -function nonoptional2(innerType, params) { - return new ZodNonOptional2({ - type: "nonoptional", - innerType, - ...exports_util2.normalizeParams(params) - }); +function grepMatchesFromFiles(files, pattern, path3 = null, glob = null) { + let normalizedPath; + try { + normalizedPath = validatePath$1(path3); + } catch { + return []; + } + let filtered = Object.fromEntries(Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath))); + if (glob) + filtered = Object.fromEntries(Object.entries(filtered).filter(([fp]) => import_micromatch.default.isMatch(basename(fp), glob, { + dot: true, + nobrace: false + }))); + const matches = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + if (!isTextMimeType(migrateToFileDataV2(fileData, filePath).mimeType)) + continue; + const lines = fileDataToString(fileData).split(` +`); + for (let i = 0;i < lines.length; i++) { + const line = lines[i]; + const lineNum = i + 1; + if (line.includes(pattern)) + matches.push({ + path: filePath, + line: lineNum, + text: line + }); + } + } + return matches; } -function success2(innerType) { - return new ZodSuccess2({ - type: "success", - innerType - }); +function getMimeType(filePath) { + return MIME_TYPES[path2.extname(filePath).toLocaleLowerCase()] || "text/plain"; } -function _catch4(innerType, catchValue) { - return new ZodCatch3({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); +function isTextMimeType(mimeType) { + return mimeType.startsWith("text/") || mimeType === "application/json" || mimeType === "application/javascript" || mimeType === "image/svg+xml"; } -function nan2(params) { - return _nan2(ZodNaN3, params); +function isFileDataV1(data) { + return Array.isArray(data.content); } -function pipe2(in_, out) { - return new ZodPipe2({ - type: "pipe", - in: in_, - out - }); +function migrateToFileDataV2(data, filePath) { + if (isFileDataV1(data)) + return { + content: data.content.join(` +`), + mimeType: getMimeType(filePath), + created_at: data.created_at, + modified_at: data.modified_at + }; + if (!("mimeType" in data) || !data.mimeType) + return { + ...data, + mimeType: getMimeType(filePath) + }; + return data; } -function readonly2(innerType) { - return new ZodReadonly3({ - type: "readonly", - innerType - }); +function adaptBackendProtocol(backend) { + return { + async ls(path3) { + const result = await ("ls" in backend ? backend.ls(path3) : backend.lsInfo(path3)); + if (Array.isArray(result)) + return { files: result }; + return result; + }, + async readRaw(filePath) { + const result = await backend.readRaw(filePath); + if ("data" in result || "error" in result) + return result; + return { data: migrateToFileDataV2(result, filePath) }; + }, + async glob(pattern, path3) { + const result = await ("glob" in backend ? backend.glob(pattern, path3) : backend.globInfo(pattern, path3)); + if (Array.isArray(result)) + return { files: result }; + return result; + }, + write: (filePath, content) => backend.write(filePath, content), + edit: (filePath, oldString, newString, replaceAll) => backend.edit(filePath, oldString, newString, replaceAll), + uploadFiles: backend.uploadFiles ? (files) => backend.uploadFiles(files) : undefined, + downloadFiles: backend.downloadFiles ? (paths) => backend.downloadFiles(paths) : undefined, + async read(filePath, offset, limit) { + const result = await backend.read(filePath, offset, limit); + if (typeof result === "string") + return { content: result }; + return result; + }, + async grep(pattern, path3, glob) { + const result = await ("grep" in backend ? backend.grep(pattern, path3, glob) : backend.grepRaw(pattern, path3, glob)); + if (Array.isArray(result)) + return { matches: result }; + if (typeof result === "string") + return { error: result }; + return result; + } + }; } -function templateLiteral2(parts, params) { - return new ZodTemplateLiteral2({ - type: "template_literal", - parts, - ...exports_util2.normalizeParams(params) +function adaptSandboxProtocol(sandbox2) { + const adapted = adaptBackendProtocol(sandbox2); + adapted.execute = (cmd) => sandbox2.execute(cmd); + Object.defineProperty(adapted, "id", { + value: sandbox2.id, + enumerable: true, + configurable: true }); + return adapted; } -function lazy2(getter) { - return new ZodLazy3({ - type: "lazy", - getter - }); +function isSandboxBackend(backend) { + return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; } -function promise2(innerType) { - return new ZodPromise3({ - type: "promise", - innerType - }); +function isSandboxProtocol(backend) { + return backend != null && typeof backend === "object" && typeof backend.execute === "function" && typeof backend.id === "string" && backend.id !== ""; } -function check2(fn) { - const ch = new $ZodCheck2({ - check: "custom" +async function resolveBackend(backend, runtime) { + if (typeof backend === "function") { + const resolved = await backend(runtime); + return isSandboxProtocol(resolved) ? adaptSandboxProtocol(resolved) : adaptBackendProtocol(resolved); + } + return isSandboxProtocol(backend) ? adaptSandboxProtocol(backend) : adaptBackendProtocol(backend); +} +function validatePermissionPaths(permissions) { + for (const permission of permissions) + for (const path3 of permission.paths) + validatePath(path3); +} +function validatePath(raw2) { + if (typeof raw2 !== "string" || raw2.length === 0) + throw new Error("path must be a non-empty string"); + if (!raw2.startsWith("/")) + throw new Error(`path must be absolute: ${JSON.stringify(raw2)}`); + const segments = raw2.split("/").filter((s) => s.length > 0); + if (segments.includes("..")) + throw new Error(`path must not contain "..": ${JSON.stringify(raw2)}`); + if (segments.includes("~")) + throw new Error(`path must not contain "~": ${JSON.stringify(raw2)}`); + return `/${segments.join("/")}`; +} +function globMatch(path3, pattern) { + return import_micromatch.default.isMatch(path3, pattern, { dot: true }); +} +function decidePathAccess(rules, operation, path3) { + for (const rule of rules) { + if (!rule.operations.includes(operation)) + continue; + if (rule.paths.some((pattern) => globMatch(path3, pattern))) + return rule.mode ?? "allow"; + } + return "allow"; +} +function extractTextFromMessage(message) { + if (typeof message.content === "string") + return message.content; + if (Array.isArray(message.content)) + return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(` +`); + return String(message.content); +} +function buildEvictedHumanContent(message, replacementText) { + if (typeof message.content === "string") + return replacementText; + if (Array.isArray(message.content)) { + const mediaBlocks = message.content.filter((block) => typeof block === "object" && block !== null && block.type !== "text"); + if (mediaBlocks.length === 0) + return replacementText; + return [{ + type: "text", + text: replacementText + }, ...mediaBlocks]; + } + return replacementText; +} +function buildTruncatedHumanMessage(message, filePath) { + const contentSample = createContentPreview(extractTextFromMessage(message)); + return new HumanMessage({ + content: buildEvictedHumanContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample)), + id: message.id, + additional_kwargs: { ...message.additional_kwargs }, + response_metadata: { ...message.response_metadata } }); - ch._zod.check = fn; - return ch; } -function custom3(fn, _params) { - return _custom2(ZodCustom2, fn ?? (() => true), _params); +function createContentPreview(contentStr, headLines = 5, tailLines = 5) { + const lines = contentStr.split(` +`); + if (lines.length <= headLines + tailLines) + return formatContentWithLineNumbers(lines.map((line) => line.substring(0, 1000)), 1); + const head = lines.slice(0, headLines).map((line) => line.substring(0, 1000)); + const tail = lines.slice(-tailLines).map((line) => line.substring(0, 1000)); + const headSample = formatContentWithLineNumbers(head, 1); + const truncationNotice = ` +... [${lines.length - headLines - tailLines} lines truncated] ... +`; + const tailSample = formatContentWithLineNumbers(tail, lines.length - tailLines + 1); + return headSample + truncationNotice + tailSample; } -function refine2(fn, _params = {}) { - return _refine2(ZodCustom2, fn, _params); +function fileDataReducer(current, update) { + if (update === undefined) + return current || {}; + if (current === undefined) { + const result2 = {}; + for (const [key, value] of Object.entries(update)) + if (value !== null) + result2[key] = value; + return result2; + } + const result = { ...current }; + for (const [key, value] of Object.entries(update)) + if (value === null) + delete result[key]; + else + result[key] = value; + return result; } -function superRefine2(fn) { - const ch = check2((payload) => { - payload.addIssue = (issue3) => { - if (typeof issue3 === "string") { - payload.issues.push(exports_util2.issue(issue3, payload.value, ch._zod.def)); - } else { - const _issue = issue3; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(exports_util2.issue(_issue)); +function enforcePermission(rules, operation, path3) { + if (rules.length === 0) + return; + const canonical = validatePath(path3); + if (decidePathAccess(rules, operation, canonical) === "deny") + throw new Error(`Error: permission denied for ${operation} on ${canonical}`); +} +function filterByPermissions(entries, rules, operation, getPath2) { + if (rules.length === 0) + return entries; + return entries.filter((entry) => { + try { + return decidePathAccess(rules, operation, validatePath(getPath2(entry))) !== "deny"; + } catch { + return true; + } + }); +} +function createLsTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "read", input.path ?? "/"); + const resolvedBackend = await resolveBackend(backend, runtime); + const path3 = input.path || "/"; + const lsResult = await resolvedBackend.ls(path3); + if (lsResult.error) + return `Error listing files: ${lsResult.error}`; + const infos = filterByPermissions(lsResult.files ?? [], permissions, "read", (info) => info.path); + if (infos.length === 0) + return `No files found in ${path3}`; + const lines = []; + for (const info of infos) + if (info.is_dir) + lines.push(`${info.path} (directory)`); + else { + const size = info.size ? ` (${info.size} bytes)` : ""; + lines.push(`${info.path}${size}`); } - }; - return fn(payload.value, payload); + const result = truncateIfTooLong(lines); + if (Array.isArray(result)) + return result.join(` +`); + return result; + }, { + name: "ls", + description: customDescription || LS_TOOL_DESCRIPTION, + schema: exports_external.object({ path: exports_external.string().optional().default("/").describe("Directory path to list (default: /)") }) }); - return ch; } -function _instanceof2(cls, params = { - error: `Input not instance of ${cls.name}` -}) { - const inst = new ZodCustom2({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...exports_util2.normalizeParams(params) +function createReadFileTool(backend, options) { + const { customDescription, toolTokenLimitBeforeEvict, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "read", input.file_path); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, offset = 0, limit = 100 } = input; + const readResult = await resolvedBackend.read(file_path, offset, limit); + if (readResult.error) + return [{ + type: "text", + text: `Error: ${readResult.error}` + }]; + const mimeType = readResult.mimeType ?? getMimeType(file_path); + if (!isTextMimeType(mimeType)) { + const binaryContent = readResult.content; + if (!binaryContent) + return [{ + type: "text", + text: `Error: expected binary content for '${file_path}'` + }]; + let base64Data; + if (typeof binaryContent === "string") + base64Data = binaryContent; + else if (ArrayBuffer.isView(binaryContent)) + base64Data = Buffer.from(binaryContent).toString("base64"); + else { + const values = Object.values(binaryContent); + base64Data = Buffer.from(new Uint8Array(values)).toString("base64"); + } + const sizeBytes = Math.ceil(base64Data.length * 3 / 4); + if (sizeBytes > 10485760) + return [{ + type: "text", + text: `Error: file too large to read (${Math.round(sizeBytes / (1024 * 1024))}MB exceeds ${MAX_BINARY_READ_SIZE_BYTES / (1024 * 1024)}MB limit for binary files)` + }]; + if (mimeType.startsWith("image/")) + return [{ + type: "image", + mimeType, + data: base64Data + }]; + if (mimeType.startsWith("audio/")) + return [{ + type: "audio", + mimeType, + data: base64Data + }]; + if (mimeType.startsWith("video/")) + return [{ + type: "video", + mimeType, + data: base64Data + }]; + return [{ + type: "file", + mimeType, + data: base64Data + }]; + } + let content = typeof readResult.content === "string" ? readResult.content : ""; + const lines = content.split(` +`); + if (lines.length > limit) + content = lines.slice(0, limit).join(` +`); + let formatted = formatContentWithLineNumbers(content, offset + 1); + if (toolTokenLimitBeforeEvict && formatted.length >= 4 * toolTokenLimitBeforeEvict) { + const truncationMsg = READ_FILE_TRUNCATION_MSG.replace("{file_path}", file_path); + const maxContentLength = 4 * toolTokenLimitBeforeEvict - truncationMsg.length; + formatted = formatted.substring(0, maxContentLength) + truncationMsg; + } + return [{ + type: "text", + text: formatted + }]; + }, { + name: "read_file", + description: customDescription || READ_FILE_TOOL_DESCRIPTION, + schema: exports_external.object({ + file_path: exports_external.string().describe("Absolute path to the file to read"), + offset: exports_external.coerce.number().optional().default(0).describe("Line offset to start reading from (0-indexed)"), + limit: exports_external.coerce.number().optional().default(100).describe("Maximum number of lines to read") + }) }); - inst._zod.bag.Class = cls; - return inst; } -function json2(params) { - const jsonSchema = lazy2(() => { - return union2([string5(params), number5(), boolean5(), _null6(), array2(jsonSchema), record2(string5(), jsonSchema)]); +function createWriteFileTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "write", input.file_path); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, content } = input; + const result = await resolvedBackend.write(file_path, content); + if (result.error) + return result.error; + const message = new ToolMessage({ + content: `Successfully wrote to '${file_path}'`, + tool_call_id: runtime.toolCall?.id, + name: "write_file", + metadata: result.metadata + }); + if (result.filesUpdate) + return new Command2({ update: { + files: result.filesUpdate, + messages: [message] + } }); + return message; + }, { + name: "write_file", + description: customDescription || WRITE_FILE_TOOL_DESCRIPTION, + schema: exports_external.object({ + file_path: exports_external.string().describe("Absolute path to the file to write"), + content: exports_external.string().default("").describe("Content to write to the file") + }) }); - return jsonSchema; } -function preprocess2(fn, schema) { - return pipe2(transform2(fn), schema); +function createEditFileTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "write", input.file_path); + const resolvedBackend = await resolveBackend(backend, runtime); + const { file_path, old_string, new_string, replace_all = false } = input; + const result = await resolvedBackend.edit(file_path, old_string, new_string, replace_all); + if (result.error) + return result.error; + const message = new ToolMessage({ + content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`, + tool_call_id: runtime.toolCall?.id, + name: "edit_file", + metadata: result.metadata + }); + if (result.filesUpdate) + return new Command2({ update: { + files: result.filesUpdate, + messages: [message] + } }); + return message; + }, { + name: "edit_file", + description: customDescription || EDIT_FILE_TOOL_DESCRIPTION, + schema: exports_external.object({ + file_path: exports_external.string().describe("Absolute path to the file to edit"), + old_string: exports_external.string().describe("String to be replaced (must match exactly)"), + new_string: exports_external.string().describe("String to replace with"), + replace_all: exports_external.boolean().optional().default(false).describe("Whether to replace all occurrences") + }) + }); } -var ZodType3, _ZodString2, ZodString3, ZodStringFormat2, ZodEmail2, ZodGUID2, ZodUUID2, ZodURL2, ZodEmoji2, ZodNanoID2, ZodCUID3, ZodCUID22, ZodULID2, ZodXID2, ZodKSUID2, ZodIPv42, ZodIPv62, ZodCIDRv42, ZodCIDRv62, ZodBase642, ZodBase64URL2, ZodE1642, ZodJWT2, ZodCustomStringFormat2, ZodNumber3, ZodNumberFormat2, ZodBoolean3, ZodBigInt3, ZodBigIntFormat2, ZodSymbol3, ZodUndefined3, ZodNull3, ZodAny3, ZodUnknown3, ZodNever3, ZodVoid3, ZodDate3, ZodArray3, ZodObject3, ZodUnion3, ZodDiscriminatedUnion3, ZodIntersection3, ZodTuple3, ZodRecord3, ZodMap3, ZodSet3, ZodEnum3, ZodLiteral3, ZodFile2, ZodTransform2, ZodOptional3, ZodNullable3, ZodDefault3, ZodPrefault2, ZodNonOptional2, ZodSuccess2, ZodCatch3, ZodNaN3, ZodPipe2, ZodReadonly3, ZodTemplateLiteral2, ZodLazy3, ZodPromise3, ZodCustom2, stringbool2 = (...args) => _stringbool2({ - Pipe: ZodPipe2, - Boolean: ZodBoolean3, - String: ZodString3, - Transform: ZodTransform2 -}, ...args); -var init_schemas4 = __esm(() => { - init_core5(); - init_core5(); - init_checks4(); - init_iso2(); - init_parse7(); - ZodType3 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => { - $ZodType2.init(inst, def); - inst.def = def; - Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks4) => { - return inst.clone({ - ...def, - checks: [ - ...def.checks ?? [], - ...checks4.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - }); - }; - inst.clone = (def2, params) => clone2(inst, def2, params); - inst.brand = () => inst; - inst.register = (reg, meta3) => { - reg.add(inst, meta3); - return inst; - }; - inst.parse = (data, params) => parse13(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse4(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.refine = (check2, params) => inst.check(refine2(check2, params)); - inst.superRefine = (refinement) => inst.check(superRefine2(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite2(fn)); - inst.optional = () => optional2(inst); - inst.nullable = () => nullable2(inst); - inst.nullish = () => optional2(nullable2(inst)); - inst.nonoptional = (params) => nonoptional2(inst, params); - inst.array = () => array2(inst); - inst.or = (arg) => union2([inst, arg]); - inst.and = (arg) => intersection2(inst, arg); - inst.transform = (tx) => pipe2(inst, transform2(tx)); - inst.default = (def2) => _default5(inst, def2); - inst.prefault = (def2) => prefault2(inst, def2); - inst.catch = (params) => _catch4(inst, params); - inst.pipe = (target) => pipe2(inst, target); - inst.readonly = () => readonly2(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry2.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry2.get(inst)?.description; - }, - configurable: true - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry2.get(inst); - } - const cl = inst.clone(); - globalRegistry2.add(cl, args[0]); - return cl; - }; - inst.isOptional = () => inst.safeParse(undefined).success; - inst.isNullable = () => inst.safeParse(null).success; - return inst; - }); - _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => { - $ZodString2.init(inst, def); - ZodType3.init(inst, def); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex2(...args)); - inst.includes = (...args) => inst.check(_includes2(...args)); - inst.startsWith = (...args) => inst.check(_startsWith2(...args)); - inst.endsWith = (...args) => inst.check(_endsWith2(...args)); - inst.min = (...args) => inst.check(_minLength2(...args)); - inst.max = (...args) => inst.check(_maxLength2(...args)); - inst.length = (...args) => inst.check(_length2(...args)); - inst.nonempty = (...args) => inst.check(_minLength2(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase2(params)); - inst.uppercase = (params) => inst.check(_uppercase2(params)); - inst.trim = () => inst.check(_trim2()); - inst.normalize = (...args) => inst.check(_normalize2(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase2()); - inst.toUpperCase = () => inst.check(_toUpperCase2()); - }); - ZodString3 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => { - $ZodString2.init(inst, def); - _ZodString2.init(inst, def); - inst.email = (params) => inst.check(_email2(ZodEmail2, params)); - inst.url = (params) => inst.check(_url2(ZodURL2, params)); - inst.jwt = (params) => inst.check(_jwt2(ZodJWT2, params)); - inst.emoji = (params) => inst.check(_emoji4(ZodEmoji2, params)); - inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); - inst.uuid = (params) => inst.check(_uuid2(ZodUUID2, params)); - inst.uuidv4 = (params) => inst.check(_uuidv42(ZodUUID2, params)); - inst.uuidv6 = (params) => inst.check(_uuidv62(ZodUUID2, params)); - inst.uuidv7 = (params) => inst.check(_uuidv72(ZodUUID2, params)); - inst.nanoid = (params) => inst.check(_nanoid2(ZodNanoID2, params)); - inst.guid = (params) => inst.check(_guid2(ZodGUID2, params)); - inst.cuid = (params) => inst.check(_cuid3(ZodCUID3, params)); - inst.cuid2 = (params) => inst.check(_cuid22(ZodCUID22, params)); - inst.ulid = (params) => inst.check(_ulid2(ZodULID2, params)); - inst.base64 = (params) => inst.check(_base642(ZodBase642, params)); - inst.base64url = (params) => inst.check(_base64url2(ZodBase64URL2, params)); - inst.xid = (params) => inst.check(_xid2(ZodXID2, params)); - inst.ksuid = (params) => inst.check(_ksuid2(ZodKSUID2, params)); - inst.ipv4 = (params) => inst.check(_ipv42(ZodIPv42, params)); - inst.ipv6 = (params) => inst.check(_ipv62(ZodIPv62, params)); - inst.cidrv4 = (params) => inst.check(_cidrv42(ZodCIDRv42, params)); - inst.cidrv6 = (params) => inst.check(_cidrv62(ZodCIDRv62, params)); - inst.e164 = (params) => inst.check(_e1642(ZodE1642, params)); - inst.datetime = (params) => inst.check(datetime4(params)); - inst.date = (params) => inst.check(date7(params)); - inst.time = (params) => inst.check(time5(params)); - inst.duration = (params) => inst.check(duration4(params)); - }); - ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => { - $ZodStringFormat2.init(inst, def); - _ZodString2.init(inst, def); - }); - ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => { - $ZodEmail2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => { - $ZodGUID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => { - $ZodUUID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => { - $ZodURL2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => { - $ZodEmoji2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => { - $ZodNanoID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => { - $ZodCUID3.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => { - $ZodCUID22.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => { - $ZodULID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => { - $ZodXID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => { - $ZodKSUID2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => { - $ZodIPv42.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => { - $ZodIPv62.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => { - $ZodCIDRv42.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => { - $ZodCIDRv62.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => { - $ZodBase642.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => { - $ZodBase64URL2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => { - $ZodE1642.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => { - $ZodJWT2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => { - $ZodCustomStringFormat2.init(inst, def); - ZodStringFormat2.init(inst, def); - }); - ZodNumber3 = /* @__PURE__ */ $constructor2("ZodNumber", (inst, def) => { - $ZodNumber2.init(inst, def); - ZodType3.init(inst, def); - inst.gt = (value, params) => inst.check(_gt2(value, params)); - inst.gte = (value, params) => inst.check(_gte2(value, params)); - inst.min = (value, params) => inst.check(_gte2(value, params)); - inst.lt = (value, params) => inst.check(_lt2(value, params)); - inst.lte = (value, params) => inst.check(_lte2(value, params)); - inst.max = (value, params) => inst.check(_lte2(value, params)); - inst.int = (params) => inst.check(int2(params)); - inst.safe = (params) => inst.check(int2(params)); - inst.positive = (params) => inst.check(_gt2(0, params)); - inst.nonnegative = (params) => inst.check(_gte2(0, params)); - inst.negative = (params) => inst.check(_lt2(0, params)); - inst.nonpositive = (params) => inst.check(_lte2(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); - inst.step = (value, params) => inst.check(_multipleOf2(value, params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; - }); - ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat2.init(inst, def); - ZodNumber3.init(inst, def); - }); - ZodBoolean3 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => { - $ZodBoolean2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodBigInt3 = /* @__PURE__ */ $constructor2("ZodBigInt", (inst, def) => { - $ZodBigInt2.init(inst, def); - ZodType3.init(inst, def); - inst.gte = (value, params) => inst.check(_gte2(value, params)); - inst.min = (value, params) => inst.check(_gte2(value, params)); - inst.gt = (value, params) => inst.check(_gt2(value, params)); - inst.gte = (value, params) => inst.check(_gte2(value, params)); - inst.min = (value, params) => inst.check(_gte2(value, params)); - inst.lt = (value, params) => inst.check(_lt2(value, params)); - inst.lte = (value, params) => inst.check(_lte2(value, params)); - inst.max = (value, params) => inst.check(_lte2(value, params)); - inst.positive = (params) => inst.check(_gt2(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt2(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte2(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte2(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; - }); - ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat2.init(inst, def); - ZodBigInt3.init(inst, def); - }); - ZodSymbol3 = /* @__PURE__ */ $constructor2("ZodSymbol", (inst, def) => { - $ZodSymbol2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodUndefined3 = /* @__PURE__ */ $constructor2("ZodUndefined", (inst, def) => { - $ZodUndefined2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodNull3 = /* @__PURE__ */ $constructor2("ZodNull", (inst, def) => { - $ZodNull2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodAny3 = /* @__PURE__ */ $constructor2("ZodAny", (inst, def) => { - $ZodAny2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodUnknown3 = /* @__PURE__ */ $constructor2("ZodUnknown", (inst, def) => { - $ZodUnknown2.init(inst, def); - ZodType3.init(inst, def); +function createGlobTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "read", input.path ?? "/"); + const resolvedBackend = await resolveBackend(backend, runtime); + const { pattern, path: path3 = "/" } = input; + const globResult = await resolvedBackend.glob(pattern, path3); + if (globResult.error) + return `Error finding files: ${globResult.error}`; + const infos = filterByPermissions(globResult.files ?? [], permissions, "read", (info) => info.path); + if (infos.length === 0) + return `No files found matching pattern '${pattern}'`; + const result = truncateIfTooLong(infos.map((info) => info.path)); + if (Array.isArray(result)) + return result.join(` +`); + return result; + }, { + name: "glob", + description: customDescription || GLOB_TOOL_DESCRIPTION, + schema: exports_external.object({ + pattern: exports_external.string().describe("Glob pattern (e.g., '*.py', '**/*.ts')"), + path: exports_external.string().optional().default("/").describe("Base path to search from (default: /)") + }) }); - ZodNever3 = /* @__PURE__ */ $constructor2("ZodNever", (inst, def) => { - $ZodNever2.init(inst, def); - ZodType3.init(inst, def); +} +function createGrepTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + enforcePermission(permissions, "read", input.path ?? "/"); + const resolvedBackend = await resolveBackend(backend, runtime); + const { pattern, path: path3 = "/", glob = null } = input; + const result = await resolvedBackend.grep(pattern, path3, glob); + if (result.error) + return result.error; + const matches = filterByPermissions(result.matches ?? [], permissions, "read", (m) => m.path); + if (matches.length === 0) + return `No matches found for pattern '${pattern}'`; + const lines = []; + let currentFile = null; + for (const match2 of matches) { + if (match2.path !== currentFile) { + currentFile = match2.path; + lines.push(` +${currentFile}:`); + } + lines.push(` ${match2.line}: ${match2.text}`); + } + const truncated = truncateIfTooLong(lines); + if (Array.isArray(truncated)) + return truncated.join(` +`); + return truncated; + }, { + name: "grep", + description: customDescription || GREP_TOOL_DESCRIPTION, + schema: exports_external.object({ + pattern: exports_external.string().describe("Regex pattern to search for"), + path: exports_external.string().optional().default("/").describe("Base path to search from (default: /)"), + glob: exports_external.string().optional().nullable().default(null).describe("Optional glob pattern to filter files (e.g., '*.py')") + }) }); - ZodVoid3 = /* @__PURE__ */ $constructor2("ZodVoid", (inst, def) => { - $ZodVoid2.init(inst, def); - ZodType3.init(inst, def); +} +function createExecuteTool(backend, options) { + const { customDescription, permissions } = options; + return tool$1(async (input, runtime) => { + const resolvedBackend = await resolveBackend(backend, runtime); + if (!isSandboxBackend(resolvedBackend)) + return "Error: Execution not available. This agent's backend does not support command execution (SandboxBackendProtocol). To use the execute tool, provide a backend that implements SandboxBackendProtocol."; + if (permissions.length > 0 && !allPathsScopedToRoutes(permissions, resolvedBackend)) + return "Error: Execution not available. Filesystem permissions cannot be used with a backend that supports command execution because shell commands can access any path, making path-based rules ineffective."; + const result = await resolvedBackend.execute(input.command); + const parts = [result.output]; + if (result.exitCode !== null) { + const status = result.exitCode === 0 ? "succeeded" : "failed"; + parts.push(` +[Command ${status} with exit code ${result.exitCode}]`); + } + if (result.truncated) + parts.push(` +[Output was truncated due to size limits]`); + return parts.join(""); + }, { + name: "execute", + description: customDescription || EXECUTE_TOOL_DESCRIPTION, + schema: exports_external.object({ command: exports_external.string().describe("The shell command to execute") }) }); - ZodDate3 = /* @__PURE__ */ $constructor2("ZodDate", (inst, def) => { - $ZodDate2.init(inst, def); - ZodType3.init(inst, def); - inst.min = (value, params) => inst.check(_gte2(value, params)); - inst.max = (value, params) => inst.check(_lte2(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; +} +function allPathsScopedToRoutes(permissions, backend) { + if (!CompositeBackend.isInstance(backend)) + return false; + const prefixes = backend.routePrefixes; + if (prefixes.length === 0) + return false; + return permissions.every((rule) => rule.paths.every((path3) => prefixes.some((prefix) => path3.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`)))); +} +function createFilesystemMiddleware(options = {}) { + const { backend = (runtime) => new StateBackend(runtime), systemPrompt: customSystemPrompt = null, customToolDescriptions = null, toolTokenLimitBeforeEvict = 20000, humanMessageTokenLimitBeforeEvict = 50000, permissions = [] } = options; + if (permissions.length > 0) + validatePermissionPaths(permissions); + if (permissions.length > 0 && typeof backend !== "function" && isSandboxBackend(backend) && !allPathsScopedToRoutes(permissions, backend)) + throw new Error("Filesystem permissions cannot be used with a backend that supports command execution. Shell commands can access any path, making path-based rules ineffective. Either remove permissions, use a backend without execution support, or use a CompositeBackend with all permission paths scoped to a route prefix."); + const baseSystemPrompt = customSystemPrompt || FILESYSTEM_SYSTEM_PROMPT; + const allToolsByName = { + ls: createLsTool(backend, { + customDescription: customToolDescriptions?.ls, + permissions + }), + read_file: createReadFileTool(backend, { + customDescription: customToolDescriptions?.read_file, + toolTokenLimitBeforeEvict, + permissions + }), + write_file: createWriteFileTool(backend, { + customDescription: customToolDescriptions?.write_file, + permissions + }), + edit_file: createEditFileTool(backend, { + customDescription: customToolDescriptions?.edit_file, + permissions + }), + glob: createGlobTool(backend, { + customDescription: customToolDescriptions?.glob, + permissions + }), + grep: createGrepTool(backend, { + customDescription: customToolDescriptions?.grep, + permissions + }), + execute: createExecuteTool(backend, { + customDescription: customToolDescriptions?.execute, + permissions + }) + }; + return createMiddleware({ + name: "FilesystemMiddleware", + stateSchema: FilesystemStateSchema, + tools: Object.values(allToolsByName), + async beforeAgent(state) { + if (!humanMessageTokenLimitBeforeEvict) + return; + const messages = state.messages; + if (!messages || messages.length === 0) + return; + const last = messages[messages.length - 1]; + if (!HumanMessage.isInstance(last)) + return; + if (last.additional_kwargs?.lc_evicted_to) + return; + const contentStr = extractTextFromMessage(last); + const threshold = 4 * humanMessageTokenLimitBeforeEvict; + if (contentStr.length <= threshold) + return; + const resolvedBackend = await resolveBackend(backend, { state: state || {} }); + const filePath = `/conversation_history/${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`; + const writeResult = await resolvedBackend.write(filePath, contentStr); + if (writeResult.error) + return; + const result = { messages: [new HumanMessage({ + content: last.content, + id: last.id, + additional_kwargs: { + ...last.additional_kwargs, + lc_evicted_to: filePath + }, + response_metadata: { ...last.response_metadata } + })] }; + if (writeResult.filesUpdate) + result.files = writeResult.filesUpdate; + return result; + }, + wrapModelCall: async (request, handler) => { + const supportsExecution = isSandboxBackend(await resolveBackend(backend, { + ...request.runtime, + state: request.state + })); + let tools = request.tools; + if (!supportsExecution) + tools = tools.filter((t) => t.name !== "execute"); + let filesystemPrompt = baseSystemPrompt; + if (supportsExecution) + filesystemPrompt = `${filesystemPrompt} + +${EXECUTION_SYSTEM_PROMPT}`; + const newSystemMessage = request.systemMessage.concat(filesystemPrompt); + let messages = request.messages; + if (humanMessageTokenLimitBeforeEvict && messages) { + if (messages.some((msg) => HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to)) + messages = messages.map((msg) => { + if (HumanMessage.isInstance(msg) && msg.additional_kwargs?.lc_evicted_to) + return buildTruncatedHumanMessage(msg, msg.additional_kwargs.lc_evicted_to); + return msg; + }); + } + return handler({ + ...request, + tools, + messages, + systemMessage: newSystemMessage + }); + }, + wrapToolCall: async (request, handler) => { + if (!toolTokenLimitBeforeEvict) + return handler(request); + const toolName = request.toolCall?.name; + if (toolName && TOOLS_EXCLUDED_FROM_EVICTION.includes(toolName)) + return handler(request); + const result = await handler(request); + async function processToolMessage(msg, toolTokenLimitBeforeEvict2) { + if (typeof msg.content === "string" && msg.content.length > toolTokenLimitBeforeEvict2 * 4) { + const resolvedBackend = await resolveBackend(backend, { + ...request.runtime, + state: request.state + }); + const evictPath = `/large_tool_results/${sanitizeToolCallId(request.toolCall?.id || msg.tool_call_id)}`; + const writeResult = await resolvedBackend.write(evictPath, msg.content); + if (writeResult.error) + return { + message: msg, + filesUpdate: null + }; + const contentSample = createContentPreview(msg.content); + return { + message: new ToolMessage({ + content: TOO_LARGE_TOOL_MSG.replace("{tool_call_id}", msg.tool_call_id).replace("{file_path}", evictPath).replace("{content_sample}", contentSample), + tool_call_id: msg.tool_call_id, + name: msg.name, + id: msg.id, + artifact: msg.artifact, + status: msg.status, + metadata: msg.metadata, + additional_kwargs: msg.additional_kwargs, + response_metadata: msg.response_metadata + }), + filesUpdate: writeResult.filesUpdate + }; + } + return { + message: msg, + filesUpdate: null + }; + } + if (ToolMessage.isInstance(result)) { + const processed = await processToolMessage(result, toolTokenLimitBeforeEvict); + if (processed.filesUpdate) + return new Command2({ update: { + files: processed.filesUpdate, + messages: [processed.message] + } }); + return processed.message; + } + if (isCommand2(result)) { + const update = result.update; + if (!update?.messages) + return result; + let hasLargeResults = false; + const accumulatedFiles = update.files ? { ...update.files } : {}; + const processedMessages = []; + for (const msg of update.messages) + if (ToolMessage.isInstance(msg)) { + const processed = await processToolMessage(msg, toolTokenLimitBeforeEvict); + processedMessages.push(processed.message); + if (processed.filesUpdate) { + hasLargeResults = true; + Object.assign(accumulatedFiles, processed.filesUpdate); + } + } else + processedMessages.push(msg); + if (hasLargeResults) + return new Command2({ update: { + ...update, + messages: processedMessages, + files: accumulatedFiles + } }); + } + return result; + } }); - ZodArray3 = /* @__PURE__ */ $constructor2("ZodArray", (inst, def) => { - $ZodArray2.init(inst, def); - ZodType3.init(inst, def); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength2(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength2(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength2(maxLength, params)); - inst.length = (len, params) => inst.check(_length2(len, params)); - inst.unwrap = () => inst.element; +} +function getTaskToolDescription(subagentDescriptions) { + return context` + Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows. + + Available agent types and the tools they have access to: + ${subagentDescriptions.join(` +`)} + + When using the Task tool, you must specify a subagent_type parameter to select which agent type to use. + + ## Usage notes: + 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses + 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. + 3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. + 4. The agent's outputs should generally be trusted + 5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent + 6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement. + 7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent. + + ### Example usage of the general-purpose agent: + + + "general-purpose": use this agent for general purpose tasks, it has access to all tools as the main agent. + + + + User: "I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them." + Assistant: *Uses the task tool in parallel to conduct isolated research on each of the three players* + Assistant: *Synthesizes the results of the three isolated research tasks and responds to the User* + + Research is a complex, multi-step task in it of itself. + The research of each individual player is not dependent on the research of the other players. + The assistant uses the task tool to break down the complex objective into three isolated tasks. + Each research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result. + This means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other. + + + + + User: "Analyze a single large code repository for security vulnerabilities and generate a report." + Assistant: *Launches a single \`task\` subagent for the repository analysis* + Assistant: *Receives report and integrates results into final summary* + + Subagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details. + If the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money. + + + + + User: "Schedule two meetings for me and prepare agendas for each." + Assistant: *Calls the task tool in parallel to launch two \`task\` subagents (one per meeting) to prepare agendas* + Assistant: *Returns final schedules and agendas* + + Tasks are simple individually, but subagents help silo agenda preparation. + Each subagent only needs to worry about the agenda for one meeting. + + + + + User: "I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway." + Assistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway* + + The assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls. + It is better to just complete the task directly and NOT use the \`task\`tool. + + + + ### Example usage with custom agents: + + + "content-reviewer": use this agent after you are done creating significant content or documents + "greeting-responder": use this agent when to respond to user greetings with a friendly joke + "research-analyst": use this agent to conduct thorough research on complex topics + + + + user: "Please write a function that checks if a number is prime" + assistant: Sure let me write a function that checks if a number is prime + assistant: First let me use the Write tool to write a function that checks if a number is prime + assistant: I'm going to use the Write tool to write the following code: + + function isPrime(n) {{ + if (n <= 1) return false + for (let i = 2; i * i <= n; i++) {{ + if (n % i === 0) return false + }} + return true + }} + + + Since significant content was created and the task was completed, now use the content-reviewer agent to review the work + + assistant: Now let me use the content-reviewer agent to review the code + assistant: Uses the Task tool to launch with the content-reviewer agent + + + + user: "Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?" + + This is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis + + assistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic. + assistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take + + + + user: "Hello" + + Since the user is greeting, use the greeting-responder agent to respond with a friendly joke + + assistant: "I'm going to use the Task tool to launch with the greeting-responder agent" + + `; +} +function filterStateForSubagent(state) { + const filtered = {}; + for (const [key, value] of Object.entries(state)) + if (!EXCLUDED_STATE_KEYS.includes(key)) + filtered[key] = value; + return filtered; +} +function returnCommandWithStateUpdate(result, toolCallId) { + const stateUpdate = filterStateForSubagent(result); + let content; + if (result.structuredResponse != null) + content = JSON.stringify(result.structuredResponse); + else { + const messages = result.messages; + content = messages?.[messages.length - 1]?.content || "Task completed"; + if (Array.isArray(content)) { + content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type)); + if (content.length === 0) + content = "Task completed"; + } + } + return new Command2({ update: { + ...stateUpdate, + messages: [new ToolMessage({ + content, + tool_call_id: toolCallId, + name: "task" + })] + } }); +} +function getSubagents(options) { + const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware: gpMiddleware, defaultInterruptOn, subagents, generalPurposeAgent } = options; + const defaultSubagentMiddleware = defaultMiddleware || []; + const generalPurposeMiddlewareBase = gpMiddleware || defaultSubagentMiddleware; + const agents = {}; + const subagentDescriptions = []; + if (generalPurposeAgent) { + const generalPurposeMiddleware = [...generalPurposeMiddlewareBase]; + if (defaultInterruptOn) + generalPurposeMiddleware.push(humanInTheLoopMiddleware({ interruptOn: defaultInterruptOn })); + agents["general-purpose"] = createAgent({ + model: defaultModel, + systemPrompt: DEFAULT_SUBAGENT_PROMPT, + tools: defaultTools, + middleware: generalPurposeMiddleware, + name: "general-purpose" + }); + subagentDescriptions.push(`- general-purpose: ${DEFAULT_GENERAL_PURPOSE_DESCRIPTION}`); + } + for (const agentParams of subagents) { + subagentDescriptions.push(`- ${agentParams.name}: ${agentParams.description}`); + if ("runnable" in agentParams) + agents[agentParams.name] = agentParams.runnable; + else { + const middleware = agentParams.middleware ? [...defaultSubagentMiddleware, ...agentParams.middleware] : [...defaultSubagentMiddleware]; + const interruptOn = agentParams.interruptOn || defaultInterruptOn; + if (interruptOn) + middleware.push(humanInTheLoopMiddleware({ interruptOn })); + agents[agentParams.name] = createAgent({ + model: agentParams.model ?? defaultModel, + systemPrompt: agentParams.systemPrompt, + tools: agentParams.tools ?? defaultTools, + middleware, + name: agentParams.name, + ...agentParams.responseFormat != null && { responseFormat: agentParams.responseFormat } + }); + } + } + return { + agents, + descriptions: subagentDescriptions + }; +} +function createTaskTool(options) { + const { defaultModel, defaultTools, defaultMiddleware, generalPurposeMiddleware, defaultInterruptOn, subagents, generalPurposeAgent, taskDescription } = options; + const { agents: subagentGraphs, descriptions: subagentDescriptions } = getSubagents({ + defaultModel, + defaultTools, + defaultMiddleware, + generalPurposeMiddleware, + defaultInterruptOn, + subagents, + generalPurposeAgent }); - ZodObject3 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def) => { - $ZodObject2.init(inst, def); - ZodType3.init(inst, def); - exports_util2.defineLazy(inst, "shape", () => def.shape); - inst.keyof = () => _enum4(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never2() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); - inst.extend = (incoming) => { - return exports_util2.extend(inst, incoming); + return tool$1(async (input, config3) => { + const { description, subagent_type } = input; + if (!(subagent_type in subagentGraphs)) { + const allowedTypes = Object.keys(subagentGraphs).map((k) => `\`${k}\``).join(", "); + throw new Error(`Error: invoked agent of type ${subagent_type}, the only allowed types are ${allowedTypes}`); + } + const subagent = subagentGraphs[subagent_type]; + const subagentState = filterStateForSubagent(getCurrentTaskInput2()); + subagentState.messages = [new HumanMessage({ content: description })]; + const subagentConfig = { + ...config3, + configurable: { + ...config3.configurable, + ls_agent_type: "subagent" + } }; - inst.merge = (other) => exports_util2.merge(inst, other); - inst.pick = (mask) => exports_util2.pick(inst, mask); - inst.omit = (mask) => exports_util2.omit(inst, mask); - inst.partial = (...args) => exports_util2.partial(ZodOptional3, inst, args[0]); - inst.required = (...args) => exports_util2.required(ZodNonOptional2, inst, args[0]); - }); - ZodUnion3 = /* @__PURE__ */ $constructor2("ZodUnion", (inst, def) => { - $ZodUnion2.init(inst, def); - ZodType3.init(inst, def); - inst.options = def.options; - }); - ZodDiscriminatedUnion3 = /* @__PURE__ */ $constructor2("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion3.init(inst, def); - $ZodDiscriminatedUnion2.init(inst, def); - }); - ZodIntersection3 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, def) => { - $ZodIntersection2.init(inst, def); - ZodType3.init(inst, def); + const result = await subagent.invoke(subagentState, subagentConfig); + if (!config3.toolCall?.id) { + if (result.structuredResponse != null) + return JSON.stringify(result.structuredResponse); + const messages = result.messages; + let content = messages?.[messages.length - 1]?.content || "Task completed"; + if (Array.isArray(content)) { + content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type)); + if (content.length === 0) + return "Task completed"; + return content.map((block) => ("text" in block) ? block.text : JSON.stringify(block)).join(` +`); + } + return content; + } + return returnCommandWithStateUpdate(result, config3.toolCall.id); + }, { + name: "task", + description: taskDescription ? taskDescription : getTaskToolDescription(subagentDescriptions), + schema: exports_external.object({ + description: exports_external.string().describe("The task to execute with the selected agent"), + subagent_type: exports_external.string().describe(`Name of the agent to use. Available: ${Object.keys(subagentGraphs).join(", ")}`) + }) }); - ZodTuple3 = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => { - $ZodTuple2.init(inst, def); - ZodType3.init(inst, def); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest - }); +} +function createSubAgentMiddleware(options) { + const { defaultModel, defaultTools = [], defaultMiddleware = null, generalPurposeMiddleware = null, defaultInterruptOn = null, subagents = [], systemPrompt = TASK_SYSTEM_PROMPT, generalPurposeAgent = true, taskDescription = null } = options; + return createMiddleware({ + name: "subAgentMiddleware", + tools: [createTaskTool({ + defaultModel, + defaultTools, + defaultMiddleware, + generalPurposeMiddleware, + defaultInterruptOn, + subagents, + generalPurposeAgent, + taskDescription + })], + wrapModelCall: async (request, handler) => { + if (systemPrompt !== null) + return handler({ + ...request, + systemMessage: request.systemMessage.concat(new SystemMessage({ content: systemPrompt })) + }); + return handler(request); + } }); - ZodRecord3 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => { - $ZodRecord2.init(inst, def); - ZodType3.init(inst, def); - inst.keyType = def.keyType; - inst.valueType = def.valueType; +} +function patchDanglingToolCalls(messages) { + if (!messages || messages.length === 0) + return { + patchedMessages: [], + needsPatch: false + }; + const allToolCallIds = /* @__PURE__ */ new Set; + for (const msg of messages) + if (AIMessage.isInstance(msg) && msg.tool_calls != null) { + for (const tc of msg.tool_calls) + if (tc.id) + allToolCallIds.add(tc.id); + } + const patchedMessages = []; + let needsPatch = false; + for (let i = 0;i < messages.length; i++) { + const msg = messages[i]; + if (ToolMessage.isInstance(msg)) { + if (!allToolCallIds.has(msg.tool_call_id)) { + needsPatch = true; + continue; + } + } + patchedMessages.push(msg); + if (AIMessage.isInstance(msg) && msg.tool_calls != null) { + for (const toolCall of msg.tool_calls) + if (!messages.slice(i + 1).find((m) => ToolMessage.isInstance(m) && m.tool_call_id === toolCall.id)) { + needsPatch = true; + const toolMsg = `Tool call ${toolCall.name} with id ${toolCall.id} was cancelled - another message came in before it could be completed.`; + patchedMessages.push(new ToolMessage({ + content: toolMsg, + name: toolCall.name, + tool_call_id: toolCall.id + })); + } + } + } + return { + patchedMessages, + needsPatch + }; +} +function createPatchToolCallsMiddleware() { + return createMiddleware({ + name: "patchToolCallsMiddleware", + beforeAgent: async (state) => { + const messages = state.messages; + if (!messages || messages.length === 0) + return; + const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); + if (!needsPatch) + return; + return { messages: [new RemoveMessage({ id: REMOVE_ALL_MESSAGES2 }), ...patchedMessages] }; + }, + wrapModelCall: async (request, handler) => { + const messages = request.messages; + if (!messages || messages.length === 0) + return handler(request); + const { patchedMessages, needsPatch } = patchDanglingToolCalls(messages); + if (!needsPatch) + return handler(request); + return handler({ + ...request, + messages: patchedMessages + }); + } }); - ZodMap3 = /* @__PURE__ */ $constructor2("ZodMap", (inst, def) => { - $ZodMap2.init(inst, def); - ZodType3.init(inst, def); - inst.keyType = def.keyType; - inst.valueType = def.valueType; +} +function formatMemoryContents(contents, sources) { + if (Object.keys(contents).length === 0) + return "(No memory loaded)"; + const sections = []; + for (const path3 of sources) + if (contents[path3]) + sections.push(`${path3} +${contents[path3]}`); + if (sections.length === 0) + return "(No memory loaded)"; + return sections.join(` + +`); +} +async function loadMemoryFromBackend(backend, path3) { + const adaptedBackend = adaptBackendProtocol(backend); + if (!adaptedBackend.downloadFiles) { + const content = await adaptedBackend.read(path3); + if (content.error) + return null; + if (typeof content.content !== "string") + return null; + return content.content; + } + const results = await adaptedBackend.downloadFiles([path3]); + if (results.length !== 1) + throw new Error(`Expected 1 response for path ${path3}, got ${results.length}`); + const response = results[0]; + if (response.error != null) { + if (response.error === "file_not_found") + return null; + throw new Error(`Failed to download ${path3}: ${response.error}`); + } + if (response.content != null) + return new TextDecoder().decode(response.content); + return null; +} +function createMemoryMiddleware(options) { + const { backend, sources, addCacheControl = false } = options; + return createMiddleware({ + name: "MemoryMiddleware", + stateSchema: MemoryStateSchema, + async beforeAgent(state) { + if ("memoryContents" in state && state.memoryContents != null) + return; + const resolvedBackend = await resolveBackend(backend, { state }); + const contents = {}; + for (const path3 of sources) + try { + const content = await loadMemoryFromBackend(resolvedBackend, path3); + if (content) + contents[path3] = content; + } catch (error90) { + console.debug(`Failed to load memory from ${path3}:`, error90); + } + return { memoryContents: contents }; + }, + wrapModelCall(request, handler) { + const formattedContents = formatMemoryContents(request.state?.memoryContents || {}, sources); + const memorySection = MEMORY_SYSTEM_PROMPT.replace("{memory_contents}", formattedContents); + const existingContent = request.systemMessage.content; + const newSystemMessage = new SystemMessage({ content: [...typeof existingContent === "string" ? [{ + type: "text", + text: existingContent + }] : Array.isArray(existingContent) ? existingContent : [], { + type: "text", + text: memorySection, + ...addCacheControl && { cache_control: { type: "ephemeral" } } + }] }); + return handler({ + ...request, + systemMessage: newSystemMessage + }); + } }); - ZodSet3 = /* @__PURE__ */ $constructor2("ZodSet", (inst, def) => { - $ZodSet2.init(inst, def); - ZodType3.init(inst, def); - inst.min = (...args) => inst.check(_minSize2(...args)); - inst.nonempty = (params) => inst.check(_minSize2(1, params)); - inst.max = (...args) => inst.check(_maxSize2(...args)); - inst.size = (...args) => inst.check(_size2(...args)); +} +function skillsMetadataReducer(current, update) { + if (!update || update.length === 0) + return current || []; + if (!current || current.length === 0) + return update; + const merged = /* @__PURE__ */ new Map; + for (const skill of current) + merged.set(skill.name, skill); + for (const skill of update) + merged.set(skill.name, skill); + return Array.from(merged.values()); +} +function validateSkillName$1(name, directoryName) { + if (!name) + return { + valid: false, + error: "name is required" + }; + if (name.length > 64) + return { + valid: false, + error: "name exceeds 64 characters" + }; + if (name.startsWith("-") || name.endsWith("-") || name.includes("--")) + return { + valid: false, + error: "name must be lowercase alphanumeric with single hyphens only" + }; + for (const c of name) { + if (c === "-") + continue; + if (/\p{Ll}/u.test(c) || /\p{Nd}/u.test(c)) + continue; + return { + valid: false, + error: "name must be lowercase alphanumeric with single hyphens only" + }; + } + if (name !== directoryName) + return { + valid: false, + error: `name '${name}' must match directory name '${directoryName}'` + }; + return { + valid: true, + error: "" + }; +} +function validateMetadata(raw2, skillPath) { + if (typeof raw2 !== "object" || raw2 === null || Array.isArray(raw2)) { + if (raw2) + console.warn(`Ignoring non-object metadata in ${skillPath} (got ${typeof raw2})`); + return {}; + } + const result = {}; + for (const [k, v] of Object.entries(raw2)) + result[String(k)] = String(v); + return result; +} +function formatSkillAnnotations(skill) { + const parts = []; + if (skill.license) + parts.push(`License: ${skill.license}`); + if (skill.compatibility) + parts.push(`Compatibility: ${skill.compatibility}`); + return parts.join(", "); +} +function parseSkillMetadataFromContent(content, skillPath, directoryName) { + if (content.length > 10485760) { + console.warn(`Skipping ${skillPath}: content too large (${content.length} bytes)`); + return null; + } + const match2 = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/); + if (!match2) { + console.warn(`Skipping ${skillPath}: no valid YAML frontmatter found`); + return null; + } + const frontmatterStr = match2[1]; + let frontmatterData; + try { + frontmatterData = import_yaml.default.parse(frontmatterStr); + } catch (e) { + console.warn(`Invalid YAML in ${skillPath}:`, e); + return null; + } + if (!frontmatterData || typeof frontmatterData !== "object") { + console.warn(`Skipping ${skillPath}: frontmatter is not a mapping`); + return null; + } + const name = String(frontmatterData.name ?? "").trim(); + const description = String(frontmatterData.description ?? "").trim(); + if (!name || !description) { + console.warn(`Skipping ${skillPath}: missing required 'name' or 'description'`); + return null; + } + const validation = validateSkillName$1(name, directoryName); + if (!validation.valid) + console.warn(`Skill '${name}' in ${skillPath} does not follow Agent Skills specification: ${validation.error}. Consider renaming for spec compliance.`); + let descriptionStr = description; + if (descriptionStr.length > 1024) { + console.warn(`Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH} characters in ${skillPath}, truncating`); + descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH); + } + const rawTools = frontmatterData["allowed-tools"]; + let allowedTools; + if (rawTools) + if (Array.isArray(rawTools)) + allowedTools = rawTools.map((t) => String(t).trim()).filter(Boolean); + else + allowedTools = String(rawTools).split(/\s+/).filter(Boolean); + else + allowedTools = []; + let compatibilityStr = String(frontmatterData.compatibility ?? "").trim() || null; + if (compatibilityStr && compatibilityStr.length > 500) { + console.warn(`Compatibility exceeds 500 characters in ${skillPath}, truncating`); + compatibilityStr = compatibilityStr.slice(0, 500); + } + return { + name, + description: descriptionStr, + path: skillPath, + metadata: validateMetadata(frontmatterData.metadata ?? {}, skillPath), + license: String(frontmatterData.license ?? "").trim() || null, + compatibility: compatibilityStr, + allowedTools, + module: validateModulePath(frontmatterData.module) + }; +} +async function listSkillsFromBackend(backend, sourcePath) { + const adaptedBackend = adaptBackendProtocol(backend); + const skills = []; + const pathSep = sourcePath.includes("\\") ? "\\" : "/"; + const normalizedPath = sourcePath.endsWith("/") || sourcePath.endsWith("\\") ? sourcePath : `${sourcePath}${pathSep}`; + let fileInfos; + try { + const lsResult = await adaptedBackend.ls(normalizedPath); + if (lsResult.error || !lsResult.files) + return []; + fileInfos = lsResult.files; + } catch { + return []; + } + const entries = fileInfos.map((info) => ({ + name: info.path.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "", + type: info.is_dir ? "directory" : "file" + })); + for (const entry of entries) { + if (entry.type !== "directory") + continue; + const skillMdPath = `${normalizedPath}${entry.name}${pathSep}SKILL.md`; + let content; + if (adaptedBackend.downloadFiles) { + const results = await adaptedBackend.downloadFiles([skillMdPath]); + if (results.length !== 1) + continue; + const response = results[0]; + if (response.error != null || response.content == null) + continue; + content = new TextDecoder().decode(response.content); + } else { + const readResult = await adaptedBackend.read(skillMdPath); + if (readResult.error) + continue; + if (typeof readResult.content !== "string") + continue; + content = readResult.content; + } + const metadata = parseSkillMetadataFromContent(content, skillMdPath, entry.name); + if (metadata) + skills.push(metadata); + } + return skills; +} +function formatSkillsLocations(sources) { + if (sources.length === 0) + return "**Skills Sources:** None configured"; + const lines = []; + for (let i = 0;i < sources.length; i++) { + const sourcePath = sources[i]; + const name = sourcePath.replace(/[/\\]$/, "").split(/[/\\]/).filter(Boolean).pop()?.replace(/^./, (c) => c.toUpperCase()) || "Skills"; + const suffix = i === sources.length - 1 ? " (higher priority)" : ""; + lines.push(`**${name} Skills**: \`${sourcePath}\`${suffix}`); + } + return lines.join(` +`); +} +function formatSkillsList(skills, sources) { + if (skills.length === 0) + return `(No skills available yet. You can create skills in ${sources.map((s) => `\`${s}\``).join(" or ")})`; + const lines = []; + for (const skill of skills) { + const annotations = formatSkillAnnotations(skill); + let descLine = `- **${skill.name}**: ${skill.description}`; + if (annotations) + descLine += ` (${annotations})`; + lines.push(descLine); + if (skill.allowedTools && skill.allowedTools.length > 0) + lines.push(` → Allowed tools: ${skill.allowedTools.join(", ")}`); + lines.push(` → Read \`${skill.path}\` for full instructions`); + if (skill.module !== undefined) + lines.push(` → Import: \`await import("@/skills/${skill.name}")\``); + } + return lines.join(` +`); +} +function endsWithModuleExtension(value) { + for (const ext of SKILL_MODULE_EXTENSIONS) + if (value.endsWith(ext)) + return true; + return false; +} +function validateModulePath(raw2) { + if (raw2 === null || raw2 === undefined) + return; + if (typeof raw2 !== "string") + return; + const stripped = raw2.trim(); + if (stripped === "") + return; + const normalized = stripped.startsWith("./") ? stripped.slice(2) : stripped; + if (normalized.startsWith("/")) + return; + if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../") || normalized.endsWith("/..")) + return; + if (normalized.endsWith(".d.ts") || normalized.endsWith(".d.mts") || normalized.endsWith(".d.cts")) + return; + if (!endsWithModuleExtension(normalized)) + return; + return normalized; +} +function createSkillsMiddleware(options) { + const { backend, sources } = options; + let loadedSkills = []; + return createMiddleware({ + name: "SkillsMiddleware", + stateSchema: SkillsStateSchema, + async beforeAgent(state) { + if (loadedSkills.length > 0) + return; + if ("skillsMetadata" in state && Array.isArray(state.skillsMetadata) && state.skillsMetadata.length > 0) { + loadedSkills = state.skillsMetadata; + return; + } + const resolvedBackend = await resolveBackend(backend, { state }); + const allSkills = /* @__PURE__ */ new Map; + for (const sourcePath of sources) + try { + const skills = await listSkillsFromBackend(resolvedBackend, sourcePath); + for (const skill of skills) + allSkills.set(skill.name, skill); + } catch (error90) { + console.debug(`[BackendSkillsMiddleware] Failed to load skills from ${sourcePath}:`, error90); + } + loadedSkills = Array.from(allSkills.values()); + return { skillsMetadata: loadedSkills }; + }, + wrapModelCall(request, handler) { + const skillsMetadata = loadedSkills.length > 0 ? loadedSkills : request.state?.skillsMetadata || []; + const skillsLocations = formatSkillsLocations(sources); + const skillsList = formatSkillsList(skillsMetadata, sources); + const skillsSection = SKILLS_SYSTEM_PROMPT.replace("{skills_locations}", skillsLocations).replace("{skills_list}", skillsList); + const newSystemMessage = request.systemMessage.concat(skillsSection); + return handler({ + ...request, + systemMessage: newSystemMessage + }); + } }); - ZodEnum3 = /* @__PURE__ */ $constructor2("ZodEnum", (inst, def) => { - $ZodEnum2.init(inst, def); - ZodType3.init(inst, def); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values2, params) => { - const newEntries = {}; - for (const value of values2) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; +} +function resolveHeaders(headers) { + const resolved = { ...headers }; + if (!("x-auth-scheme" in resolved)) + resolved["x-auth-scheme"] = "langsmith"; + return resolved; +} +async function notifyParent(callbackGraphId, callbackThreadId, message, options) { + try { + await new Client2({ + apiUrl: options?.url ?? undefined, + apiKey: null, + defaultHeaders: resolveHeaders(options?.headers) + }).runs.create(callbackThreadId, callbackGraphId, { input: { messages: [{ + role: "user", + content: message + }] } }); + } catch (e) { + console.warn(`[CompletionCallbackMiddleware] Failed to notify callback thread ${callbackThreadId}:`, e); + } +} +function extractLastMessage(state, taskId) { + const messages = state.messages; + if (!messages || messages.length === 0) + throw new Error(`Expected at least one message in state ${JSON.stringify(state)}`); + const last = messages[messages.length - 1]; + if (!AIMessage.isInstance(last)) + throw new TypeError(`Expected an AIMessage, got ${typeof last === "object" && last !== null ? last.constructor?.name ?? typeof last : typeof last} instead`); + let textContent = last.text; + if (textContent.length > MAX_MESSAGE_LENGTH) { + textContent = textContent.slice(0, MAX_MESSAGE_LENGTH) + TRUNCATION_SUFFIX; + if (taskId) + textContent += ` Result truncated. Use \`check_async_task(task_id='${taskId}')\` to retrieve the full result if needed.`; + } + return textContent; +} +function createCompletionCallbackMiddleware(options) { + const { callbackGraphId, url: url3, headers } = options; + async function sendNotification(callbackThreadId, message) { + await notifyParent(callbackGraphId, callbackThreadId, message, { + url: url3, + headers + }); + } + function getTaskId(runtime) { + return runtime?.configurable?.thread_id; + } + function formatNotification(body, runtime) { + const taskId = getTaskId(runtime); + return `${taskId ? `[task_id=${taskId}]` : ""}${body}`; + } + return createMiddleware({ + name: "CompletionCallbackMiddleware", + stateSchema: CompletionCallbackStateSchema, + async afterAgent(state, runtime) { + const callbackThreadId = state[CALLBACK_THREAD_ID_KEY]; + if (callbackThreadId == null) + throw new Error(`Missing required state key '${CALLBACK_THREAD_ID_KEY}'`); + const taskId = getTaskId(runtime); + await sendNotification(callbackThreadId, formatNotification(`Completed. Result: ${extractLastMessage(state, typeof taskId === "string" ? taskId : undefined)}`, runtime)); + }, + async wrapModelCall(request, handler) { + try { + return await handler(request); + } catch (e) { + const callbackThreadId = request.state[CALLBACK_THREAD_ID_KEY]; + if (typeof callbackThreadId === "string") + await sendNotification(callbackThreadId, formatNotification("The agent encountered an error while calling the model.", request.runtime)); + throw e; + } + } + }); +} +function computeSummarizationDefaults(resolvedModel) { + if (resolvedModel.profile && typeof resolvedModel.profile === "object" && "maxInputTokens" in resolvedModel.profile && typeof resolvedModel.profile.maxInputTokens === "number") + return { + trigger: PROFILE_TRIGGER, + keep: PROFILE_KEEP, + truncateArgsSettings: PROFILE_TRUNCATE_ARGS + }; + return { + trigger: FALLBACK_TRIGGER, + keep: FALLBACK_KEEP, + truncateArgsSettings: FALLBACK_TRUNCATE_ARGS + }; +} +function isSummaryMessage(msg) { + if (!HumanMessage.isInstance(msg)) + return false; + return msg.additional_kwargs?.lc_source === "summarization"; +} +function createSummarizationMiddleware(options) { + const { model, backend, summaryPrompt = DEFAULT_SUMMARY_PROMPT2, trimTokensToSummarize = DEFAULT_TRIM_TOKEN_LIMIT, historyPathPrefix = "/conversation_history" } = options; + let trigger = options.trigger; + let keep = options.keep ?? { + type: "messages", + value: DEFAULT_MESSAGES_TO_KEEP + }; + let truncateArgsSettings = options.truncateArgsSettings; + let defaultsComputed = trigger != null; + let truncateTrigger = truncateArgsSettings?.trigger; + let truncateKeep = truncateArgsSettings?.keep ?? { + type: "messages", + value: 20 + }; + let maxArgLength = truncateArgsSettings?.maxLength ?? 2000; + let truncationText = truncateArgsSettings?.truncationText ?? "...(argument truncated)"; + function applyModelDefaults(resolvedModel) { + if (defaultsComputed) + return; + defaultsComputed = true; + const defaults = computeSummarizationDefaults(resolvedModel); + trigger = defaults.trigger; + keep = options.keep ?? defaults.keep; + if (!options.truncateArgsSettings) { + truncateArgsSettings = defaults.truncateArgsSettings; + truncateTrigger = defaults.truncateArgsSettings.trigger; + truncateKeep = defaults.truncateArgsSettings.keep ?? { + type: "messages", + value: 20 + }; + maxArgLength = defaults.truncateArgsSettings.maxLength ?? 2000; + truncationText = defaults.truncateArgsSettings.truncationText ?? "...(argument truncated)"; + } + } + let sessionId = null; + let tokenEstimationMultiplier = 1; + function getSessionId(state) { + if (state._summarizationSessionId) + return state._summarizationSessionId; + if (!sessionId) + sessionId = `session_${crypto.randomUUID().substring(0, 8)}`; + return sessionId; + } + function getHistoryPath(state) { + return `${historyPathPrefix}/${getSessionId(state)}.md`; + } + let cachedModel = undefined; + async function getChatModel() { + if (cachedModel) + return cachedModel; + if (!model) + throw new Error("Summarization middleware could not resolve a model. Provide `options.model` or ensure `request.model` is present."); + if (typeof model === "string") + cachedModel = await initChatModel(model); + else + cachedModel = model; + return cachedModel; + } + function getMaxInputTokens(resolvedModel) { + const profile = resolvedModel.profile; + if (profile && typeof profile === "object" && "maxInputTokens" in profile && typeof profile.maxInputTokens === "number") + return profile.maxInputTokens; + } + function shouldSummarize(messages, totalTokens, maxInputTokens) { + if (!trigger) + return false; + const adjustedTokens = totalTokens * tokenEstimationMultiplier; + const triggers = Array.isArray(trigger) ? trigger : [trigger]; + for (const t of triggers) { + if (t.type === "messages" && messages.length >= t.value) + return true; + if (t.type === "tokens" && adjustedTokens >= t.value) + return true; + if (t.type === "fraction" && maxInputTokens) { + if (adjustedTokens >= Math.floor(maxInputTokens * t.value)) + return true; + } + } + return false; + } + function findSafeCutoffPoint(messages, cutoffIndex) { + if (cutoffIndex >= messages.length || !ToolMessage.isInstance(messages[cutoffIndex])) + return cutoffIndex; + let forwardIdx = cutoffIndex; + while (forwardIdx < messages.length && ToolMessage.isInstance(messages[forwardIdx])) + forwardIdx++; + const toolCallIds = /* @__PURE__ */ new Set; + for (let i = cutoffIndex;i < forwardIdx; i++) { + const toolMsg = messages[i]; + if (toolMsg.tool_call_id) + toolCallIds.add(toolMsg.tool_call_id); + } + let backwardIdx = null; + for (let i = cutoffIndex - 1;i >= 0; i--) { + const msg = messages[i]; + if (AIMessage.isInstance(msg) && msg.tool_calls) { + const aiToolCallIds = new Set(msg.tool_calls.map((tc) => tc.id).filter((id) => id != null)); + for (const id of toolCallIds) + if (aiToolCallIds.has(id)) { + backwardIdx = i; + break; + } + if (backwardIdx !== null) + break; + } + } + if (backwardIdx === null) + return forwardIdx; + if (cutoffIndex - backwardIdx > cutoffIndex / 2 && cutoffIndex > 2) + return forwardIdx; + return backwardIdx; + } + function determineCutoffIndex(messages, maxInputTokens) { + let rawCutoff; + if (keep.type === "messages") { + if (messages.length <= keep.value) + return 0; + rawCutoff = messages.length - keep.value; + } else if (keep.type === "tokens" || keep.type === "fraction") { + const targetTokenCount = keep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * keep.value) : keep.value; + let tokensKept = 0; + rawCutoff = 0; + for (let i = messages.length - 1;i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (tokensKept + msgTokens > targetTokenCount) { + rawCutoff = i + 1; + break; + } + tokensKept += msgTokens; + } + } else + return 0; + return findSafeCutoffPoint(messages, rawCutoff); + } + function shouldTruncateArgs(messages, totalTokens, maxInputTokens) { + if (!truncateTrigger) + return false; + const adjustedTokens = totalTokens * tokenEstimationMultiplier; + if (truncateTrigger.type === "messages") + return messages.length >= truncateTrigger.value; + if (truncateTrigger.type === "tokens") + return adjustedTokens >= truncateTrigger.value; + if (truncateTrigger.type === "fraction" && maxInputTokens) + return adjustedTokens >= Math.floor(maxInputTokens * truncateTrigger.value); + return false; + } + function determineTruncateCutoffIndex(messages, maxInputTokens) { + let rawCutoff; + if (truncateKeep.type === "messages") { + if (messages.length <= truncateKeep.value) + return messages.length; + rawCutoff = messages.length - truncateKeep.value; + } else if (truncateKeep.type === "tokens" || truncateKeep.type === "fraction") { + const targetTokenCount = truncateKeep.type === "fraction" && maxInputTokens ? Math.floor(maxInputTokens * truncateKeep.value) : truncateKeep.value; + let tokensKept = 0; + rawCutoff = 0; + for (let i = messages.length - 1;i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (tokensKept + msgTokens > targetTokenCount) { + rawCutoff = i + 1; + break; + } + tokensKept += msgTokens; + } + } else + return messages.length; + return findSafeCutoffPoint(messages, rawCutoff); + } + function countTotalTokens(messages, systemMessage, tools) { + return countTokensApproximately(systemMessage && SystemMessage.isInstance(systemMessage) ? [systemMessage, ...messages] : [...messages], tools && Array.isArray(tools) && tools.length > 0 ? tools : null); + } + function compactToolResults(messages, maxInputTokens, systemMessage, tools) { + const toolMessageIndices = []; + for (let i = 0;i < messages.length; i++) + if (ToolMessage.isInstance(messages[i])) + toolMessageIndices.push(i); + if (toolMessageIndices.length === 0) + return { + messages, + modified: false + }; + const overheadTokens = countTotalTokens(messages.filter((m) => !ToolMessage.isInstance(m)), systemMessage, tools); + const adjustedMax = maxInputTokens / tokenEstimationMultiplier; + const budgetForTools = Math.max(adjustedMax * 0.7 - overheadTokens, 1000); + const perToolBudgetChars = Math.floor(budgetForTools / toolMessageIndices.length) * 4; + let modified = false; + const result = [...messages]; + for (const idx of toolMessageIndices) { + const msg = messages[idx]; + const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content); + if (content.length > perToolBudgetChars) { + result[idx] = new ToolMessage({ + content: content.substring(0, perToolBudgetChars) + ` +...(result truncated)`, + tool_call_id: msg.tool_call_id, + name: msg.name + }); + modified = true; + } + } + return { + messages: result, + modified + }; + } + function truncateArgs(messages, maxInputTokens, systemMessage, tools) { + if (!shouldTruncateArgs(messages, countTotalTokens(messages, systemMessage, tools), maxInputTokens)) + return { + messages, + modified: false + }; + const cutoffIndex = determineTruncateCutoffIndex(messages, maxInputTokens); + if (cutoffIndex >= messages.length) + return { + messages, + modified: false + }; + const truncatedMessages = []; + let modified = false; + for (let i = 0;i < messages.length; i++) { + const msg = messages[i]; + if (i < cutoffIndex && AIMessage.isInstance(msg) && msg.tool_calls) { + const truncatedToolCalls = msg.tool_calls.map((toolCall) => { + const args = toolCall.args || {}; + const truncatedArgs = {}; + let toolModified = false; + for (const [key, value] of Object.entries(args)) + if (typeof value === "string" && value.length > maxArgLength && (toolCall.name === "write_file" || toolCall.name === "edit_file")) { + truncatedArgs[key] = value.substring(0, 20) + truncationText; + toolModified = true; + } else + truncatedArgs[key] = value; + if (toolModified) { + modified = true; + return { + ...toolCall, + args: truncatedArgs + }; + } + return toolCall; + }); + if (modified) { + const truncatedMsg = new AIMessage({ + content: msg.content, + tool_calls: truncatedToolCalls, + additional_kwargs: msg.additional_kwargs + }); + truncatedMessages.push(truncatedMsg); } else - throw new Error(`Key ${value} not found in enum`); + truncatedMessages.push(msg); + } else + truncatedMessages.push(msg); + } + return { + messages: truncatedMessages, + modified + }; + } + function filterSummaryMessages(messages) { + return messages.filter((msg) => !isSummaryMessage(msg)); + } + async function offloadToBackend(resolvedBackend, messages, state) { + const filePath = getHistoryPath(state); + const filteredMessages = filterSummaryMessages(messages); + const newSection = `## Summarized at ${(/* @__PURE__ */ new Date()).toISOString()} + +${getBufferString(filteredMessages)} + +`; + const sectionBytes = new TextEncoder().encode(newSection); + try { + let existingBytes = null; + if (resolvedBackend.downloadFiles) + try { + const responses = await resolvedBackend.downloadFiles([filePath]); + if (responses.length > 0 && responses[0].content && !responses[0].error) + existingBytes = responses[0].content; + } catch {} + let result; + if (existingBytes && resolvedBackend.uploadFiles) { + const combined = new Uint8Array(existingBytes.byteLength + sectionBytes.byteLength); + combined.set(existingBytes, 0); + combined.set(sectionBytes, existingBytes.byteLength); + const uploadResults = await resolvedBackend.uploadFiles([[filePath, combined]]); + result = uploadResults[0].error ? { error: uploadResults[0].error } : { path: filePath }; + } else if (!existingBytes) + result = await resolvedBackend.write(filePath, newSection); + else { + const existingContent = new TextDecoder().decode(existingBytes); + result = await resolvedBackend.edit(filePath, existingContent, existingContent + newSection); } - return new ZodEnum3({ - ...def, - checks: [], - ...exports_util2.normalizeParams(params), - entries: newEntries + if (result.error) { + console.warn(`Failed to offload conversation history to ${filePath}: ${result.error}`); + return null; + } + return filePath; + } catch (e) { + console.warn(`Exception offloading conversation history to ${filePath}:`, e); + return null; + } + } + async function createSummary(messages, chatModel) { + let messagesToSummarize = messages; + if (countTokensApproximately(messages) > trimTokensToSummarize) { + let kept = 0; + const trimmedMessages = []; + for (let i = messages.length - 1;i >= 0; i--) { + const msgTokens = countTokensApproximately([messages[i]]); + if (kept + msgTokens > trimTokensToSummarize) + break; + trimmedMessages.unshift(messages[i]); + kept += msgTokens; + } + messagesToSummarize = trimmedMessages; + } + const conversation = getBufferString(messagesToSummarize); + const prompt = summaryPrompt.replace("{conversation}", conversation); + const response = await chatModel.invoke([new HumanMessage({ content: prompt })]); + return typeof response.content === "string" ? response.content : JSON.stringify(response.content); + } + function buildSummaryMessage(summary, filePath) { + let content; + if (filePath) + content = context` + You are in the middle of a conversation that has been summarized. + + The full conversation history has been saved to ${filePath} should you need to refer back to it for details. + + A condensed summary follows: + + + ${summary} + + `; + else + content = `Here is a summary of the conversation to date: + +${summary}`; + return new HumanMessage({ + content, + additional_kwargs: { lc_source: "summarization" } + }); + } + function getEffectiveMessages(messages, state) { + const event = state._summarizationEvent; + if (!event) + return messages; + const result = [event.summaryMessage]; + result.push(...messages.slice(event.cutoffIndex)); + return result; + } + async function summarizeMessages(messagesToSummarize, resolvedModel, state, previousCutoffIndex, cutoffIndex) { + const filePath = await offloadToBackend(await resolveBackend(backend, { state }), messagesToSummarize, state); + if (filePath === null) + console.warn(`[SummarizationMiddleware] Backend offload failed during summarization. Proceeding with summary generation.`); + return { + summaryMessage: buildSummaryMessage(await createSummary(messagesToSummarize, resolvedModel), filePath), + filePath, + stateCutoffIndex: previousCutoffIndex != null ? previousCutoffIndex + cutoffIndex - 1 : cutoffIndex + }; + } + function isContextOverflow(err) { + let cause = err; + for (;; ) { + if (!cause) + break; + if (ContextOverflowError.isInstance(cause)) + return true; + cause = typeof cause === "object" && "cause" in cause ? cause.cause : undefined; + } + return false; + } + async function performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens) { + const cutoffIndex = determineCutoffIndex(truncatedMessages, maxInputTokens); + if (cutoffIndex <= 0) + return handler({ + ...request, + messages: truncatedMessages + }); + const messagesToSummarize = truncatedMessages.slice(0, cutoffIndex); + const preservedMessages = truncatedMessages.slice(cutoffIndex); + if (preservedMessages.length === 0 && maxInputTokens) { + const compact = compactToolResults(truncatedMessages, maxInputTokens, request.systemMessage, request.tools); + if (compact.modified) + try { + return await handler({ + ...request, + messages: compact.messages + }); + } catch (err) { + if (!isContextOverflow(err)) + throw err; + } + } + const previousEvent = request.state._summarizationEvent; + const previousCutoffIndex = previousEvent != null ? previousEvent.cutoffIndex : undefined; + const { summaryMessage, filePath, stateCutoffIndex } = await summarizeMessages(messagesToSummarize, resolvedModel, request.state, previousCutoffIndex, cutoffIndex); + let modifiedMessages = [summaryMessage, ...preservedMessages]; + const modifiedTokens = countTotalTokens(modifiedMessages, request.systemMessage, request.tools); + let finalStateCutoffIndex = stateCutoffIndex; + let finalSummaryMessage = summaryMessage; + let finalFilePath = filePath; + try { + await handler({ + ...request, + messages: modifiedMessages + }); + } catch (err) { + if (!isContextOverflow(err)) + throw err; + if (maxInputTokens && modifiedTokens > 0) { + const observedRatio = maxInputTokens / modifiedTokens; + if (observedRatio > tokenEstimationMultiplier) + tokenEstimationMultiplier = observedRatio * 1.1; + } + const reSumResult = await summarizeMessages([...messagesToSummarize, ...preservedMessages], resolvedModel, request.state, previousCutoffIndex, truncatedMessages.length); + finalSummaryMessage = reSumResult.summaryMessage; + finalFilePath = reSumResult.filePath; + finalStateCutoffIndex = reSumResult.stateCutoffIndex; + modifiedMessages = [reSumResult.summaryMessage]; + await handler({ + ...request, + messages: modifiedMessages + }); + } + return new Command2({ update: { + _summarizationEvent: { + cutoffIndex: finalStateCutoffIndex, + summaryMessage: finalSummaryMessage, + filePath: finalFilePath + }, + _summarizationSessionId: getSessionId(request.state) + } }); + } + return createMiddleware({ + name: "SummarizationMiddleware", + stateSchema: SummarizationStateSchema, + async wrapModelCall(request, handler) { + const effectiveMessages = getEffectiveMessages(request.messages ?? [], request.state); + if (effectiveMessages.length === 0) + return handler(request); + const resolvedModel = request.model ?? await getChatModel(); + const maxInputTokens = getMaxInputTokens(resolvedModel); + applyModelDefaults(resolvedModel); + const { messages: truncatedMessages } = truncateArgs(effectiveMessages, maxInputTokens, request.systemMessage, request.tools); + const totalTokens = countTotalTokens(truncatedMessages, request.systemMessage, request.tools); + if (!shouldSummarize(truncatedMessages, totalTokens, maxInputTokens)) + try { + return await handler({ + ...request, + messages: truncatedMessages + }); + } catch (err) { + if (!isContextOverflow(err)) + throw err; + if (maxInputTokens && totalTokens > 0) { + const observedRatio = maxInputTokens / totalTokens; + if (observedRatio > tokenEstimationMultiplier) + tokenEstimationMultiplier = observedRatio * 1.1; + } + } + return performSummarization(request, handler, truncatedMessages, resolvedModel, maxInputTokens); + } + }); +} +function toolCallIdFromRuntime(runtime) { + return runtime.toolCall?.id ?? runtime.toolCallId ?? ""; +} +function asyncTasksReducer(existing, update) { + return { + ...existing || {}, + ...update || {} + }; +} +function resolveTrackedTask(taskId, state) { + const tracked = (state.asyncTasks ?? {})[taskId.trim()]; + if (!tracked) + return `No tracked task found for taskId: '${taskId}'`; + return tracked; +} +function buildCheckResult(run2, threadId, threadValues) { + const checkResult = { + status: run2.status, + threadId + }; + if (run2.status === "success") { + const messages = (Array.isArray(threadValues) ? {} : threadValues)?.messages ?? []; + if (messages.length > 0) { + const last = messages[messages.length - 1]; + const rawContent = typeof last === "object" && last !== null && "content" in last ? last.content : last; + checkResult.result = typeof rawContent === "string" ? rawContent : JSON.stringify(rawContent); + } else + checkResult.result = "Completed with no output messages."; + } else if (run2.status === "error") + checkResult.error = "The async subagent encountered an error."; + return checkResult; +} +function filterTasks(tasks, statusFilter) { + if (!statusFilter || statusFilter === "all") + return Object.values(tasks); + return Object.values(tasks).filter((task3) => task3.status === statusFilter); +} +async function fetchLiveTaskStatus(clients, task3) { + if (TERMINAL_STATUSES.has(task3.status)) + return task3.status; + try { + return (await clients.getClient(task3.agentName).runs.get(task3.threadId, task3.runId)).status; + } catch { + return task3.status; + } +} +function formatTaskEntry(task3, status) { + return `- taskId: ${task3.taskId} agent: ${task3.agentName} status: ${status}`; +} +function extractCallbackContext(runtime) { + const threadId = runtime.config?.configurable?.thread_id; + if (typeof threadId === "string" && threadId) + return { callbackThreadId: threadId }; + return {}; +} +function buildStartTool(agentMap, clients, toolDescription) { + return tool$1(async (input, runtime) => { + if (!(input.agentName in agentMap)) { + const allowed = Object.keys(agentMap).map((k) => `\`${k}\``).join(", "); + return `Unknown async subagent type \`${input.agentName}\`. Available types: ${allowed}`; + } + const spec = agentMap[input.agentName]; + const callbackContext = extractCallbackContext(runtime); + try { + const client2 = clients.getClient(input.agentName); + const thread = await client2.threads.create(); + const run2 = await client2.runs.create(thread.thread_id, spec.graphId, { input: { + messages: [{ + role: "user", + content: input.description + }], + ...callbackContext + } }); + const taskId = thread.thread_id; + const task3 = { + taskId, + agentName: input.agentName, + threadId: taskId, + runId: run2.run_id, + status: "running", + createdAt: (/* @__PURE__ */ new Date()).toISOString(), + description: input.description + }; + return new Command2({ update: { + messages: [new ToolMessage({ + content: `Launched async subagent. taskId: ${taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [taskId]: task3 } + } }); + } catch (e) { + return `Failed to launch async subagent '${input.agentName}': ${e}`; + } + }, { + name: "start_async_task", + description: toolDescription, + schema: exports_external.object({ + description: exports_external.string().describe("A detailed description of the task for the async subagent to perform."), + agentName: exports_external.string().describe("The type of async subagent to use. Must be one of the available types listed in the tool description.") + }) + }); +} +function buildCheckTool(clients) { + return tool$1(async (input, runtime) => { + const task3 = resolveTrackedTask(input.taskId, runtime.state); + if (typeof task3 === "string") + return task3; + const client2 = clients.getClient(task3.agentName); + let run2; + try { + run2 = await client2.runs.get(task3.threadId, task3.runId); + } catch (e) { + return `Failed to get run status: ${e}`; + } + let threadValues = {}; + if (run2.status === "success") + try { + threadValues = (await client2.threads.getState(task3.threadId)).values || {}; + } catch {} + const result = buildCheckResult(run2, task3.threadId, threadValues); + const updatedTask = { + taskId: task3.taskId, + agentName: task3.agentName, + threadId: task3.threadId, + runId: task3.runId, + status: result.status, + createdAt: task3.createdAt, + updatedAt: result.status !== task3.status ? (/* @__PURE__ */ new Date()).toISOString() : task3.updatedAt, + checkedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + return new Command2({ update: { + messages: [new ToolMessage({ + content: JSON.stringify(result), + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [task3.taskId]: updatedTask } + } }); + }, { + name: "check_async_task", + description: "Check the status of an async subagent task. Returns the current status and, if complete, the result.", + schema: exports_external.object({ taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) + }); +} +function buildUpdateTool(agentMap, clients) { + return tool$1(async (input, runtime) => { + const tracked = resolveTrackedTask(input.taskId, runtime.state); + if (typeof tracked === "string") + return tracked; + const spec = agentMap[tracked.agentName]; + try { + const run2 = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, { + input: { messages: [{ + role: "user", + content: input.message + }] }, + multitaskStrategy: "interrupt" + }); + const task3 = { + taskId: tracked.taskId, + agentName: tracked.agentName, + threadId: tracked.threadId, + runId: run2.run_id, + status: "running", + createdAt: tracked.createdAt, + description: input.message, + updatedAt: (/* @__PURE__ */ new Date()).toISOString(), + checkedAt: tracked.checkedAt + }; + return new Command2({ update: { + messages: [new ToolMessage({ + content: `Updated async subagent. taskId: ${tracked.taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [tracked.taskId]: task3 } + } }); + } catch (e) { + return `Failed to update async subagent: ${e}`; + } + }, { + name: "update_async_task", + description: "send updated instructions to an async subagent. Interrupts the current run and starts a new one on the same thread so the subagent sees the full conversation history plus your new message. The taskId remains the same.", + schema: exports_external.object({ + taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."), + message: exports_external.string().describe("Follow-up instructions or context to send to the subagent") + }) + }); +} +function buildCancelTool(clients) { + return tool$1(async (input, runtime) => { + const tracked = resolveTrackedTask(input.taskId, runtime.state); + if (typeof tracked === "string") + return tracked; + const client2 = clients.getClient(tracked.agentName); + try { + await client2.runs.cancel(tracked.threadId, tracked.runId); + } catch (e) { + return `Failed to cancel run: ${e}`; + } + const updated = { + taskId: tracked.taskId, + agentName: tracked.agentName, + threadId: tracked.threadId, + runId: tracked.runId, + status: "cancelled", + createdAt: tracked.createdAt, + updatedAt: (/* @__PURE__ */ new Date()).toISOString(), + checkedAt: tracked.checkedAt + }; + return new Command2({ update: { + messages: [new ToolMessage({ + content: `Cancelled async subagent task: ${tracked.taskId}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: { [tracked.taskId]: updated } + } }); + }, { + name: "cancel_async_task", + description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.", + schema: exports_external.object({ taskId: exports_external.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") }) + }); +} +function buildListTool(clients) { + return tool$1(async (input, runtime) => { + const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? undefined); + if (filtered.length === 0) + return "No async subagent tasks tracked"; + const statuses = await Promise.all(filtered.map((task3) => fetchLiveTaskStatus(clients, task3))); + const updatedTasks = {}; + const entries = []; + for (let idx = 0;idx < filtered.length; idx++) { + const task3 = filtered[idx]; + const status = statuses[idx]; + const taskEntry = formatTaskEntry(task3, status); + entries.push(taskEntry); + updatedTasks[task3.taskId] = { + taskId: task3.taskId, + agentName: task3.agentName, + threadId: task3.threadId, + runId: task3.runId, + status, + createdAt: task3.createdAt, + updatedAt: status !== task3.status ? (/* @__PURE__ */ new Date()).toISOString() : task3.updatedAt, + checkedAt: task3.checkedAt + }; + } + return new Command2({ update: { + messages: [new ToolMessage({ + content: `${entries.length} tracked task(s): +${entries.join(` +`)}`, + tool_call_id: toolCallIdFromRuntime(runtime) + })], + asyncTasks: updatedTasks + } }); + }, { + name: "list_async_tasks", + description: "List tracked async subagent tasks with their current live statuses. Be default shows all tasks. Use `statusFilter` to narrow by status (e.g., 'running', 'success', 'error', 'cancelled'). Use `check_async_task` to get the full result of a specific completed task.", + schema: exports_external.object({ statusFilter: exports_external.string().nullish().describe("Filter tasks by status. One of: 'running', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") }) + }); +} +function isAsyncSubAgent(subAgent) { + return "graphId" in subAgent; +} +function createAsyncSubAgentMiddleware(options) { + const { asyncSubAgents, systemPrompt = ASYNC_TASK_SYSTEM_PROMPT } = options; + if (!asyncSubAgents || asyncSubAgents.length === 0) + throw new Error("At least one async subagent must be specified"); + const names = asyncSubAgents.map((a) => a.name); + const duplicates = names.filter((n4, i) => names.indexOf(n4) !== i); + if (duplicates.length > 0) + throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`); + const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a])); + const clients = new ClientCache(agentMap); + const agentsDescription = asyncSubAgents.map((a) => `- ${a.name}: ${a.description}`).join(` +`); + const tools = [ + buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)), + buildCheckTool(clients), + buildUpdateTool(agentMap, clients), + buildCancelTool(clients), + buildListTool(clients) + ]; + const fullSystemPrompt = systemPrompt ? `${systemPrompt} + +Available async subagent types: +${agentsDescription}` : null; + return createMiddleware({ + name: "asyncSubAgentMiddleware", + stateSchema: AsyncTaskStateSchema, + tools, + wrapModelCall: async (request, handler) => { + if (fullSystemPrompt !== null) + return handler({ + ...request, + systemMessage: request.systemMessage.concat(new SystemMessage({ content: fullSystemPrompt })) + }); + return handler(request); + } + }); +} +function getObjectRecord(value) { + return value != null && typeof value === "object" ? value : undefined; +} +function getAssistantIdFromRecord(value) { + const assistantId = value?.assistant_id ?? value?.assistantId; + return typeof assistantId === "string" && assistantId.length > 0 ? assistantId : undefined; +} +function validateNamespace2(namespace) { + if (namespace.length === 0) + throw new Error("Namespace array must not be empty."); + for (let i = 0;i < namespace.length; i++) { + const component = namespace[i]; + if (typeof component !== "string") + throw new TypeError(`Namespace component at index ${i} must be a string, got ${typeof component}.`); + if (!component) + throw new Error(`Namespace component at index ${i} must not be empty.`); + if (!NAMESPACE_COMPONENT_RE.test(component)) + throw new Error(`Namespace component at index ${i} contains disallowed characters: "${component}". Only alphanumeric characters, hyphens, underscores, dots, @, +, colons, and tildes are allowed.`); + } + return namespace; +} +function getErrorMessage(error90) { + if (typeof error90 === "string") + return error90; + if (typeof error90 === "object" && error90 !== null && "message" in error90 && typeof error90.message === "string") + return error90.message; + return String(error90); +} +function splitLinesKeepEnds(content) { + const lines = []; + let lineStart = 0; + for (let index2 = 0;index2 < content.length; index2 += 1) + if (content[index2] === ` +`) { + lines.push(content.slice(lineStart, index2 + 1)); + lineStart = index2 + 1; + } + if (lineStart < content.length) + lines.push(content.slice(lineStart)); + return lines; +} +function sliceReadContent(content, offset, limit) { + if (!content || content.trim() === "") + return { content }; + const lines = splitLinesKeepEnds(content.replace(/\r\n/g, ` +`).replace(/\r/g, ` +`)); + const startIndex = offset; + const endIndex = Math.min(startIndex + limit, lines.length); + if (startIndex >= lines.length) + return { error: `Line offset ${offset} exceeds file length (${lines.length} lines)` }; + return { content: lines.slice(startIndex, endIndex).join("") }; +} +function isLangSmithNotFoundError2(error90) { + if (typeof error90 !== "object" || error90 === null) + return false; + const maybeError = error90; + return maybeError.name === "LangSmithNotFoundError" || maybeError.status === 404; +} +function isLangSmithError(error90) { + if (typeof error90 !== "object" || error90 === null) + return false; + const maybeError = error90; + return typeof maybeError.name === "string" && maybeError.name.startsWith("LangSmith") || typeof maybeError.status === "number"; +} +function getLangSmithStatus(error90) { + if (typeof error90 !== "object" || error90 === null) + return; + const maybeError = error90; + if (typeof maybeError.status === "number") + return maybeError.status; +} +function mapHubFileOperationError(error90) { + const status = getLangSmithStatus(error90); + if (status === 401 || status === 403) + return "permission_denied"; + if (status === 404) + return "file_not_found"; + return "invalid_path"; +} +function shellQuote(s) { + return "'" + s.replace(/'/g, "'\\''") + "'"; +} +function globToPathRegex(pattern) { + let regex2 = "^"; + let i = 0; + while (i < pattern.length) { + const c = pattern[i]; + if (c === "*") + if (i + 1 < pattern.length && pattern[i + 1] === "*") { + i += 2; + if (i < pattern.length && pattern[i] === "/") { + regex2 += "(.*/)?"; + i++; + } else + regex2 += ".*"; + } else { + regex2 += "[^/]*"; + i++; + } + else if (c === "?") { + regex2 += "[^/]"; + i++; + } else if (c === "[") { + let j = i + 1; + while (j < pattern.length && pattern[j] !== "]") + j++; + regex2 += pattern.slice(i, j + 1); + i = j + 1; + } else if (c === "." || c === "+" || c === "^" || c === "$" || c === "{" || c === "}" || c === "(" || c === ")" || c === "|" || c === "\\") { + regex2 += `\\${c}`; + i++; + } else { + regex2 += c; + i++; + } + } + regex2 += "$"; + return new RegExp(regex2); +} +function parseStatLine(line) { + const firstTab = line.indexOf("\t"); + if (firstTab === -1) + return null; + const secondTab = line.indexOf("\t", firstTab + 1); + if (secondTab === -1) + return null; + const thirdTab = line.indexOf("\t", secondTab + 1); + if (thirdTab === -1) + return null; + const size = parseInt(line.slice(0, firstTab), 10); + const mtime = parseInt(line.slice(firstTab + 1, secondTab), 10); + const fileType = line.slice(secondTab + 1, thirdTab); + const fullPath = line.slice(thirdTab + 1); + if (isNaN(size) || isNaN(mtime)) + return null; + return { + size, + mtime, + isDir: fileType === "d" || fileType === "directory" || fileType.startsWith("d"), + fullPath + }; +} +function buildLsCommand(dirPath) { + const quotedPath = shellQuote(dirPath); + const findBase = `find -L ${quotedPath} -maxdepth 1 -not -path ${quotedPath}`; + return `if find /dev/null -maxdepth 0 -printf '' 2>/dev/null; then ${findBase} -printf '%s\\t%T@\\t%y\\t%p\\n' 2>/dev/null; elif stat -c %s /dev/null >/dev/null 2>&1; then ${findBase} -exec sh -c '${STAT_C_SCRIPT}' _ {} +; else ${findBase} -exec stat -f '%z %m %Sp %N' {} + 2>/dev/null; fi || true`; +} +function buildFindCommand(searchPath) { + const quotedPath = shellQuote(searchPath); + const findBase = `find -L ${quotedPath} -not -path ${quotedPath}`; + return `if find /dev/null -maxdepth 0 -printf '' 2>/dev/null; then ${findBase} -printf '%s\\t%T@\\t%y\\t%p\\n' 2>/dev/null; elif stat -c %s /dev/null >/dev/null 2>&1; then ${findBase} -exec sh -c '${STAT_C_SCRIPT}' _ {} +; else ${findBase} -exec stat -f '%z %m %Sp %N' {} + 2>/dev/null; fi || true`; +} +function buildReadCommand(filePath, offset, limit) { + const quotedPath = shellQuote(filePath); + const safeOffset = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0; + const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.min(Math.floor(limit), 999999999) : 999999999; + const start = safeOffset + 1; + const end = safeOffset + safeLimit; + return [ + `if [ ! -f ${quotedPath} ]; then echo "Error: File not found"; exit 1; fi`, + `if [ ! -s ${quotedPath} ]; then echo "System reminder: File exists but has empty contents"; exit 0; fi`, + `awk 'NR >= ${start} && NR <= ${end} { printf "%6d\\t%s\\n", NR, $0 }' ${quotedPath}` + ].join("; "); +} +function buildGrepCommand(pattern, searchPath, globPattern) { + const patternEscaped = shellQuote(pattern); + const searchPathQuoted = shellQuote(searchPath); + if (globPattern) + return `find -L ${searchPathQuoted} -type f -name ${shellQuote(globPattern)} -exec grep -HnF -e ${patternEscaped} {} + 2>/dev/null || true`; + return `grep -rHnF -e ${patternEscaped} ${searchPathQuoted} 2>/dev/null || true`; +} +function createCacheBreakpointMiddleware() { + return createMiddleware({ + name: "CacheBreakpointMiddleware", + wrapModelCall(request, handler) { + const existingContent = request.systemMessage.content; + const existingBlocks = typeof existingContent === "string" ? [{ + type: "text", + text: existingContent + }] : Array.isArray(existingContent) ? [...existingContent] : []; + if (existingBlocks.length === 0) + return handler(request); + existingBlocks[existingBlocks.length - 1] = { + ...existingBlocks[existingBlocks.length - 1], + cache_control: { type: "ephemeral" } + }; + return handler({ + ...request, + systemMessage: new SystemMessage({ content: existingBlocks }) + }); + } + }); +} +function hasPrefix3(ns3, prefix) { + if (prefix.length > ns3.length) + return false; + for (let i = 0;i < prefix.length; i += 1) + if (ns3[i] !== prefix[i]) + return false; + return true; +} +function createSubagentTransformer(path3) { + return () => { + const subagentsLog = StreamChannel3.local(); + const pendingByCallId = /* @__PURE__ */ new Map; + const pendingByNamespaceSegment = /* @__PURE__ */ new Map; + const latestValuesByNamespaceSegment = /* @__PURE__ */ new Map; + const subagentsByName = /* @__PURE__ */ new Map; + const toolsNodeToName = /* @__PURE__ */ new Map; + const childToolCalls = /* @__PURE__ */ new Map; + const activeMessages = /* @__PURE__ */ new Map; + function deletePendingSubagent(pending) { + pendingByCallId.delete(pending.callId); + for (const [segment, entry] of pendingByNamespaceSegment) + if (entry === pending) { + pendingByNamespaceSegment.delete(segment); + latestValuesByNamespaceSegment.delete(segment); + } + } + function subagentSegment(ns3) { + return ns3.length === path3.length + 1 ? ns3[path3.length] : undefined; + } + function getOrCreateSubagentLogs(name) { + let logs = subagentsByName.get(name); + if (!logs) { + logs = { + messagesLog: StreamChannel3.local(), + toolCallsLog: StreamChannel3.local(), + nestedSubagentsLog: StreamChannel3.local() + }; + subagentsByName.set(name, logs); + } + return logs; + } + return { + __native: true, + init: () => ({ subagents: subagentsLog }), + process(event) { + if (!hasPrefix3(event.params.namespace, path3)) + return true; + const ns3 = event.params.namespace; + const depth = ns3.length - path3.length; + if (depth <= 1 && event.method === "tools") { + const data = event.params.data; + const toolCallId = data.tool_call_id; + const toolName = data.tool_name; + if (toolName === "task" && data.event === "tool-started") { + const rawInput = data.input; + const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {}; + const subagentName = input.subagent_type ?? "unknown"; + const taskDescription = input.description ?? ""; + let resolveTaskInput; + let resolveOutput; + let rejectOutput; + const taskInput = new Promise((res) => { + resolveTaskInput = res; + }); + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; + }); + const pending2 = { + name: subagentName, + callId: toolCallId, + resolveTaskInput, + resolveOutput, + rejectOutput + }; + if (toolCallId) + pendingByCallId.set(toolCallId, pending2); + resolveTaskInput(taskDescription); + if (depth === 1) { + toolsNodeToName.set(ns3[path3.length], subagentName); + pendingByNamespaceSegment.set(ns3[path3.length], pending2); + } + if (toolCallId) { + const taskSegment = `tools:${toolCallId}`; + toolsNodeToName.set(taskSegment, subagentName); + pendingByNamespaceSegment.set(taskSegment, pending2); + } + const logs = getOrCreateSubagentLogs(subagentName); + subagentsLog.push({ + name: subagentName, + taskInput, + output, + messages: logs.messagesLog, + toolCalls: logs.toolCallsLog, + subagents: logs.nestedSubagentsLog + }); + } + if (toolName === "task" && toolCallId) { + const pending2 = pendingByCallId.get(toolCallId); + if (pending2) { + if (data.event === "tool-finished") { + pending2.resolveOutput(data.output); + deletePendingSubagent(pending2); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + pending2.rejectOutput(new Error(message)); + deletePendingSubagent(pending2); + } + } + } + } + const segment = subagentSegment(ns3); + const pending = segment ? pendingByNamespaceSegment.get(segment) : undefined; + if (pending) { + if (event.method === "values") + latestValuesByNamespaceSegment.set(segment, event.params.data); + else if (event.method === "lifecycle") { + const data = event.params.data; + if (data.event === "completed" || data.event === "interrupted") { + pending.resolveOutput(latestValuesByNamespaceSegment.get(segment)); + deletePendingSubagent(pending); + } else if (data.event === "failed") { + pending.rejectOutput(/* @__PURE__ */ new Error(`Subagent ${pending.name} failed`)); + deletePendingSubagent(pending); + } + } + } + if (depth >= 2) { + const parentSegment = ns3[path3.length]; + const subagentName = toolsNodeToName.get(parentSegment); + const logs = subagentName ? subagentsByName.get(subagentName) : undefined; + if (logs && subagentName) { + if (event.method === "tools") { + const data = event.params.data; + const toolCallId = data.tool_call_id; + const toolName = data.tool_name; + if (data.event === "tool-started") { + let resolveOutput; + let rejectOutput; + let resolveStatus; + let resolveError; + const output = new Promise((res, rej) => { + resolveOutput = res; + rejectOutput = rej; + }); + const status = new Promise((res) => { + resolveStatus = res; + }); + const error90 = new Promise((res) => { + resolveError = res; + }); + childToolCalls.set(toolCallId, { + resolveOutput, + rejectOutput, + resolveStatus, + resolveError + }); + const rawInput = data.input; + const parsedInput = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput; + logs.toolCallsLog.push({ + name: toolName ?? "unknown", + callId: toolCallId, + input: parsedInput, + output, + status, + error: error90 + }); + } + const pending2 = toolCallId ? childToolCalls.get(toolCallId) : undefined; + if (pending2) { + if (data.event === "tool-finished") { + pending2.resolveOutput(data.output); + pending2.resolveStatus("finished"); + pending2.resolveError(undefined); + childToolCalls.delete(toolCallId); + } else if (data.event === "tool-error") { + const message = data.message ?? "unknown error"; + pending2.rejectOutput(new Error(message)); + pending2.resolveStatus("error"); + pending2.resolveError(message); + childToolCalls.delete(toolCallId); + } + } + } + if (event.method === "messages") { + const data = event.params.data; + if (data.event === "message-start") { + const eventsLog = StreamChannel3.local(); + const stream2 = new ChatModelStream(eventsLog); + eventsLog.push(data); + activeMessages.set(subagentName, { + stream: stream2, + eventsLog + }); + logs.messagesLog.push(stream2); + } else if (data.event === "message-finish") { + const active = activeMessages.get(subagentName); + if (active) { + active.eventsLog.push(data); + active.eventsLog.close(); + activeMessages.delete(subagentName); + } + } else + activeMessages.get(subagentName)?.eventsLog.push(data); + } + } + } + return true; + }, + finalize() { + for (const pending of pendingByCallId.values()) + pending.resolveOutput(undefined); + pendingByCallId.clear(); + for (const pending of childToolCalls.values()) { + pending.resolveOutput(undefined); + pending.resolveStatus("finished"); + pending.resolveError(undefined); + } + childToolCalls.clear(); + for (const active of activeMessages.values()) + active.eventsLog.fail(/* @__PURE__ */ new Error("run finalized before message completed")); + activeMessages.clear(); + subagentsLog.close(); + for (const logs of subagentsByName.values()) { + logs.toolCallsLog.close(); + logs.messagesLog.close(); + logs.nestedSubagentsLog.close(); + } + }, + fail(err) { + for (const pending of pendingByCallId.values()) + pending.rejectOutput(err); + pendingByCallId.clear(); + for (const pending of childToolCalls.values()) { + pending.rejectOutput(err); + pending.resolveStatus("error"); + pending.resolveError(err instanceof Error ? err.message : String(err)); + } + childToolCalls.clear(); + for (const active of activeMessages.values()) + active.eventsLog.fail(err); + activeMessages.clear(); + subagentsLog.fail(err); + for (const logs of subagentsByName.values()) { + logs.toolCallsLog.fail(err); + logs.messagesLog.fail(err); + logs.nestedSubagentsLog.fail(err); + } + } + }; + }; +} +function validateProfileKey(key) { + const trimmed = key.trim(); + if (!trimmed) + throw new Error("Profile key must be a non-empty string"); + if (trimmed.split(":").length > 2) + throw new Error(`Profile key "${trimmed}" has more than one ":"; expected "provider" or "provider:model"`); + if (trimmed.includes(":")) { + const [provider, model] = trimmed.split(":"); + if (!provider.trim() || !model.trim()) + throw new Error(`Profile key "${trimmed}" has an empty provider or model half; expected "provider:model"`); + } + return trimmed; +} +function isHarnessProfile(value) { + return value.excludedTools != null && typeof value.excludedTools.has === "function" && !Array.isArray(value.excludedTools); +} +function resolveMiddleware(middleware) { + if (typeof middleware === "function") + return middleware(); + return middleware; +} +function validateExcludedMiddlewareName(name) { + if (!name || !name.trim()) + throw new Error("excludedMiddleware entries must be non-empty, non-whitespace strings."); + if (name.includes(":")) + throw new Error(`excludedMiddleware entries must be plain middleware names; class-path syntax is not supported, got "${name}".`); + if (name.startsWith("_")) + throw new Error(`excludedMiddleware entry "${name}" cannot start with "_" (underscore-prefixed names refer to private middleware not part of the public exclusion surface).`); + if (REQUIRED_MIDDLEWARE_NAMES.has(name)) + throw new Error(`Cannot exclude required middleware "${name}" — it provides essential agent capabilities that the runtime depends on.`); +} +function createHarnessProfile(options = {}) { + for (const name of options.excludedMiddleware ?? []) + validateExcludedMiddlewareName(name); + const toolDescriptionOverrides = Object.freeze(Object.assign(Object.create(null), options.toolDescriptionOverrides)); + const generalPurposeSubagent = options.generalPurposeSubagent ? Object.freeze({ ...options.generalPurposeSubagent }) : undefined; + const profile = { + baseSystemPrompt: options.baseSystemPrompt, + systemPromptSuffix: options.systemPromptSuffix, + toolDescriptionOverrides, + excludedTools: new Set(options.excludedTools), + excludedMiddleware: new Set(options.excludedMiddleware), + extraMiddleware: options.extraMiddleware ?? [], + generalPurposeSubagent + }; + return Object.freeze(profile); +} +function rejectPoisonedKeys(value, path3 = "") { + if (typeof value !== "object" || value === null || Array.isArray(value)) + return; + for (const key of Object.keys(value)) { + if (POISONED_KEYS.has(key)) + throw new Error(`Rejected dangerous key "${key}" at ${path3 || "root"} in harness profile config.`); + rejectPoisonedKeys(value[key], path3 ? `${path3}.${key}` : key); + } +} +function parseHarnessProfileConfig(data) { + rejectPoisonedKeys(data); + return createHarnessProfile(harnessProfileConfigSchema.parse(data)); +} +function serializeProfile(profile) { + if (resolveMiddleware(profile.extraMiddleware).length > 0) + throw new Error("Cannot serialize a HarnessProfile with non-empty extraMiddleware — middleware instances are runtime-only and have no JSON representation."); + const result = {}; + if (profile.baseSystemPrompt !== undefined) + result.baseSystemPrompt = profile.baseSystemPrompt; + if (profile.systemPromptSuffix !== undefined) + result.systemPromptSuffix = profile.systemPromptSuffix; + if (Object.keys(profile.toolDescriptionOverrides).length > 0) + result.toolDescriptionOverrides = { ...profile.toolDescriptionOverrides }; + if (profile.excludedTools.size > 0) + result.excludedTools = [...profile.excludedTools]; + if (profile.excludedMiddleware.size > 0) + result.excludedMiddleware = [...profile.excludedMiddleware]; + if (profile.generalPurposeSubagent !== undefined) { + const gp = {}; + if (profile.generalPurposeSubagent.enabled !== undefined) + gp.enabled = profile.generalPurposeSubagent.enabled; + if (profile.generalPurposeSubagent.description !== undefined) + gp.description = profile.generalPurposeSubagent.description; + if (profile.generalPurposeSubagent.systemPrompt !== undefined) + gp.systemPrompt = profile.generalPurposeSubagent.systemPrompt; + if (Object.keys(gp).length > 0) + result.generalPurposeSubagent = gp; + } + return result; +} +function mergeMiddleware(base, override) { + const baseArr = resolveMiddleware(base); + const overrideArr = resolveMiddleware(override); + if (baseArr.length === 0) + return override; + if (overrideArr.length === 0) + return base; + return () => { + const baseSeq = resolveMiddleware(base); + const overrideSeq = resolveMiddleware(override); + const overrideByName = new Map(overrideSeq.map((m) => [m.name, m])); + const merged = []; + const replaced = /* @__PURE__ */ new Set; + for (const entry of baseSeq) { + const replacement = overrideByName.get(entry.name); + if (replacement) { + if (!replaced.has(entry.name)) { + merged.push(replacement); + replaced.add(entry.name); + } + } else + merged.push(entry); + } + for (const entry of overrideSeq) + if (!replaced.has(entry.name)) + merged.push(entry); + return merged; + }; +} +function mergeGeneralPurposeSubagentConfigs(base, override) { + if (base === undefined) + return override; + if (override === undefined) + return base; + return { + enabled: override.enabled ?? base.enabled, + description: override.description ?? base.description, + systemPrompt: override.systemPrompt ?? base.systemPrompt + }; +} +function mergeProfiles(base, override) { + return createHarnessProfile({ + baseSystemPrompt: override.baseSystemPrompt ?? base.baseSystemPrompt, + systemPromptSuffix: override.systemPromptSuffix ?? base.systemPromptSuffix, + toolDescriptionOverrides: { + ...base.toolDescriptionOverrides, + ...override.toolDescriptionOverrides + }, + excludedTools: [...base.excludedTools, ...override.excludedTools], + excludedMiddleware: [...base.excludedMiddleware, ...override.excludedMiddleware], + extraMiddleware: mergeMiddleware(base.extraMiddleware, override.extraMiddleware), + generalPurposeSubagent: mergeGeneralPurposeSubagentConfigs(base.generalPurposeSubagent, override.generalPurposeSubagent) + }); +} +function register$3() { + registerHarnessProfileImpl("anthropic:claude-opus-4-7", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$3 })); +} +function register$2() { + registerHarnessProfileImpl("anthropic:claude-sonnet-4-6", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$2 })); +} +function register$1() { + registerHarnessProfileImpl("anthropic:claude-haiku-4-5", createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX$1 })); +} +function register() { + const profile = createHarnessProfile({ systemPromptSuffix: SYSTEM_PROMPT_SUFFIX }); + for (const spec of CODEX_MODEL_SPECS) + registerHarnessProfileImpl(spec, profile); +} +function loadBuiltinProfiles() { + register$3(); + register$2(); + register$1(); + register(); + snapshotBuiltinKeys(); +} +function getHarnessProfileRegistry() { + const global2 = globalThis; + if (global2[PROFILE_REGISTRY_KEY] == null) + global2[PROFILE_REGISTRY_KEY] = { + profiles: /* @__PURE__ */ new Map, + builtinKeys: /* @__PURE__ */ new Set, + builtinsLoaded: false + }; + return global2[PROFILE_REGISTRY_KEY]; +} +function ensureBuiltinsLoaded() { + const registry4 = getHarnessProfileRegistry(); + if (registry4.builtinsLoaded) + return; + registry4.builtinsLoaded = true; + loadBuiltinProfiles(); +} +function snapshotBuiltinKeys() { + const registry4 = getHarnessProfileRegistry(); + registry4.builtinKeys = new Set(registry4.profiles.keys()); +} +function registerHarnessProfileImpl(key, profile) { + key = validateProfileKey(key); + const { profiles } = getHarnessProfileRegistry(); + const existing = profiles.get(key); + if (existing !== undefined) + profiles.set(key, mergeProfiles(existing, profile)); + else + profiles.set(key, profile); +} +function registerHarnessProfile(key, profile) { + ensureBuiltinsLoaded(); + registerHarnessProfileImpl(key, isHarnessProfile(profile) ? profile : createHarnessProfile(profile)); +} +function getHarnessProfile(spec) { + if (spec.split(":").length > 2) + return; + const colonIdx = spec.indexOf(":"); + const hasColon = colonIdx !== -1; + const provider = hasColon ? spec.slice(0, colonIdx) : undefined; + const model = hasColon ? spec.slice(colonIdx + 1) : undefined; + if (hasColon && (!provider || !model)) + return; + ensureBuiltinsLoaded(); + const { profiles } = getHarnessProfileRegistry(); + const exact = profiles.get(spec); + const base = provider ? profiles.get(provider) : undefined; + if (exact !== undefined && base !== undefined) + return mergeProfiles(base, exact); + return exact ?? base; +} +function resolveHarnessProfile(opts = {}) { + const { spec, providerHint, identifierHint } = opts; + if (spec !== undefined) + return getHarnessProfile(spec) ?? EMPTY_HARNESS_PROFILE; + if (providerHint && identifierHint && !identifierHint.includes(":")) { + const profile = getHarnessProfile(`${providerHint}:${identifierHint}`); + if (profile) + return profile; + } + if (identifierHint && identifierHint.includes(":")) { + const profile = getHarnessProfile(identifierHint); + if (profile) + return profile; + } + if (providerHint) { + const profile = getHarnessProfile(providerHint); + if (profile) + return profile; + } + return EMPTY_HARNESS_PROFILE; +} +function applyProfilePrompt(profile, basePrompt) { + const prompt = profile.baseSystemPrompt !== undefined ? profile.baseSystemPrompt : basePrompt; + if (profile.systemPromptSuffix !== undefined) + return `${prompt} + +${profile.systemPromptSuffix}`; + return prompt; +} +function isAnthropicModel(model) { + if (typeof model === "string") { + if (model.includes(":")) + return model.split(":")[0] === "anthropic"; + return model.startsWith("claude"); + } + if (model.getName() === "ConfigurableModel") + return model._defaultConfig?.modelProvider === "anthropic"; + return model.getName() === "ChatAnthropic"; +} +function getModelProvider(model) { + if (model.getName() === "ConfigurableModel") + return model._defaultConfig?.modelProvider; + return { + ChatAnthropic: "anthropic", + ChatOpenAI: "openai", + ChatGoogleGenerativeAI: "google" + }[model.getName()]; +} +function getModelIdentifier(model) { + return (model.getName() === "ConfigurableModel" ? model._defaultConfig : undefined)?.model ?? model.model_name ?? model.modelName ?? undefined; +} +function createDeepAgent(params = {}) { + const { model = "anthropic:claude-sonnet-4-6", tools = [], systemPrompt, middleware: customMiddleware = [], subagents = [], responseFormat, contextSchema: contextSchema7, checkpointer, store, backend = (config3) => new StateBackend(config3), interruptOn, name, memory, skills, permissions = [], streamTransformers = [] } = params; + const collidingTools = tools.map((t) => t.name).filter((n4) => typeof n4 === "string" && BUILTIN_TOOL_NAMES.has(n4)); + if (collidingTools.length > 0) + throw new ConfigurationError(`Tool name(s) [${collidingTools.join(", ")}] conflict with built-in tools. Rename your custom tools to avoid this.`, "TOOL_NAME_COLLISION"); + const harnessProfile = typeof model === "string" ? resolveHarnessProfile({ spec: model }) : resolveHarnessProfile({ + providerHint: getModelProvider(model), + identifierHint: getModelIdentifier(model) + }); + const toolOverrides = harnessProfile.toolDescriptionOverrides; + const effectiveTools = Object.keys(toolOverrides).length > 0 ? tools.map((t) => (t.name in toolOverrides) ? Object.assign(Object.create(Object.getPrototypeOf(t)), t, { description: toolOverrides[t.name] }) : t) : tools; + const anthropicModel = isAnthropicModel(model); + const cacheMiddleware = anthropicModel ? [anthropicPromptCachingMiddleware({ + unsupportedModelBehavior: "ignore", + minMessagesToCache: 1 + }), createCacheBreakpointMiddleware()] : []; + const normalizeSubagentSpec = (input) => { + const effectivePermissions = input.permissions ?? permissions; + const subagentMiddleware2 = [ + todoListMiddleware(), + createFilesystemMiddleware({ + backend, + permissions: effectivePermissions + }), + createSummarizationMiddleware({ backend }), + createPatchToolCallsMiddleware(), + ...input.skills != null && input.skills.length > 0 ? [createSkillsMiddleware({ + backend, + sources: input.skills + })] : [], + ...input.middleware ?? [], + ...cacheMiddleware + ]; + return { + ...input, + tools: input.tools ?? [], + middleware: subagentMiddleware2 + }; + }; + const allSubagents = subagents; + const asyncSubAgents = allSubagents.filter((item) => isAsyncSubAgent(item)); + const inlineSubagents = allSubagents.filter((item) => !isAsyncSubAgent(item)).map((item) => ("runnable" in item) ? item : normalizeSubagentSpec(item)); + const gpConfig = harnessProfile.generalPurposeSubagent; + if (!(gpConfig?.enabled === false) && !inlineSubagents.some((item) => item.name === GENERAL_PURPOSE_SUBAGENT["name"])) { + const gpSystemPrompt = gpConfig?.systemPrompt ?? applyProfilePrompt(harnessProfile, GENERAL_PURPOSE_SUBAGENT.systemPrompt); + const generalPurposeSpec = normalizeSubagentSpec({ + ...GENERAL_PURPOSE_SUBAGENT, + description: gpConfig?.description ?? GENERAL_PURPOSE_SUBAGENT.description, + systemPrompt: gpSystemPrompt, + model, + skills, + tools: effectiveTools + }); + inlineSubagents.unshift(generalPurposeSpec); + } + const skillsMiddleware = skills != null && skills.length > 0 ? [createSkillsMiddleware({ + backend, + sources: skills + })] : []; + const [todoMiddleware, fsMiddleware, subagentMiddleware, summarizationMiddleware2, patchToolCallsMiddleware] = [ + todoListMiddleware(), + createFilesystemMiddleware({ + backend, + permissions + }), + createSubAgentMiddleware({ + defaultModel: model, + defaultTools: effectiveTools, + defaultInterruptOn: interruptOn, + subagents: inlineSubagents, + generalPurposeAgent: false + }), + createSummarizationMiddleware({ backend }), + createPatchToolCallsMiddleware() + ]; + const middleware = [ + todoMiddleware, + ...skillsMiddleware, + fsMiddleware, + subagentMiddleware, + summarizationMiddleware2, + patchToolCallsMiddleware, + ...asyncSubAgents.length > 0 ? [createAsyncSubAgentMiddleware({ asyncSubAgents })] : [], + ...customMiddleware, + ...cacheMiddleware, + ...memory && memory.length > 0 ? [createMemoryMiddleware({ + backend, + sources: memory, + addCacheControl: anthropicModel + })] : [], + ...interruptOn ? [humanInTheLoopMiddleware({ interruptOn })] : [] + ]; + const profileMiddleware = resolveMiddleware(harnessProfile.extraMiddleware); + if (profileMiddleware.length > 0) { + const cacheIdx = middleware.findIndex((m) => m.name === "AnthropicPromptCachingMiddleware"); + if (cacheIdx !== -1) + middleware.splice(cacheIdx, 0, ...profileMiddleware); + else + middleware.push(...profileMiddleware); + } + if (harnessProfile.excludedMiddleware.size > 0) { + const excluded = harnessProfile.excludedMiddleware; + const filtered = middleware.filter((m) => !excluded.has(m.name)); + middleware.length = 0; + middleware.push(...filtered); + } + if (harnessProfile.excludedTools.size > 0) { + const excludedTools = harnessProfile.excludedTools; + middleware.push(createMiddleware({ + name: "_ToolExclusionMiddleware", + wrapModelCall: async (request, handler) => { + return handler({ + ...request, + tools: request.tools?.filter((t) => !excludedTools.has(t.name)) + }); + } + })); + } + const effectiveBasePrompt = applyProfilePrompt(harnessProfile, BASE_AGENT_PROMPT); + return createAgent({ + model, + systemPrompt: typeof systemPrompt === "string" ? new SystemMessage({ contentBlocks: [{ + type: "text", + text: systemPrompt + }, { + type: "text", + text: effectiveBasePrompt + }] }) : SystemMessage.isInstance(systemPrompt) ? new SystemMessage({ contentBlocks: [...systemPrompt.contentBlocks, { + type: "text", + text: effectiveBasePrompt + }] }) : new SystemMessage({ contentBlocks: [{ + type: "text", + text: effectiveBasePrompt + }] }), + tools: effectiveTools, + middleware, + ...responseFormat !== null && { responseFormat }, + contextSchema: contextSchema7, + checkpointer, + store, + name, + streamTransformers: [createSubagentTransformer([]), ...streamTransformers] + }).withConfig({ + recursionLimit: 1e4, + metadata: { + ls_integration: "deepagents", + lc_agent_name: name + } + }); +} +function findProjectRoot(startPath) { + let current = path$1.resolve(startPath || process.cwd()); + while (current !== path$1.dirname(current)) { + const gitDir = path$1.join(current, ".git"); + if (fs$1.existsSync(gitDir)) + return current; + current = path$1.dirname(current); + } + const rootGitDir = path$1.join(current, ".git"); + if (fs$1.existsSync(rootGitDir)) + return current; + return null; +} +function isValidAgentName(agentName) { + if (!agentName || !agentName.trim()) + return false; + return /^[a-zA-Z0-9_\-\s]+$/.test(agentName); +} +function createSettings(options = {}) { + const projectRoot = findProjectRoot(options.startPath); + const userDeepagentsDir = path$1.join(os.homedir(), ".deepagents"); + return { + projectRoot, + userDeepagentsDir, + hasProject: projectRoot !== null, + getAgentDir(agentName) { + if (!isValidAgentName(agentName)) + throw new Error(`Invalid agent name: ${JSON.stringify(agentName)}. Agent names can only contain letters, numbers, hyphens, underscores, and spaces.`); + return path$1.join(userDeepagentsDir, agentName); + }, + ensureAgentDir(agentName) { + const agentDir = this.getAgentDir(agentName); + fs$1.mkdirSync(agentDir, { recursive: true }); + return agentDir; + }, + getUserAgentMdPath(agentName) { + return path$1.join(this.getAgentDir(agentName), "agent.md"); + }, + getProjectAgentMdPath() { + if (!projectRoot) + return null; + return path$1.join(projectRoot, ".deepagents", "agent.md"); + }, + getUserSkillsDir(agentName) { + return path$1.join(this.getAgentDir(agentName), "skills"); + }, + ensureUserSkillsDir(agentName) { + const skillsDir = this.getUserSkillsDir(agentName); + fs$1.mkdirSync(skillsDir, { recursive: true }); + return skillsDir; + }, + getProjectSkillsDir() { + if (!projectRoot) + return null; + return path$1.join(projectRoot, ".deepagents", "skills"); + }, + ensureProjectSkillsDir() { + const skillsDir = this.getProjectSkillsDir(); + if (!skillsDir) + return null; + fs$1.mkdirSync(skillsDir, { recursive: true }); + return skillsDir; + }, + ensureProjectDeepagentsDir() { + if (!projectRoot) + return null; + const deepagentsDir = path$1.join(projectRoot, ".deepagents"); + fs$1.mkdirSync(deepagentsDir, { recursive: true }); + return deepagentsDir; + } + }; +} +function createAgentMemoryMiddleware(options) { + const { settings, assistantId, systemPromptTemplate } = options; + const agentDir = settings.getAgentDir(assistantId); + const agentDirDisplay = `~/.deepagents/${assistantId}`; + const agentDirAbsolute = agentDir; + const projectRoot = settings.projectRoot; + const projectMemoryInfo = projectRoot ? `\`${projectRoot}\` (detected)` : "None (not in a git project)"; + const projectDeepagentsDir = projectRoot ? `${projectRoot}/.deepagents` : "[project-root]/.deepagents (not in a project)"; + const template = systemPromptTemplate || DEFAULT_MEMORY_TEMPLATE; + return createMiddleware({ + name: "AgentMemoryMiddleware", + stateSchema: AgentMemoryStateSchema, + beforeAgent(state) { + const result = {}; + if (!("userMemory" in state)) { + const userPath = settings.getUserAgentMdPath(assistantId); + if (fs$1.existsSync(userPath)) + try { + result.userMemory = fs$1.readFileSync(userPath, "utf-8"); + } catch {} + } + if (!("projectMemory" in state)) { + const projectPath = settings.getProjectAgentMdPath(); + if (projectPath && fs$1.existsSync(projectPath)) + try { + result.projectMemory = fs$1.readFileSync(projectPath, "utf-8"); + } catch {} + } + return Object.keys(result).length > 0 ? result : undefined; + }, + wrapModelCall(request, handler) { + const userMemory = request.state?.userMemory; + const projectMemory = request.state?.projectMemory; + const baseSystemPrompt = request.systemPrompt || ""; + const memorySection = template.replace("{user_memory}", userMemory || "(No user agent.md)").replace("{project_memory}", projectMemory || "(No project agent.md)"); + const memoryDocs = LONGTERM_MEMORY_SYSTEM_PROMPT.replaceAll("{agent_dir_absolute}", agentDirAbsolute).replaceAll("{agent_dir_display}", agentDirDisplay).replaceAll("{project_memory_info}", projectMemoryInfo).replaceAll("{project_deepagents_dir}", projectDeepagentsDir); + let systemPrompt = memorySection; + if (baseSystemPrompt) + systemPrompt += ` + +` + baseSystemPrompt; + systemPrompt += ` + +` + memoryDocs; + return handler({ + ...request, + systemPrompt + }); + } + }); +} +function isSafePath(targetPath, baseDir) { + try { + const resolvedPath = fs$1.realpathSync(targetPath); + const resolvedBase = fs$1.realpathSync(baseDir); + return resolvedPath.startsWith(resolvedBase + path$1.sep) || resolvedPath === resolvedBase; + } catch { + return false; + } +} +function validateSkillName(name, directoryName) { + if (!name) + return { + valid: false, + error: "name is required" + }; + if (name.length > 64) + return { + valid: false, + error: "name exceeds 64 characters" + }; + if (!SKILL_NAME_PATTERN.test(name)) + return { + valid: false, + error: "name must be lowercase alphanumeric with single hyphens only" + }; + if (name !== directoryName) + return { + valid: false, + error: `name '${name}' must match directory name '${directoryName}'` + }; + return { valid: true }; +} +function parseFrontmatter(content) { + const match2 = content.match(FRONTMATTER_PATTERN); + if (!match2) + return null; + try { + const parsed = import_yaml.default.parse(match2[1]); + return typeof parsed === "object" && parsed !== null ? parsed : null; + } catch { + return null; + } +} +function parseSkillMetadata(skillMdPath, source) { + try { + const stats = fs$1.statSync(skillMdPath); + if (stats.size > 10485760) { + console.warn(`Skipping ${skillMdPath}: file too large (${stats.size} bytes)`); + return null; + } + const frontmatter = parseFrontmatter(fs$1.readFileSync(skillMdPath, "utf-8")); + if (!frontmatter) { + console.warn(`Skipping ${skillMdPath}: no valid YAML frontmatter found`); + return null; + } + const name = frontmatter.name; + const description = frontmatter.description; + if (!name || !description) { + console.warn(`Skipping ${skillMdPath}: missing required 'name' or 'description'`); + return null; + } + const directoryName = path$1.basename(path$1.dirname(skillMdPath)); + const validation = validateSkillName(String(name), directoryName); + if (!validation.valid) + console.warn(`Skill '${name}' in ${skillMdPath} does not follow Agent Skills spec: ${validation.error}. Consider renaming to be spec-compliant.`); + let descriptionStr = String(description); + if (descriptionStr.length > 1024) { + console.warn(`Description exceeds ${MAX_SKILL_DESCRIPTION_LENGTH$1} chars in ${skillMdPath}, truncating`); + descriptionStr = descriptionStr.slice(0, MAX_SKILL_DESCRIPTION_LENGTH$1); + } + return { + name: String(name), + description: descriptionStr, + path: skillMdPath, + source, + license: frontmatter.license ? String(frontmatter.license) : undefined, + compatibility: frontmatter.compatibility ? String(frontmatter.compatibility) : undefined, + metadata: frontmatter.metadata && typeof frontmatter.metadata === "object" ? frontmatter.metadata : undefined, + allowedTools: frontmatter["allowed-tools"] ? String(frontmatter["allowed-tools"]) : undefined + }; + } catch (error90) { + console.warn(`Error reading ${skillMdPath}: ${error90}`); + return null; + } +} +function listSkillsFromDir(skillsDir, source) { + const expandedDir = skillsDir.startsWith("~") ? path$1.join(process.env.HOME || process.env.USERPROFILE || "", skillsDir.slice(1)) : skillsDir; + if (!fs$1.existsSync(expandedDir)) + return []; + let resolvedBase; + try { + resolvedBase = fs$1.realpathSync(expandedDir); + } catch { + return []; + } + const skills = []; + let entries; + try { + entries = fs$1.readdirSync(resolvedBase, { withFileTypes: true }); + } catch { + return []; + } + for (const entry of entries) { + const skillDir = path$1.join(resolvedBase, entry.name); + if (!isSafePath(skillDir, resolvedBase)) + continue; + if (!entry.isDirectory()) + continue; + const skillMdPath = path$1.join(skillDir, "SKILL.md"); + if (!fs$1.existsSync(skillMdPath)) + continue; + if (!isSafePath(skillMdPath, resolvedBase)) + continue; + const metadata = parseSkillMetadata(skillMdPath, source); + if (metadata) + skills.push(metadata); + } + return skills; +} +function listSkills(options) { + const allSkills = /* @__PURE__ */ new Map; + if (options.userSkillsDir) { + const userSkills = listSkillsFromDir(options.userSkillsDir, "user"); + for (const skill of userSkills) + allSkills.set(skill.name, skill); + } + if (options.projectSkillsDir) { + const projectSkills = listSkillsFromDir(options.projectSkillsDir, "project"); + for (const skill of projectSkills) + allSkills.set(skill.name, skill); + } + return Array.from(allSkills.values()); +} +var import_micromatch, import_yaml, import_fast_glob, EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents", MAX_LINE_LENGTH = 5000, TOOL_RESULT_TOKEN_LIMIT = 20000, TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]", MIME_TYPES, SANDBOX_ERROR_SYMBOL, SandboxError, PREGEL_SEND_KEY = "__pregel_send", PREGEL_READ_KEY = "__pregel_read", StateBackend = class { + runtime; + fileFormat; + constructor(runtimeOrOptions, options) { + if (runtimeOrOptions != null && typeof runtimeOrOptions === "object" && "state" in runtimeOrOptions) { + this.runtime = runtimeOrOptions; + this.fileFormat = options?.fileFormat ?? "v2"; + } else { + this.runtime = undefined; + this.fileFormat = runtimeOrOptions?.fileFormat ?? "v2"; + } + } + get isLegacy() { + return this.runtime !== undefined; + } + get files() { + if (this.runtime) + return this.runtime.state.files ?? {}; + const read = getConfig2().configurable?.[PREGEL_READ_KEY]; + return read?.("files", true) ?? {}; + } + sendFilesUpdate(update) { + if (this.isLegacy) + return; + const send = getConfig2().configurable?.[PREGEL_SEND_KEY]; + if (typeof send === "function") + send([["files", update]]); + } + ls(path3) { + const files = this.files; + const infos = []; + const subdirs = /* @__PURE__ */ new Set; + const normalizedPath = path3.endsWith("/") ? path3 : path3 + "/"; + for (const [k, fd] of Object.entries(files)) { + if (!k.startsWith(normalizedPath)) + continue; + const relative2 = k.substring(normalizedPath.length); + if (relative2.includes("/")) { + const subdirName = relative2.split("/")[0]; + subdirs.add(normalizedPath + subdirName + "/"); + continue; + } + const size = isFileDataV1(fd) ? fd.content.join(` +`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length; + infos.push({ + path: k, + is_dir: false, + size, + modified_at: fd.modified_at + }); + } + for (const subdir of Array.from(subdirs).sort()) + infos.push({ + path: subdir, + is_dir: true, + size: 0, + modified_at: "" + }); + infos.sort((a, b) => a.path.localeCompare(b.path)); + return { files: infos }; + } + read(filePath, offset = 0, limit = 500) { + const fileData = this.files[filePath]; + if (!fileData) + return { error: `File '${filePath}' not found` }; + const fileDataV2 = migrateToFileDataV2(fileData, filePath); + if (!isTextMimeType(fileDataV2.mimeType)) + return { + content: fileDataV2.content, + mimeType: fileDataV2.mimeType + }; + if (typeof fileDataV2.content !== "string") + return { error: `File '${filePath}' has binary content but text MIME type` }; + return { + content: fileDataV2.content.split(` +`).slice(offset, offset + limit).join(` +`), + mimeType: fileDataV2.mimeType + }; + } + readRaw(filePath) { + const fileData = this.files[filePath]; + if (!fileData) + return { error: `File '${filePath}' not found` }; + return { data: fileData }; + } + write(filePath, content) { + if (filePath in this.files) + return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; + const mimeType = getMimeType(filePath); + const newFileData = createFileData(content, undefined, this.fileFormat, mimeType); + const update = { [filePath]: newFileData }; + if (!this.isLegacy) { + this.sendFilesUpdate(update); + return { path: filePath }; + } + return { + path: filePath, + filesUpdate: { [filePath]: newFileData } + }; + } + edit(filePath, oldString, newString, replaceAll = false) { + const fileData = this.files[filePath]; + if (!fileData) + return { error: `Error: File '${filePath}' not found` }; + const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll); + if (typeof result === "string") + return { error: result }; + const [newContent, occurrences] = result; + const newFileData = updateFileData(fileData, newContent); + const update = { [filePath]: newFileData }; + if (!this.isLegacy) { + this.sendFilesUpdate(update); + return { + path: filePath, + occurrences + }; + } + return { + path: filePath, + filesUpdate: { [filePath]: newFileData }, + occurrences + }; + } + grep(pattern, path3 = "/", glob = null) { + const files = this.files; + return { matches: grepMatchesFromFiles(files, pattern, path3, glob) }; + } + glob(pattern, path3 = "/") { + const files = this.files; + const result = globSearchFiles(files, pattern, path3); + if (result === "No files found") + return { files: [] }; + const paths = result.split(` +`); + const infos = []; + for (const p of paths) { + const fd = files[p]; + const size = fd ? isFileDataV1(fd) ? fd.content.join(` +`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0; + infos.push({ + path: p, + is_dir: false, + size, + modified_at: fd?.modified_at || "" + }); + } + return { files: infos }; + } + uploadFiles(files) { + const responses = []; + const updates = {}; + for (const [path3, content] of files) + try { + const mimeType = getMimeType(path3); + if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) + updates[path3] = createFileData(content, undefined, "v2", mimeType); + else + updates[path3] = createFileData(new TextDecoder().decode(content), undefined, this.fileFormat, mimeType); + responses.push({ + path: path3, + error: null + }); + } catch { + responses.push({ + path: path3, + error: "invalid_path" + }); + } + if (!this.isLegacy) { + if (Object.keys(updates).length > 0) + this.sendFilesUpdate(updates); + return responses; + } + const result = responses; + result.filesUpdate = updates; + return result; + } + downloadFiles(paths) { + const files = this.files; + const responses = []; + for (const path3 of paths) { + const fileData = files[path3]; + if (!fileData) { + responses.push({ + path: path3, + content: null, + error: "file_not_found" + }); + continue; + } + const fileDataV2 = migrateToFileDataV2(fileData, path3); + if (typeof fileDataV2.content === "string") { + const content = new TextEncoder().encode(fileDataV2.content); + responses.push({ + path: path3, + content, + error: null + }); + } else + responses.push({ + path: path3, + content: fileDataV2.content, + error: null + }); + } + return responses; + } +}, CompositeBackend = class { + default; + routes; + sortedRoutes; + constructor(defaultBackend, routes) { + this.default = isSandboxProtocol(defaultBackend) ? adaptSandboxProtocol(defaultBackend) : adaptBackendProtocol(defaultBackend); + this.routes = Object.fromEntries(Object.entries(routes).map(([k, v]) => [k, isSandboxProtocol(v) ? adaptSandboxProtocol(v) : adaptBackendProtocol(v)])); + this.sortedRoutes = Object.entries(this.routes).sort((a, b) => b[0].length - a[0].length); + } + get id() { + return isSandboxBackend(this.default) ? this.default.id : ""; + } + get routePrefixes() { + return Object.keys(this.routes); + } + static isInstance(backend) { + return typeof backend === "object" && backend !== null && Array.isArray(backend.routePrefixes); + } + getBackendAndKey(key) { + for (const [prefix, backend] of this.sortedRoutes) + if (key.startsWith(prefix)) { + const suffix = key.substring(prefix.length); + return [backend, suffix ? "/" + suffix : "/"]; + } + return [this.default, key]; + } + async ls(path3) { + for (const [routePrefix, backend] of this.sortedRoutes) + if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { + const suffix = path3.substring(routePrefix.length); + const searchPath = suffix ? "/" + suffix : "/"; + const result = await backend.ls(searchPath); + if (result.error) + return result; + const prefixed = []; + for (const fi of result.files || []) + prefixed.push({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + }); + return { files: prefixed }; + } + if (path3 === "/") { + const results = []; + const defaultResult = await this.default.ls(path3); + if (defaultResult.error) + return defaultResult; + results.push(...defaultResult.files || []); + for (const [routePrefix] of this.sortedRoutes) + results.push({ + path: routePrefix, + is_dir: true, + size: 0, + modified_at: "" + }); + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + return await this.default.ls(path3); + } + async read(filePath, offset = 0, limit = 500) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.read(strippedKey, offset, limit); + } + async readRaw(filePath) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.readRaw(strippedKey); + } + async grep(pattern, path3 = "/", glob = null) { + for (const [routePrefix, backend] of this.sortedRoutes) + if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { + const searchPath = path3.substring(routePrefix.length - 1); + const raw2 = await backend.grep(pattern, searchPath || "/", glob); + if (raw2.error) + return raw2; + return { matches: (raw2.matches || []).map((m) => ({ + ...m, + path: routePrefix.slice(0, -1) + m.path + })) }; + } + const allMatches = []; + const rawDefault = await this.default.grep(pattern, path3, glob); + if (rawDefault.error) + return rawDefault; + allMatches.push(...rawDefault.matches || []); + for (const [routePrefix, backend] of Object.entries(this.routes)) { + const raw2 = await backend.grep(pattern, "/", glob); + if (raw2.error) + return raw2; + const matches = (raw2.matches || []).map((m) => ({ + ...m, + path: routePrefix.slice(0, -1) + m.path + })); + allMatches.push(...matches); + } + return { matches: allMatches }; + } + async glob(pattern, path3 = "/") { + const results = []; + for (const [routePrefix, backend] of this.sortedRoutes) + if (path3.startsWith(routePrefix.replace(/\/$/, ""))) { + const searchPath = path3.substring(routePrefix.length - 1); + const result = await backend.glob(pattern, searchPath || "/"); + if (result.error) + return result; + return { files: (result.files || []).map((fi) => ({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + })) }; + } + const defaultResult = await this.default.glob(pattern, path3); + if (defaultResult.error) + return defaultResult; + results.push(...defaultResult.files || []); + for (const [routePrefix, backend] of Object.entries(this.routes)) { + const result = await backend.glob(pattern, "/"); + if (result.error) + continue; + const files = (result.files || []).map((fi) => ({ + ...fi, + path: routePrefix.slice(0, -1) + fi.path + })); + results.push(...files); + } + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + async write(filePath, content) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.write(strippedKey, content); + } + async edit(filePath, oldString, newString, replaceAll = false) { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.edit(strippedKey, oldString, newString, replaceAll); + } + execute(command) { + if (!isSandboxBackend(this.default)) + throw new Error("Default backend doesn't support command execution (SandboxBackendProtocol). To enable execution, provide a default backend that implements SandboxBackendProtocol."); + return Promise.resolve(this.default.execute(command)); + } + async uploadFiles(files) { + const results = Array.from({ length: files.length }, () => null); + const batchesByBackend = /* @__PURE__ */ new Map; + for (let idx = 0;idx < files.length; idx++) { + const [path3, content] = files[idx]; + const [backend, strippedPath] = this.getBackendAndKey(path3); + if (!batchesByBackend.has(backend)) + batchesByBackend.set(backend, []); + batchesByBackend.get(backend).push({ + idx, + path: strippedPath, + content + }); + } + for (const [backend, batch] of batchesByBackend) { + if (!backend.uploadFiles) + throw new Error("Backend does not support uploadFiles"); + const batchFiles = batch.map((b) => [b.path, b.content]); + const batchResponses = await backend.uploadFiles(batchFiles); + for (let i = 0;i < batch.length; i++) { + const originalIdx = batch[i].idx; + results[originalIdx] = { + path: files[originalIdx][0], + error: batchResponses[i]?.error ?? null + }; + } + } + return results; + } + async downloadFiles(paths) { + const results = Array.from({ length: paths.length }, () => null); + const batchesByBackend = /* @__PURE__ */ new Map; + for (let idx = 0;idx < paths.length; idx++) { + const path3 = paths[idx]; + const [backend, strippedPath] = this.getBackendAndKey(path3); + if (!batchesByBackend.has(backend)) + batchesByBackend.set(backend, []); + batchesByBackend.get(backend).push({ + idx, + path: strippedPath + }); + } + for (const [backend, batch] of batchesByBackend) { + if (!backend.downloadFiles) + throw new Error("Backend does not support downloadFiles"); + const batchPaths = batch.map((b) => b.path); + const batchResponses = await backend.downloadFiles(batchPaths); + for (let i = 0;i < batch.length; i++) { + const originalIdx = batch[i].idx; + results[originalIdx] = { + path: paths[originalIdx], + content: batchResponses[i]?.content ?? null, + error: batchResponses[i]?.error ?? null + }; + } + } + return results; + } +}, INT_FORMATTER, FILESYSTEM_TOOL_NAMES, TOOLS_EXCLUDED_FROM_EVICTION, MAX_BINARY_READ_SIZE_BYTES, READ_FILE_TRUNCATION_MSG = ` + +[Output was truncated due to size limits. The file content is very large. Consider reformatting the file to make it easier to navigate. For example, if this is JSON, use execute(command='jq . {file_path}') to pretty-print it with line breaks. For other formats, you can use appropriate formatting tools to split long lines.]`, TOO_LARGE_TOOL_MSG, TOO_LARGE_HUMAN_MSG = `Message content too large and was saved to the filesystem at: {file_path} + +You can read the full content using the read_file tool with pagination (offset and limit parameters). + +Here is a preview showing the head and tail of the content: + +{content_sample}`, FileDataV1Schema, FileDataV2Schema, FileDataSchema, FilesystemStateSchema, FILESYSTEM_SYSTEM_PROMPT, LS_TOOL_DESCRIPTION, READ_FILE_TOOL_DESCRIPTION, WRITE_FILE_TOOL_DESCRIPTION, EDIT_FILE_TOOL_DESCRIPTION, GLOB_TOOL_DESCRIPTION, GREP_TOOL_DESCRIPTION, EXECUTE_TOOL_DESCRIPTION, EXECUTION_SYSTEM_PROMPT, DEFAULT_SUBAGENT_PROMPT = "In order to complete the objective that the user asks of you, you have access to a number of standard tools.", EXCLUDED_STATE_KEYS, DEFAULT_GENERAL_PURPOSE_DESCRIPTION = "General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.", TASK_SYSTEM_PROMPT, GENERAL_PURPOSE_SUBAGENT, INVALID_TOOL_MESSAGE_BLOCK_TYPES, filesValue, MemoryStateSchema, MEMORY_SYSTEM_PROMPT, MAX_SKILL_FILE_SIZE, DEFAULT_SKILL_READ_LINE_LIMIT = 1000, MAX_SKILL_NAME_LENGTH = 64, MAX_SKILL_DESCRIPTION_LENGTH = 1024, SKILL_MODULE_EXTENSIONS, SkillMetadataEntrySchema, SkillsStateSchema, SKILLS_SYSTEM_PROMPT, MAX_MESSAGE_LENGTH = 500, TRUNCATION_SUFFIX = "... [full result truncated]", CALLBACK_THREAD_ID_KEY = "callbackThreadId", CompletionCallbackStateSchema, DEFAULT_MESSAGES_TO_KEEP = 20, DEFAULT_TRIM_TOKEN_LIMIT = 4000, FALLBACK_TRIGGER, FALLBACK_KEEP, FALLBACK_TRUNCATE_ARGS, PROFILE_TRIGGER, PROFILE_KEEP, PROFILE_TRUNCATE_ARGS, DEFAULT_SUMMARY_PROMPT2 = `You are a conversation summarizer. Your task is to create a concise summary of the conversation that captures: +1. The main topics discussed +2. Key decisions or conclusions reached +3. Any important context that would be needed for continuing the conversation + +Keep the summary focused and informative. Do not include unnecessary details. + +Conversation to summarize: +{conversation} + +Summary:`, SummarizationEventSchema, SummarizationStateSchema, AsyncTaskSchema, AsyncTaskStateSchema, ASYNC_TASK_TOOL_DESCRIPTION = `Launch an async subagent on a remote server. The subagent runs in the background and returns a task ID immediately. + +Available async agent types: +{available_agents} + +## Usage notes: +1. This tool launches a background task and returns immediately with a task ID. Report the task ID to the user and stop — do NOT immediately check status. +2. Use \`check_async_task\` only when the user asks for a status update or result. +3. Use \`update_async_task\` to send new instructions to a running task. +4. Multiple async subagents can run concurrently — launch several and let them run in the background. +5. The subagent runs on a remote server, so it has its own tools and capabilities.`, ASYNC_TASK_SYSTEM_PROMPT = `## Async subagents (remote servers) + +You have access to async subagent tools that launch background tasks on remote servers. + +### Tools: +- \`start_async_task\`: Start a new background task. Returns a task ID immediately. +- \`check_async_task\`: Check the status of a running task. Returns status and result if complete. +- \`update_async_task\`: Send an update or new instructions to a running task. +- \`cancel_async_task\`: Cancel a running task that is no longer needed. +- \`list_async_tasks\`: List all tracked tasks with live statuses. Use this to check all tasks at once. + +### Workflow: +1. **Launch** — Use \`start_async_task\` to start a task. Report the task ID to the user and stop. + Do NOT immediately check the status — the task runs in the background while you and the user continue other work. +2. **Check (on request)** — Only use \`check_async_task\` when the user explicitly asks for a status update or + result. If the status is "running", report that and stop — do not poll in a loop. +3. **Update** (optional) — Use \`update_async_task\` to send new instructions to a running task. This interrupts + the current run and starts a fresh one on the same thread. The task_id stays the same. +4. **Cancel** (optional) — Use \`cancel_async_task\` to stop a task that is no longer needed. +5. **Collect** — When \`check_async_task\` returns status "success", the result is included in the response. +6. **List** — Use \`list_async_tasks\` to see live statuses for all tasks at once, or to recall task IDs after context compaction. + +### Critical rules: +- After launching, ALWAYS return control to the user immediately. Never auto-check after launching. +- Never poll \`check_async_task\` in a loop. Check once per user request, then stop. +- If a check returns "running", tell the user and wait for them to ask again. +- Task statuses in conversation history are ALWAYS stale — a task that was "running" may now be done. + NEVER report a status from a previous tool result. ALWAYS call a tool to get the current status: + use \`list_async_tasks\` when the user asks about multiple tasks or "all tasks", + use \`check_async_task\` when the user asks about a specific task. +- Always show the full task_id — never truncate or abbreviate it. + +### When to use async subagents: +- Long-running tasks that would block the main agent +- Tasks that benefit from running on specialized remote deployments +- When you want to run multiple tasks concurrently and collect results later`, ASYNC_TASK_TOOL_NAMES, TERMINAL_STATUSES, ClientCache = class { + agents; + clients = /* @__PURE__ */ new Map; + constructor(agents) { + this.agents = agents; + } + resolveHeaders(spec) { + const headers = { ...spec.headers || {} }; + if (!("x-auth-scheme" in headers)) + headers["x-auth-scheme"] = "langsmith"; + return headers; + } + cacheKey(spec) { + const headers = this.resolveHeaders(spec); + const headerStr = Object.entries(headers).sort().flat().join(":"); + return `${spec.url ?? ""}|${headerStr}`; + } + getClient(name) { + const spec = this.agents[name]; + const key = this.cacheKey(spec); + const existing = this.clients.get(key); + if (existing) + return existing; + const headers = this.resolveHeaders(spec); + const client2 = new Client2({ + apiUrl: spec.url, + defaultHeaders: headers + }); + this.clients.set(key, client2); + return client2; + } +}, NAMESPACE_COMPONENT_RE, StoreBackend = class { + stateAndStore; + storeOverride; + _namespace; + fileFormat; + constructor(stateAndStoreOrOptions, options) { + let opts; + if (stateAndStoreOrOptions != null && typeof stateAndStoreOrOptions === "object" && "state" in stateAndStoreOrOptions) { + this.stateAndStore = stateAndStoreOrOptions; + opts = options; + } else { + this.stateAndStore = undefined; + opts = stateAndStoreOrOptions; + } + if (Array.isArray(opts?.namespace)) + this._namespace = validateNamespace2(opts.namespace); + else if (opts?.namespace) + this._namespace = opts.namespace; + this.storeOverride = opts?.store; + this.fileFormat = opts?.fileFormat ?? "v2"; + } + getStore() { + if (this.stateAndStore) { + const store2 = this.stateAndStore.store; + if (!store2) + throw new Error("Store is required but not available in runtime"); + return store2; + } + if (this.storeOverride) + return this.storeOverride; + const store = getStore2(); + if (!store) + throw new Error("Store is required but not available in LangGraph execution context. Ensure the graph was configured with a store."); + return store; + } + getState() { + if (this.stateAndStore) + return this.stateAndStore.state; + try { + return getCurrentTaskInput2(); + } catch { + return; + } + } + getNamespaceConfig() { + const injectedConfig = getObjectRecord(this.stateAndStore?.config); + if (injectedConfig) + return { + metadata: getObjectRecord(injectedConfig.metadata), + configurable: getObjectRecord(injectedConfig.configurable) + }; + try { + const configRecord = getObjectRecord(getConfig2()); + if (!configRecord) + return; + return { + metadata: getObjectRecord(configRecord.metadata), + configurable: getObjectRecord(configRecord.configurable) + }; + } catch { + return; + } + } + getLegacyAssistantId() { + const config3 = this.getNamespaceConfig(); + const assistantIdFromConfig = getAssistantIdFromRecord(config3?.metadata) ?? getAssistantIdFromRecord(config3?.configurable); + if (assistantIdFromConfig) + return assistantIdFromConfig; + const assistantId = this.stateAndStore?.assistantId; + return typeof assistantId === "string" && assistantId.length > 0 ? assistantId : undefined; + } + getNamespace() { + if (Array.isArray(this._namespace)) + return this._namespace; + if (this._namespace) + return validateNamespace2(this._namespace({ + state: this.getState(), + config: this.getNamespaceConfig(), + assistantId: this.getLegacyAssistantId() + })); + const assistantId = this.getLegacyAssistantId(); + if (assistantId) + return [assistantId, "filesystem"]; + return ["filesystem"]; + } + convertStoreItemToFileData(storeItem) { + const value = storeItem.value; + if (!(value.content !== undefined && (Array.isArray(value.content) || typeof value.content === "string" || ArrayBuffer.isView(value.content))) || typeof value.created_at !== "string" || typeof value.modified_at !== "string") + throw new Error(`Store item does not contain valid FileData fields. Got keys: ${Object.keys(value).join(", ")}`); + return { + content: value.content, + ...value.mimeType ? { mimeType: value.mimeType } : {}, + created_at: value.created_at, + modified_at: value.modified_at + }; + } + convertFileDataToStoreValue(fileData) { + return { + content: fileData.content, + ..."mimeType" in fileData ? { mimeType: fileData.mimeType } : {}, + created_at: fileData.created_at, + modified_at: fileData.modified_at + }; + } + async searchStorePaginated(store, namespace, options = {}) { + const { query: query3, filter, pageSize = 100 } = options; + const allItems = []; + let offset = 0; + while (true) { + const pageItems = await store.search(namespace, { + query: query3, + filter, + limit: pageSize, + offset + }); + if (!pageItems || pageItems.length === 0) + break; + allItems.push(...pageItems); + if (pageItems.length < pageSize) + break; + offset += pageSize; + } + return allItems; + } + async ls(path3) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const items = await this.searchStorePaginated(store, namespace); + const infos = []; + const subdirs = /* @__PURE__ */ new Set; + const normalizedPath = path3.endsWith("/") ? path3 : path3 + "/"; + for (const item of items) { + const itemKey = String(item.key); + if (!itemKey.startsWith(normalizedPath)) + continue; + const relative2 = itemKey.substring(normalizedPath.length); + if (relative2.includes("/")) { + const subdirName = relative2.split("/")[0]; + subdirs.add(normalizedPath + subdirName + "/"); + continue; + } + try { + const fd = this.convertStoreItemToFileData(item); + const size = isFileDataV1(fd) ? fd.content.join(` +`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length; + infos.push({ + path: itemKey, + is_dir: false, + size, + modified_at: fd.modified_at + }); + } catch { + continue; + } + } + for (const subdir of Array.from(subdirs).sort()) + infos.push({ + path: subdir, + is_dir: true, + size: 0, + modified_at: "" + }); + infos.sort((a, b) => a.path.localeCompare(b.path)); + return { files: infos }; + } + async read(filePath, offset = 0, limit = 500) { + try { + const readRawResult = await this.readRaw(filePath); + if (readRawResult.error || !readRawResult.data) + return { error: readRawResult.error || "File data not found" }; + const fileDataV2 = migrateToFileDataV2(readRawResult.data, filePath); + if (!isTextMimeType(fileDataV2.mimeType)) + return { + content: fileDataV2.content, + mimeType: fileDataV2.mimeType + }; + if (typeof fileDataV2.content !== "string") + return { error: `File '${filePath}' has binary content but text MIME type` }; + return { + content: fileDataV2.content.split(` +`).slice(offset, offset + limit).join(` +`), + mimeType: fileDataV2.mimeType + }; + } catch (e) { + return { error: e.message }; + } + } + async readRaw(filePath) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const item = await store.get(namespace, filePath); + if (!item) + return { error: `File '${filePath}' not found` }; + return { data: this.convertStoreItemToFileData(item) }; + } + async write(filePath, content) { + const store = this.getStore(); + const namespace = this.getNamespace(); + if (await store.get(namespace, filePath)) + return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; + const mimeType = getMimeType(filePath); + const fileData = createFileData(content, undefined, this.fileFormat, mimeType); + const storeValue = this.convertFileDataToStoreValue(fileData); + await store.put(namespace, filePath, storeValue); + return { + path: filePath, + filesUpdate: null + }; + } + async edit(filePath, oldString, newString, replaceAll = false) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const item = await store.get(namespace, filePath); + if (!item) + return { error: `Error: File '${filePath}' not found` }; + try { + const fileData = this.convertStoreItemToFileData(item); + const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll); + if (typeof result === "string") + return { error: result }; + const [newContent, occurrences] = result; + const newFileData = updateFileData(fileData, newContent); + const storeValue = this.convertFileDataToStoreValue(newFileData); + await store.put(namespace, filePath, storeValue); + return { + path: filePath, + filesUpdate: null, + occurrences + }; + } catch (e) { + return { error: `Error: ${e.message}` }; + } + } + async grep(pattern, path3 = "/", glob = null) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const items = await this.searchStorePaginated(store, namespace); + const files = {}; + for (const item of items) + try { + files[item.key] = this.convertStoreItemToFileData(item); + } catch { + continue; + } + return { matches: grepMatchesFromFiles(files, pattern, path3, glob) }; + } + async glob(pattern, path3 = "/") { + const store = this.getStore(); + const namespace = this.getNamespace(); + const items = await this.searchStorePaginated(store, namespace); + const files = {}; + for (const item of items) + try { + files[item.key] = this.convertStoreItemToFileData(item); + } catch { + continue; + } + const result = globSearchFiles(files, pattern, path3); + if (result === "No files found") + return { files: [] }; + const paths = result.split(` +`); + const infos = []; + for (const p of paths) { + const fd = files[p]; + const size = fd ? isFileDataV1(fd) ? fd.content.join(` +`).length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0; + infos.push({ + path: p, + is_dir: false, + size, + modified_at: fd?.modified_at || "" + }); + } + return { files: infos }; + } + async uploadFiles(files) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const responses = []; + for (const [path3, content] of files) + try { + const mimeType = getMimeType(path3); + const isBinary = this.fileFormat === "v2" && !isTextMimeType(mimeType); + let fileData; + if (isBinary) + fileData = createFileData(content, undefined, "v2", mimeType); + else + fileData = createFileData(new TextDecoder().decode(content), undefined, this.fileFormat, mimeType); + const storeValue = this.convertFileDataToStoreValue(fileData); + await store.put(namespace, path3, storeValue); + responses.push({ + path: path3, + error: null + }); + } catch { + responses.push({ + path: path3, + error: "invalid_path" + }); + } + return responses; + } + async downloadFiles(paths) { + const store = this.getStore(); + const namespace = this.getNamespace(); + const responses = []; + for (const path3 of paths) + try { + const item = await store.get(namespace, path3); + if (!item) { + responses.push({ + path: path3, + content: null, + error: "file_not_found" + }); + continue; + } + const fileDataV2 = migrateToFileDataV2(this.convertStoreItemToFileData(item), path3); + if (typeof fileDataV2.content === "string") { + const content = new TextEncoder().encode(fileDataV2.content); + responses.push({ + path: path3, + content, + error: null + }); + } else + responses.push({ + path: path3, + content: fileDataV2.content, + error: null + }); + } catch { + responses.push({ + path: path3, + content: null, + error: "file_not_found" + }); + } + return responses; + } +}, SUPPORTS_NOFOLLOW, FilesystemBackend = class { + cwd; + virtualMode; + maxFileSizeBytes; + constructor(options = {}) { + const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options; + this.cwd = rootDir ? path$1.resolve(rootDir) : process.cwd(); + this.virtualMode = virtualMode; + this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024; + } + resolvePath(key) { + if (this.virtualMode) { + const vpath = key.startsWith("/") ? key : "/" + key; + if (vpath.includes("..") || vpath.startsWith("~")) + throw new Error("Path traversal not allowed"); + const full = path$1.resolve(this.cwd, vpath.substring(1)); + const relative2 = path$1.relative(this.cwd, full); + if (relative2.startsWith("..") || path$1.isAbsolute(relative2)) + throw new Error(`Path: ${full} outside root directory: ${this.cwd}`); + return full; + } + if (path$1.isAbsolute(key)) + return key; + return path$1.resolve(this.cwd, key); + } + async ls(dirPath) { + try { + const resolvedPath = this.resolvePath(dirPath); + if (!(await fs.stat(resolvedPath)).isDirectory()) + return { files: [] }; + const entries = await fs.readdir(resolvedPath, { withFileTypes: true }); + const results = []; + const cwdStr = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; + for (const entry of entries) { + const fullPath = path$1.join(resolvedPath, entry.name); + try { + const entryStat = await fs.stat(fullPath); + const isFile = entryStat.isFile(); + const isDir = entryStat.isDirectory(); + if (!this.virtualMode) { + if (isFile) + results.push({ + path: fullPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString() + }); + else if (isDir) + results.push({ + path: fullPath + path$1.sep, + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString() + }); + } else { + let relativePath; + if (fullPath.startsWith(cwdStr)) + relativePath = fullPath.substring(cwdStr.length); + else if (fullPath.startsWith(this.cwd)) + relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + else + relativePath = fullPath; + relativePath = relativePath.split(path$1.sep).join("/"); + const virtPath = "/" + relativePath; + if (isFile) + results.push({ + path: virtPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString() + }); + else if (isDir) + results.push({ + path: virtPath + "/", + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString() + }); + } + } catch { + continue; + } + } + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } catch { + return { files: [] }; + } + } + async read(filePath, offset = 0, limit = 500) { + try { + const resolvedPath = this.resolvePath(filePath); + const mimeType = getMimeType(filePath); + const isBinary = !isTextMimeType(mimeType); + let content; + if (SUPPORTS_NOFOLLOW) { + if (!(await fs.stat(resolvedPath)).isFile()) + return { error: `File '${filePath}' not found` }; + const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); + try { + if (isBinary) { + const buffer = await fd.readFile(); + return { + content: new Uint8Array(buffer), + mimeType + }; + } + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat4 = await fs.lstat(resolvedPath); + if (stat4.isSymbolicLink()) + return { error: `Symlinks are not allowed: ${filePath}` }; + if (!stat4.isFile()) + return { error: `File '${filePath}' not found` }; + if (isBinary) { + const buffer = await fs.readFile(resolvedPath); + return { + content: new Uint8Array(buffer), + mimeType + }; + } + content = await fs.readFile(resolvedPath, "utf-8"); + } + const emptyMsg = checkEmptyContent(content); + if (emptyMsg) + return { + content: emptyMsg, + mimeType + }; + const lines = content.split(` +`); + const startIdx = offset; + const endIdx = Math.min(startIdx + limit, lines.length); + if (startIdx >= lines.length) + return { error: `Line offset ${offset} exceeds file length (${lines.length} lines)` }; + return { + content: lines.slice(startIdx, endIdx).join(` +`), + mimeType + }; + } catch (e) { + return { error: `Error reading file '${filePath}': ${e.message}` }; + } + } + async readRaw(filePath) { + const resolvedPath = this.resolvePath(filePath); + const mimeType = getMimeType(filePath); + const isBinary = !isTextMimeType(mimeType); + let content; + let stat4; + if (SUPPORTS_NOFOLLOW) { + stat4 = await fs.stat(resolvedPath); + if (!stat4.isFile()) + return { error: `File '${filePath}' not found` }; + const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); + try { + if (isBinary) { + const buffer = await fd.readFile(); + return { data: { + content: new Uint8Array(buffer), + mimeType, + created_at: stat4.ctime.toISOString(), + modified_at: stat4.mtime.toISOString() + } }; + } + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + stat4 = await fs.lstat(resolvedPath); + if (stat4.isSymbolicLink()) + return { error: `Symlinks are not allowed: ${filePath}` }; + if (!stat4.isFile()) + return { error: `File '${filePath}' not found` }; + if (isBinary) { + const buffer = await fs.readFile(resolvedPath); + return { data: { + content: new Uint8Array(buffer), + mimeType, + created_at: stat4.ctime.toISOString(), + modified_at: stat4.mtime.toISOString() + } }; + } + content = await fs.readFile(resolvedPath, "utf-8"); + } + return { data: { + content, + mimeType, + created_at: stat4.ctime.toISOString(), + modified_at: stat4.mtime.toISOString() + } }; + } + async write(filePath, content) { + try { + const resolvedPath = this.resolvePath(filePath); + const isBinary = !isTextMimeType(getMimeType(filePath)); + try { + if ((await fs.lstat(resolvedPath)).isSymbolicLink()) + return { error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.` }; + return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; + } catch {} + await fs.mkdir(path$1.dirname(resolvedPath), { recursive: true }); + if (SUPPORTS_NOFOLLOW) { + const flags = fs$1.constants.O_WRONLY | fs$1.constants.O_CREAT | fs$1.constants.O_TRUNC | fs$1.constants.O_NOFOLLOW; + const fd = await fs.open(resolvedPath, flags, 420); + try { + if (isBinary) { + const buffer = Buffer.from(content, "base64"); + await fd.writeFile(buffer); + } else + await fd.writeFile(content, "utf-8"); + } finally { + await fd.close(); + } + } else if (isBinary) { + const buffer = Buffer.from(content, "base64"); + await fs.writeFile(resolvedPath, buffer); + } else + await fs.writeFile(resolvedPath, content, "utf-8"); + return { + path: filePath, + filesUpdate: null + }; + } catch (e) { + return { error: `Error writing file '${filePath}': ${e.message}` }; + } + } + async edit(filePath, oldString, newString, replaceAll = false) { + try { + const resolvedPath = this.resolvePath(filePath); + let content; + if (SUPPORTS_NOFOLLOW) { + if (!(await fs.stat(resolvedPath)).isFile()) + return { error: `Error: File '${filePath}' not found` }; + const fd = await fs.open(resolvedPath, fs$1.constants.O_RDONLY | fs$1.constants.O_NOFOLLOW); + try { + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat4 = await fs.lstat(resolvedPath); + if (stat4.isSymbolicLink()) + return { error: `Error: Symlinks are not allowed: ${filePath}` }; + if (!stat4.isFile()) + return { error: `Error: File '${filePath}' not found` }; + content = await fs.readFile(resolvedPath, "utf-8"); + } + const result = performStringReplacement(content, oldString, newString, replaceAll); + if (typeof result === "string") + return { error: result }; + const [newContent, occurrences] = result; + if (SUPPORTS_NOFOLLOW) { + const flags = fs$1.constants.O_WRONLY | fs$1.constants.O_TRUNC | fs$1.constants.O_NOFOLLOW; + const fd = await fs.open(resolvedPath, flags); + try { + await fd.writeFile(newContent, "utf-8"); + } finally { + await fd.close(); + } + } else + await fs.writeFile(resolvedPath, newContent, "utf-8"); + return { + path: filePath, + filesUpdate: null, + occurrences + }; + } catch (e) { + return { error: `Error editing file '${filePath}': ${e.message}` }; + } + } + async grep(pattern, dirPath = "/", glob = null) { + let baseFull; + try { + baseFull = this.resolvePath(dirPath || "."); + } catch { + return { matches: [] }; + } + try { + await fs.stat(baseFull); + } catch { + return { matches: [] }; + } + let results = await this.ripgrepSearch(pattern, baseFull, glob); + if (results === null) + results = await this.literalSearch(pattern, baseFull, glob); + const matches = []; + for (const [fpath, items] of Object.entries(results)) + for (const [lineNum, lineText] of items) + matches.push({ + path: fpath, + line: lineNum, + text: lineText + }); + return { matches }; + } + async ripgrepSearch(pattern, baseFull, includeGlob) { + return new Promise((resolve2) => { + const args = ["--json", "-F"]; + if (includeGlob) + args.push("--glob", includeGlob); + args.push("--", pattern, baseFull); + const proc = spawn("rg", args, { timeout: 30000 }); + const results = {}; + let output = ""; + proc.stdout.on("data", (data) => { + output += data.toString(); + }); + proc.on("close", (code) => { + if (code !== 0 && code !== 1) { + resolve2(null); + return; + } + for (const line of output.split(` +`)) { + if (!line.trim()) + continue; + try { + const data = JSON.parse(line); + if (data.type !== "match") + continue; + const pdata = data.data || {}; + const ftext = pdata.path?.text; + if (!ftext) + continue; + let virtPath; + if (this.virtualMode) + try { + const resolved = path$1.resolve(ftext); + const relative2 = path$1.relative(this.cwd, resolved); + if (relative2.startsWith("..")) + continue; + virtPath = "/" + relative2.split(path$1.sep).join("/"); + } catch { + continue; + } + else + virtPath = ftext; + const ln = pdata.line_number; + const lt = pdata.lines?.text?.replace(/\n$/, "") || ""; + if (ln === undefined) + continue; + if (!results[virtPath]) + results[virtPath] = []; + results[virtPath].push([ln, lt]); + } catch { + continue; + } + } + resolve2(results); + }); + proc.on("error", () => { + resolve2(null); + }); + }); + } + async literalSearch(pattern, baseFull, includeGlob) { + const results = {}; + const files = await import_fast_glob.default("**/*", { + cwd: (await fs.stat(baseFull)).isDirectory() ? baseFull : path$1.dirname(baseFull), + absolute: true, + onlyFiles: true, + dot: true + }); + for (const fp of files) + try { + if (!isTextMimeType(getMimeType(fp))) + continue; + if (includeGlob && !import_micromatch.default.isMatch(path$1.basename(fp), includeGlob)) + continue; + if ((await fs.stat(fp)).size > this.maxFileSizeBytes) + continue; + const lines = (await fs.readFile(fp, "utf-8")).split(` +`); + for (let i = 0;i < lines.length; i++) { + const line = lines[i]; + if (line.includes(pattern)) { + let virtPath; + if (this.virtualMode) + try { + const relative2 = path$1.relative(this.cwd, fp); + if (relative2.startsWith("..")) + continue; + virtPath = "/" + relative2.split(path$1.sep).join("/"); + } catch { + continue; + } + else + virtPath = fp; + if (!results[virtPath]) + results[virtPath] = []; + results[virtPath].push([i + 1, line]); + } + } + } catch { + continue; + } + return results; + } + async glob(pattern, searchPath = "/") { + if (pattern.startsWith("/")) + pattern = pattern.substring(1); + const resolvedSearchPath = searchPath === "/" ? this.cwd : this.resolvePath(searchPath); + try { + if (!(await fs.stat(resolvedSearchPath)).isDirectory()) + return { files: [] }; + } catch { + return { files: [] }; + } + const results = []; + try { + const matches = await import_fast_glob.default(pattern, { + cwd: resolvedSearchPath, + absolute: true, + onlyFiles: true, + dot: true + }); + for (const matchedPath of matches) + try { + const stat4 = await fs.stat(matchedPath); + if (!stat4.isFile()) + continue; + const normalizedPath = matchedPath.split("/").join(path$1.sep); + if (!this.virtualMode) + results.push({ + path: normalizedPath, + is_dir: false, + size: stat4.size, + modified_at: stat4.mtime.toISOString() + }); + else { + const cwdStr = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; + let relativePath; + if (normalizedPath.startsWith(cwdStr)) + relativePath = normalizedPath.substring(cwdStr.length); + else if (normalizedPath.startsWith(this.cwd)) + relativePath = normalizedPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + else + relativePath = normalizedPath; + relativePath = relativePath.split(path$1.sep).join("/"); + const virt = "/" + relativePath; + results.push({ + path: virt, + is_dir: false, + size: stat4.size, + modified_at: stat4.mtime.toISOString() + }); + } + } catch { + continue; + } + } catch {} + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + async uploadFiles(files) { + const responses = []; + for (const [filePath, content] of files) + try { + const resolvedPath = this.resolvePath(filePath); + await fs.mkdir(path$1.dirname(resolvedPath), { recursive: true }); + await fs.writeFile(resolvedPath, content); + responses.push({ + path: filePath, + error: null + }); + } catch (e) { + if (e.code === "ENOENT") + responses.push({ + path: filePath, + error: "file_not_found" + }); + else if (e.code === "EACCES") + responses.push({ + path: filePath, + error: "permission_denied" + }); + else if (e.code === "EISDIR") + responses.push({ + path: filePath, + error: "is_directory" + }); + else + responses.push({ + path: filePath, + error: "invalid_path" + }); + } + return responses; + } + async downloadFiles(paths) { + const responses = []; + for (const filePath of paths) + try { + const resolvedPath = this.resolvePath(filePath); + const content = await fs.readFile(resolvedPath); + responses.push({ + path: filePath, + content, + error: null + }); + } catch (e) { + if (e.code === "ENOENT") + responses.push({ + path: filePath, + content: null, + error: "file_not_found" + }); + else if (e.code === "EACCES") + responses.push({ + path: filePath, + content: null, + error: "permission_denied" + }); + else if (e.code === "EISDIR") + responses.push({ + path: filePath, + content: null, + error: "is_directory" + }); + else + responses.push({ + path: filePath, + content: null, + error: "invalid_path" + }); + } + return responses; + } +}, URL_COMMIT_SUFFIX_RE, TEXT_MIME_TYPE = "text/plain", FNMATCH_OPTIONS, ContextHubBackend = class ContextHubBackend2 { + identifier; + client; + cache = null; + linkedEntries = {}; + commitHash = null; + constructor(identifier, options = {}) { + this.identifier = identifier; + this.client = options.client ?? new Client; + } + static stripPrefix(path3) { + return path3.replace(/^\/+/, ""); + } + static toHubUnavailableError(error90) { + return `Hub unavailable: ${getErrorMessage(error90)}`; + } + async loadTree() { + let context2; + try { + context2 = await this.client.pullAgent(this.identifier); + } catch (error90) { + if (isLangSmithNotFoundError2(error90)) { + this.cache = {}; + this.linkedEntries = {}; + this.commitHash = null; + return; + } + throw error90; + } + this.commitHash = context2.commit_hash; + this.cache = {}; + this.linkedEntries = {}; + for (const [path3, entry] of Object.entries(context2.files)) + if (entry.type === "file") + this.cache[path3] = entry.content; + else if ((entry.type === "agent" || entry.type === "skill") && typeof entry.repo_handle === "string") + this.linkedEntries[path3] = entry.repo_handle; + } + async ensureCache() { + if (this.cache === null) + await this.loadTree(); + if (this.cache === null) + throw new Error("Context Hub cache failed to initialize"); + return this.cache; + } + async commit(files) { + if (Object.keys(files).length === 0) + return; + const payload = {}; + for (const [path3, content] of Object.entries(files)) + payload[path3] = { + type: "file", + content + }; + const url3 = await this.client.pushAgent(this.identifier, { + files: payload, + ...this.commitHash ? { parentCommit: this.commitHash } : {} + }); + const match2 = URL_COMMIT_SUFFIX_RE.exec(url3); + if (match2) + this.commitHash = match2[1]; + if (this.cache !== null) + for (const [path3, content] of Object.entries(files)) + this.cache[path3] = content; + } + async getLinkedEntries() { + await this.ensureCache(); + return { ...this.linkedEntries }; + } + async hasPriorCommits() { + await this.ensureCache(); + return this.commitHash !== null; + } + async ls(path3 = "/") { + const hubPrefix = ContextHubBackend2.stripPrefix(path3).replace(/\/+$/, ""); + let cache2; + try { + cache2 = await this.ensureCache(); + } catch (error90) { + if (isLangSmithError(error90)) + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + throw error90; + } + const dirs = /* @__PURE__ */ new Set; + const entries = []; + for (const filePath of Object.keys(cache2)) { + if (hubPrefix && !filePath.startsWith(`${hubPrefix}/`)) + continue; + const relative2 = hubPrefix ? filePath.slice(hubPrefix.length + 1) : filePath; + if (!relative2) + continue; + const slashIndex = relative2.indexOf("/"); + if (slashIndex === -1) { + entries.push({ + path: `/${filePath}`, + is_dir: false + }); + continue; + } + const dirName = relative2.slice(0, slashIndex); + const dirPath = hubPrefix ? `${hubPrefix}/${dirName}` : dirName; + if (!dirs.has(dirPath)) { + dirs.add(dirPath); + entries.push({ + path: `/${dirPath}`, + is_dir: true + }); + } + } + return { files: entries }; + } + async read(filePath, offset = 0, limit = 2000) { + const hubPath = ContextHubBackend2.stripPrefix(filePath); + let cache2; + try { + cache2 = await this.ensureCache(); + } catch (error90) { + if (isLangSmithError(error90)) + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + throw error90; + } + const content = cache2[hubPath]; + if (content === undefined) + return { error: `File '${filePath}' not found` }; + const sliced = sliceReadContent(content, offset, limit); + if (sliced.error) + return { error: sliced.error }; + return { + content: sliced.content ?? "", + mimeType: TEXT_MIME_TYPE + }; + } + async readRaw(filePath) { + const readResult = await this.read(filePath, 0, Number.MAX_SAFE_INTEGER); + if (readResult.error || typeof readResult.content !== "string") + return { error: readResult.error ?? `File '${filePath}' not found` }; + const now = (/* @__PURE__ */ new Date()).toISOString(); + return { data: { + content: readResult.content, + mimeType: TEXT_MIME_TYPE, + created_at: now, + modified_at: now + } }; + } + async grep(pattern, path3 = null, glob = null) { + let cache2; + try { + cache2 = await this.ensureCache(); + } catch (error90) { + if (isLangSmithError(error90)) + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + throw error90; + } + const prefix = path3 ? ContextHubBackend2.stripPrefix(path3).replace(/\/+$/, "") : ""; + const matches = []; + for (const [filePath, content] of Object.entries(cache2)) { + if (prefix && !filePath.startsWith(prefix)) + continue; + if (glob && !import_micromatch.default.isMatch(filePath, glob, FNMATCH_OPTIONS)) + continue; + const lines = content.split(` +`); + for (let index2 = 0;index2 < lines.length; index2++) { + const line = lines[index2]; + if (line.includes(pattern)) + matches.push({ + path: `/${filePath}`, + line: index2 + 1, + text: line + }); + } + } + return { matches }; + } + async glob(pattern, _path = "/") { + let cache2; + try { + cache2 = await this.ensureCache(); + } catch (error90) { + if (isLangSmithError(error90)) + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + throw error90; + } + const files = []; + for (const filePath of Object.keys(cache2)) + if (import_micromatch.default.isMatch(`/${filePath}`, pattern, FNMATCH_OPTIONS) || import_micromatch.default.isMatch(filePath, pattern, FNMATCH_OPTIONS)) + files.push({ + path: `/${filePath}`, + is_dir: false + }); + return { files }; + } + async write(filePath, content) { + const hubPath = ContextHubBackend2.stripPrefix(filePath); + try { + await this.ensureCache(); + await this.commit({ [hubPath]: content }); + } catch (error90) { + if (isLangSmithError(error90)) { + this.cache = null; + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + } + throw error90; + } + return { + path: filePath, + filesUpdate: null + }; + } + async edit(filePath, oldString, newString, replaceAll = false) { + const hubPath = ContextHubBackend2.stripPrefix(filePath); + try { + const current = (await this.ensureCache())[hubPath]; + if (current === undefined) + return { error: `Error: File '${filePath}' not found` }; + const replacementResult = performStringReplacement(current, oldString, newString, replaceAll); + if (typeof replacementResult === "string") + return { error: replacementResult }; + const [newContent, occurrences] = replacementResult; + await this.commit({ [hubPath]: newContent }); + return { + path: filePath, + filesUpdate: null, + occurrences + }; + } catch (error90) { + if (isLangSmithError(error90)) { + this.cache = null; + return { error: ContextHubBackend2.toHubUnavailableError(error90) }; + } + throw error90; + } + } + async uploadFiles(files) { + const decoder = new TextDecoder("utf-8", { fatal: true }); + const decoded = []; + const validFiles = {}; + for (const [path3, content] of files) + try { + const text = decoder.decode(content); + decoded.push([path3, text]); + validFiles[ContextHubBackend2.stripPrefix(path3)] = text; + } catch { + decoded.push([path3, null]); + } + let commitError = null; + if (Object.keys(validFiles).length > 0) + try { + await this.ensureCache(); + await this.commit(validFiles); + } catch (error90) { + if (isLangSmithError(error90)) { + this.cache = null; + commitError = mapHubFileOperationError(error90); + } else + throw error90; + } + return decoded.map(([path3, text]) => { + if (text === null) + return { + path: path3, + error: "invalid_path" + }; + if (commitError !== null) + return { + path: path3, + error: commitError + }; + return { + path: path3, + error: null + }; + }); + } + async downloadFiles(paths) { + let cache2; + try { + cache2 = await this.ensureCache(); + } catch (error90) { + if (isLangSmithError(error90)) { + const mappedError = mapHubFileOperationError(error90); + return paths.map((path3) => ({ + path: path3, + content: null, + error: mappedError + })); + } + throw error90; + } + const encoder2 = new TextEncoder; + return paths.map((path3) => { + const hubPath = ContextHubBackend2.stripPrefix(path3); + const content = cache2[hubPath]; + if (content !== undefined) + return { + path: path3, + content: encoder2.encode(content), + error: null + }; + return { + path: path3, + content: null, + error: "file_not_found" + }; + }); + } +}, LocalShellBackend, STAT_C_SCRIPT = 'for f; do if [ -d "$f" ]; then t=d; elif [ -L "$f" ]; then t=l; else t=f; fi; sz=$(stat -c %s "$f" 2>/dev/null) || continue; mt=$(stat -c %Y "$f" 2>/dev/null) || continue; printf "%s\\t%s\\t%s\\t%s\\n" "$sz" "$mt" "$t" "$f"; done', BaseSandbox = class { + async ls(path3) { + const command = buildLsCommand(path3); + const result = await this.execute(command); + const infos = []; + const lines = result.output.trim().split(` +`).filter(Boolean); + for (const line of lines) { + const parsed = parseStatLine(line); + if (!parsed) + continue; + infos.push({ + path: parsed.isDir ? parsed.fullPath + "/" : parsed.fullPath, + is_dir: parsed.isDir, + size: parsed.size, + modified_at: (/* @__PURE__ */ new Date(parsed.mtime * 1000)).toISOString() + }); + } + return { files: infos }; + } + async read(filePath, offset = 0, limit = 500) { + const mimeType = getMimeType(filePath); + if (!isTextMimeType(mimeType)) { + const results = await this.downloadFiles([filePath]); + if (results[0].error || !results[0].content) + return { error: `File '${filePath}' not found` }; + return { + content: results[0].content, + mimeType + }; + } + if (limit === 0) + return { + content: "", + mimeType + }; + const command = buildReadCommand(filePath, offset, limit); + const result = await this.execute(command); + if (result.exitCode !== 0) + return { error: `File '${filePath}' not found` }; + return { + content: result.output, + mimeType + }; + } + async readRaw(filePath) { + const results = await this.downloadFiles([filePath]); + if (results[0].error || !results[0].content) + return { error: `File '${filePath}' not found` }; + const now = (/* @__PURE__ */ new Date()).toISOString(); + const mimeType = getMimeType(filePath); + if (!isTextMimeType(mimeType)) + return { data: { + content: results[0].content, + mimeType, + created_at: now, + modified_at: now + } }; + return { data: { + content: new TextDecoder().decode(results[0].content), + mimeType, + created_at: now, + modified_at: now + } }; + } + async grep(pattern, path3 = "/", glob = null) { + const command = buildGrepCommand(pattern, path3, glob); + const output = (await this.execute(command)).output.trim(); + if (!output) + return { matches: [] }; + const matches = []; + for (const line of output.split(` +`)) { + const parts = line.split(":"); + if (parts.length >= 3) { + const filePath = parts[0]; + if (!isTextMimeType(getMimeType(filePath))) + continue; + const lineNum = parseInt(parts[1], 10); + if (!isNaN(lineNum)) + matches.push({ + path: filePath, + line: lineNum, + text: parts.slice(2).join(":") + }); + } + } + return { matches }; + } + async glob(pattern, path3 = "/") { + const command = buildFindCommand(path3); + const result = await this.execute(command); + const regex2 = globToPathRegex(pattern); + const infos = []; + const lines = result.output.trim().split(` +`).filter(Boolean); + const basePath = path3.endsWith("/") ? path3.slice(0, -1) : path3; + for (const line of lines) { + const parsed = parseStatLine(line); + if (!parsed) + continue; + const relPath = parsed.fullPath.startsWith(basePath + "/") ? parsed.fullPath.slice(basePath.length + 1) : parsed.fullPath; + if (regex2.test(relPath)) + infos.push({ + path: relPath, + is_dir: parsed.isDir, + size: parsed.size, + modified_at: (/* @__PURE__ */ new Date(parsed.mtime * 1000)).toISOString() + }); + } + return { files: infos }; + } + async write(filePath, content) { + try { + const existCheck = await this.downloadFiles([filePath]); + if (existCheck[0].content !== null && existCheck[0].error === null) + return { error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.` }; + } catch {} + const mimeType = getMimeType(filePath); + let fileContent; + if (isTextMimeType(mimeType)) + fileContent = new TextEncoder().encode(content); + else + fileContent = Buffer.from(content, "base64"); + const results = await this.uploadFiles([[filePath, fileContent]]); + if (results[0].error) + return { error: `Failed to write to ${filePath}: ${results[0].error}` }; + return { + path: filePath, + filesUpdate: null + }; + } + async edit(filePath, oldString, newString, replaceAll = false) { + const results = await this.downloadFiles([filePath]); + if (results[0].error || !results[0].content) + return { error: `Error: File '${filePath}' not found` }; + const text = new TextDecoder().decode(results[0].content); + results[0].content = null; + if (oldString.length === 0) { + if (text.length !== 0) + return { error: "oldString must not be empty unless the file is empty" }; + if (newString.length === 0) + return { + path: filePath, + filesUpdate: null, + occurrences: 0 + }; + const encoded2 = new TextEncoder().encode(newString); + const uploadResults2 = await this.uploadFiles([[filePath, encoded2]]); + if (uploadResults2[0].error) + return { error: `Failed to write edited file '${filePath}': ${uploadResults2[0].error}` }; + return { + path: filePath, + filesUpdate: null, + occurrences: 1 + }; + } + const firstIdx = text.indexOf(oldString); + if (firstIdx === -1) + return { error: `String not found in file '${filePath}'` }; + if (oldString === newString) + return { + path: filePath, + filesUpdate: null, + occurrences: 1 + }; + let newText; + let count; + if (replaceAll) { + newText = text.replaceAll(oldString, newString); + const lenDiff = oldString.length - newString.length; + if (lenDiff !== 0) + count = (text.length - newText.length) / lenDiff; + else { + count = 1; + let pos = firstIdx + oldString.length; + while (pos <= text.length) { + const idx = text.indexOf(oldString, pos); + if (idx === -1) + break; + count++; + pos = idx + oldString.length; + } + } + } else { + if (text.indexOf(oldString, firstIdx + oldString.length) !== -1) + return { error: `Multiple occurrences found in '${filePath}'. Use replaceAll=true to replace all.` }; + count = 1; + newText = text.slice(0, firstIdx) + newString + text.slice(firstIdx + oldString.length); + } + const encoded = new TextEncoder().encode(newText); + const uploadResults = await this.uploadFiles([[filePath, encoded]]); + if (uploadResults[0].error) + return { error: `Failed to write edited file '${filePath}': ${uploadResults[0].error}` }; + return { + path: filePath, + filesUpdate: null, + occurrences: count + }; + } +}, LangSmithSandbox, CONFIGURATION_ERROR_SYMBOL, ConfigurationError, REQUIRED_MIDDLEWARE_NAMES, EMPTY_HARNESS_PROFILE, POISONED_KEYS, generalPurposeSubagentConfigSchema, harnessProfileConfigSchema, SYSTEM_PROMPT_SUFFIX$3 = ` +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. + + + +When a task depends on the state of files, tests, or system output, use tools to observe that state directly rather than reasoning from memory about what it probably contains. Read files before describing them. Run tests before claiming they pass. Search the codebase before asserting a symbol does or does not exist. Active investigation with tools is the default mode of working, not a fallback. + + + +Do not spawn a subagent for work you can complete directly in a single response (e.g. refactoring a function you can already see). + +Spawn multiple subagents in the same turn when fanning out across items or reading multiple files. +`, SYSTEM_PROMPT_SUFFIX$2 = ` +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. +`, SYSTEM_PROMPT_SUFFIX$1 = ` +If you intend to call multiple tools and there are no dependencies between the tool calls, make all of the independent tool calls in parallel. Prioritize calling tools simultaneously whenever the actions can be done in parallel rather than sequentially. For example, when reading 3 files, run 3 tool calls in parallel to read all 3 files into context at the same time. Maximize use of parallel tool calls where possible to increase speed and efficiency. However, if some tool calls depend on previous calls to inform dependent values like the parameters, do NOT call these tools in parallel and instead call them sequentially. Never use placeholders or guess missing parameters in tool calls. + + + +Never speculate about code you have not opened. If the user references a specific file, you MUST read the file before answering. Make sure to investigate and read relevant files BEFORE answering questions about the codebase. Never make any claims about code before investigating unless you are certain of the correct answer - give grounded and hallucination-free answers. + + + +After receiving tool results, carefully reflect on their quality and determine optimal next steps before proceeding. Use your thinking to plan and iterate based on this new information, and then take the best next action. +`, CODEX_MODEL_SPECS, SYSTEM_PROMPT_SUFFIX = `## Codex-Specific Behavior + +- You are an autonomous senior engineer. Once given a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. +- Persist until the task is fully handled end-to-end within the current turn whenever feasible. Do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes. +- Bias to action: default to implementing with reasonable assumptions. Do not end your turn with clarifications unless truly blocked. +- Do not communicate an upfront plan or status preamble before acting. Just act. + +## Parallel Tool Use + +- Before any tool call, decide ALL files and resources you will need. +- Batch reads, searches, and other independent operations into parallel tool calls instead of issuing them one at a time. +- Only make sequential calls when you truly cannot determine the next step without seeing a prior result. + +## Plan Hygiene + +- Before finishing, reconcile every TODO or plan item created via write_todos. Mark each as done, blocked (with a one-sentence reason), or cancelled. Do not finish with pending items.`, PROFILE_REGISTRY_KEY, BASE_AGENT_PROMPT, BUILTIN_TOOL_NAMES, AgentMemoryStateSchema, DEFAULT_MEMORY_TEMPLATE = ` +{user_memory} + + + +{project_memory} +`, LONGTERM_MEMORY_SYSTEM_PROMPT = ` + +## Long-term Memory + +Your long-term memory is stored in files on the filesystem and persists across sessions. + +**User Memory Location**: \`{agent_dir_absolute}\` (displays as \`{agent_dir_display}\`) +**Project Memory Location**: {project_memory_info} + +Your system prompt is loaded from TWO sources at startup: +1. **User agent.md**: \`{agent_dir_absolute}/agent.md\` - Your personal preferences across all projects +2. **Project agent.md**: Loaded from project root if available - Project-specific instructions + +Project-specific agent.md is loaded from these locations (both combined if both exist): +- \`[project-root]/.deepagents/agent.md\` (preferred) +- \`[project-root]/agent.md\` (fallback, but also included if both exist) + +**When to CHECK/READ memories (CRITICAL - do this FIRST):** +- **At the start of ANY new session**: Check both user and project memories + - User: \`ls {agent_dir_absolute}\` + - Project: \`ls {project_deepagents_dir}\` (if in a project) +- **BEFORE answering questions**: If asked "what do you know about X?" or "how do I do Y?", check project memories FIRST, then user +- **When user asks you to do something**: Check if you have project-specific guides or examples +- **When user references past work**: Search project memory files for related context + +**Memory-first response pattern:** +1. User asks a question → Check project directory first: \`ls {project_deepagents_dir}\` +2. If relevant files exist → Read them with \`read_file '{project_deepagents_dir}/[filename]'\` +3. Check user memory if needed → \`ls {agent_dir_absolute}\` +4. Base your answer on saved knowledge supplemented by general knowledge + +**When to update memories:** +- **IMMEDIATELY when the user describes your role or how you should behave** +- **IMMEDIATELY when the user gives feedback on your work** - Update memories to capture what was wrong and how to do it better +- When the user explicitly asks you to remember something +- When patterns or preferences emerge (coding styles, conventions, workflows) +- After significant work where context would help in future sessions + +**Learning from feedback:** +- When user says something is better/worse, capture WHY and encode it as a pattern +- Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions +- When user says "you should remember X" or "be careful about Y", treat this as HIGH PRIORITY - update memories IMMEDIATELY +- Look for the underlying principle behind corrections, not just the specific mistake + +## Deciding Where to Store Memory + +When writing or updating agent memory, decide whether each fact, configuration, or behavior belongs in: + +### User Agent File: \`{agent_dir_absolute}/agent.md\` +→ Describes the agent's **personality, style, and universal behavior** across all projects. + +**Store here:** +- Your general tone and communication style +- Universal coding preferences (formatting, comment style, etc.) +- General workflows and methodologies you follow +- Tool usage patterns that apply everywhere +- Personal preferences that don't change per-project + +**Examples:** +- "Be concise and direct in responses" +- "Always use type hints in Python" +- "Prefer functional programming patterns" + +### Project Agent File: \`{project_deepagents_dir}/agent.md\` +→ Describes **how this specific project works** and **how the agent should behave here only.** + +**Store here:** +- Project-specific architecture and design patterns +- Coding conventions specific to this codebase +- Project structure and organization +- Testing strategies for this project +- Deployment processes and workflows +- Team conventions and guidelines + +**Examples:** +- "This project uses FastAPI with SQLAlchemy" +- "Tests go in tests/ directory mirroring src/ structure" +- "All API changes require updating OpenAPI spec" + +### Project Memory Files: \`{project_deepagents_dir}/*.md\` +→ Use for **project-specific reference information** and structured notes. + +**Store here:** +- API design documentation +- Architecture decisions and rationale +- Deployment procedures +- Common debugging patterns +- Onboarding information + +**Examples:** +- \`{project_deepagents_dir}/api-design.md\` - REST API patterns used +- \`{project_deepagents_dir}/architecture.md\` - System architecture overview +- \`{project_deepagents_dir}/deployment.md\` - How to deploy this project + +### File Operations: + +**User memory:** +\`\`\` +ls {agent_dir_absolute} # List user memory files +read_file '{agent_dir_absolute}/agent.md' # Read user preferences +edit_file '{agent_dir_absolute}/agent.md' ... # Update user preferences +\`\`\` + +**Project memory (preferred for project-specific information):** +\`\`\` +ls {project_deepagents_dir} # List project memory files +read_file '{project_deepagents_dir}/agent.md' # Read project instructions +edit_file '{project_deepagents_dir}/agent.md' ... # Update project instructions +write_file '{project_deepagents_dir}/agent.md' ... # Create project memory file +\`\`\` + +**Important**: +- Project memory files are stored in \`.deepagents/\` inside the project root +- Always use absolute paths for file operations +- Check project memories BEFORE user when answering project-specific questions`, MAX_SKILL_DESCRIPTION_LENGTH$1 = 1024, SKILL_NAME_PATTERN, FRONTMATTER_PATTERN; +var init_dist9 = __esm(() => { + init_dist5(); + init_dist6(); + init_v44(); + init_messages(); + init_zod(); + init_zod(); + init_dist8(); + init_errors3(); + init_universal(); + init_langsmith(); + init_sandbox3(); + import_micromatch = __toESM(require_micromatch(), 1); + import_yaml = __toESM(require_dist3(), 1); + import_fast_glob = __toESM(require_out4(), 1); + MIME_TYPES = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".svg": "image/svg+xml", + ".heic": "image/heic", + ".heif": "image/heif", + ".mp3": "audio/mpeg", + ".wav": "audio/wav", + ".aiff": "audio/aiff", + ".aac": "audio/aac", + ".ogg": "audio/ogg", + ".flac": "audio/flac", + ".mp4": "video/mp4", + ".webm": "video/webm", + ".mpeg": "video/mpeg", + ".mov": "video/quicktime", + ".avi": "video/x-msvideo", + ".flv": "video/x-flv", + ".mpg": "video/mpeg", + ".wmv": "video/x-ms-wmv", + ".3gpp": "video/3gpp", + ".pdf": "application/pdf", + ".ppt": "application/vnd.ms-powerpoint", + ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation" + }; + SANDBOX_ERROR_SYMBOL = Symbol.for("sandbox.error"); + SandboxError = class SandboxError2 extends Error { + [SANDBOX_ERROR_SYMBOL] = true; + name = "SandboxError"; + constructor(message, code, cause) { + super(message); + this.code = code; + this.cause = cause; + Object.setPrototypeOf(this, SandboxError2.prototype); + } + static isInstance(error90) { + return typeof error90 === "object" && error90 !== null && error90[SANDBOX_ERROR_SYMBOL] === true; + } + }; + INT_FORMATTER = new Intl.NumberFormat("en-US"); + FILESYSTEM_TOOL_NAMES = [ + "ls", + "read_file", + "write_file", + "edit_file", + "glob", + "grep", + "execute" + ]; + TOOLS_EXCLUDED_FROM_EVICTION = [ + "ls", + "glob", + "grep", + "read_file", + "edit_file", + "write_file" + ]; + MAX_BINARY_READ_SIZE_BYTES = 10 * 1024 * 1024; + TOO_LARGE_TOOL_MSG = context` + Tool result too large, the result of this tool call {tool_call_id} was saved in the filesystem at this path: {file_path} + You can read the result from the filesystem by using the read_file tool, but make sure to only read part of the result at a time. + You can do this by specifying an offset and limit in the read_file tool call. + For example, to read the first ${100} lines, you can use the read_file tool with offset=0 and limit=${100}. + + Here is a preview showing the head and tail of the result (lines of the form + ... [N lines truncated] ... + indicate omitted lines in the middle of the content): + + {content_sample} +`; + FileDataV1Schema = exports_external.object({ + content: exports_external.array(exports_external.string()), + created_at: exports_external.string(), + modified_at: exports_external.string() + }); + FileDataV2Schema = exports_external.object({ + content: exports_external.union([exports_external.string(), exports_external.instanceof(Uint8Array)]), + mimeType: exports_external.string(), + created_at: exports_external.string(), + modified_at: exports_external.string() + }); + FileDataSchema = exports_external.union([FileDataV1Schema, FileDataV2Schema]); + FilesystemStateSchema = new StateSchema2({ files: new ReducedValue2(exports_external.record(exports_external.string(), FileDataSchema).default(() => ({})), { + inputSchema: exports_external.record(exports_external.string(), FileDataSchema.nullable()).optional(), + reducer: fileDataReducer + }) }); + FILESYSTEM_SYSTEM_PROMPT = context` + ## Following Conventions + + - Read files before editing — understand existing content before making changes + - Mimic existing style, naming conventions, and patterns + + ## Filesystem Tools \`ls\`, \`read_file\`, \`write_file\`, \`edit_file\`, \`glob\`, \`grep\` + + You have access to a filesystem which you can interact with using these tools. + All file paths must start with a /. + + - ls: list files in a directory (requires absolute path) + - read_file: read a file from the filesystem + - write_file: write to a file in the filesystem + - edit_file: edit a file in the filesystem + - glob: find files matching a pattern (e.g., "**/*.py") + - grep: search for text within files +`; + LS_TOOL_DESCRIPTION = context` + Lists all files in a directory. + + This is useful for exploring the filesystem and finding the right file to read or edit. + You should almost ALWAYS use this tool before using the read_file or edit_file tools. +`; + READ_FILE_TOOL_DESCRIPTION = context` + Reads a file from the filesystem. + + Assume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned. + + Usage: + - By default, it reads up to ${100} lines starting from the beginning of the file + - **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow + - First scan: read_file(path, limit=${100}) to see file structure + - Read more sections: read_file(path, offset=${100}, limit=200) for next 200 lines + - Only omit limit (read full file) when necessary for editing + - Specify offset and limit: read_file(path, offset=0, limit=${100}) reads first ${100} lines + - Results are returned using cat -n format, with line numbers starting at 1 +- Lines longer than ${INT_FORMATTER.format(MAX_LINE_LENGTH)} characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). When you specify a limit, these continuation lines count towards the limit. + - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. + - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents. + - You should ALWAYS make sure a file has been read before editing it. +`; + WRITE_FILE_TOOL_DESCRIPTION = context` + Writes to a new file in the filesystem. + + Usage: + - The write_file tool will create a new file. + - Prefer to edit existing files (with the edit_file tool) over creating new ones when possible. +`; + EDIT_FILE_TOOL_DESCRIPTION = context` + Performs exact string replacements in files. + + Usage: + - You must read the file before editing. This tool will error if you attempt an edit without reading the file first. + - When editing, preserve the exact indentation (tabs/spaces) from the read output. Never include line number prefixes in old_string or new_string. + - ALWAYS prefer editing existing files over creating new ones. + - Only use emojis if the user explicitly requests it. +`; + GLOB_TOOL_DESCRIPTION = context` + Find files matching a glob pattern. + + Supports standard glob patterns: \`*\` (any characters), \`**\` (any directories), \`?\` (single character). + Returns a list of absolute file paths that match the pattern. + + Examples: + - \`**/*.py\` - Find all Python files + - \`*.txt\` - Find all text files in root + - \`/subdir/**/*.md\` - Find all markdown files under /subdir +`; + GREP_TOOL_DESCRIPTION = context` + Search for a text pattern across files. + + Searches for literal text (not regex) and returns matching files or content based on output_mode. + Special characters like parentheses, brackets, pipes, etc. are treated as literal characters, not regex operators. + + Examples: + - Search all files: \`grep(pattern="TODO")\` + - Search Python files only: \`grep(pattern="import", glob="*.py")\` + - Show matching lines: \`grep(pattern="error", output_mode="content")\` + - Search for code with special chars: \`grep(pattern="def __init__(self):")\` +`; + EXECUTE_TOOL_DESCRIPTION = context` + Executes a shell command in an isolated sandbox environment. + + Usage: + Executes a given command in the sandbox environment with proper handling and security measures. + Before executing the command, please follow these steps: + + 1. Directory Verification: + - If the command will create new directories or files, first use the ls tool to verify the parent directory exists and is the correct location + - For example, before running "mkdir foo/bar", first use ls to check that "foo" exists and is the intended parent directory + + 2. Command Execution: + - Always quote file paths that contain spaces with double quotes (e.g., cd "path with spaces/file.txt") + - Examples of proper quoting: + - cd "/Users/name/My Documents" (correct) + - cd /Users/name/My Documents (incorrect - will fail) + - python "/path/with spaces/script.py" (correct) + - python /path/with spaces/script.py (incorrect - will fail) + - After ensuring proper quoting, execute the command + - Capture the output of the command + + Usage notes: + - Commands run in an isolated sandbox environment + - Returns combined stdout/stderr output with exit code + - If the output is very large, it may be truncated + - VERY IMPORTANT: You MUST avoid using search commands like find and grep. Instead use the grep, glob tools to search. You MUST avoid read tools like cat, head, tail, and use read_file to read files. + - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings) + - Use '&&' when commands depend on each other (e.g., "mkdir dir && cd dir") + - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail + - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd + + Examples: + Good examples: + - execute(command="pytest /foo/bar/tests") + - execute(command="python /path/to/script.py") + - execute(command="npm install && npm test") + + Bad examples (avoid these): + - execute(command="cd /foo/bar && pytest tests") # Use absolute path instead + - execute(command="cat file.txt") # Use read_file tool instead + - execute(command="find . -name '*.py'") # Use glob tool instead + - execute(command="grep -r 'pattern' .") # Use grep tool instead + + Note: This tool is only available if the backend supports execution (SandboxBackendProtocol). + If execution is not supported, the tool will return an error message. +`; + EXECUTION_SYSTEM_PROMPT = context` + ## Execute Tool \`execute\` + + You have access to an \`execute\` tool for running shell commands in a sandboxed environment. + Use this tool to run commands, scripts, tests, builds, and other shell operations. + + - execute: run a shell command in the sandbox (returns output and exit code) +`; + EXCLUDED_STATE_KEYS = [ + "messages", + "todos", + "structuredResponse", + "skillsMetadata", + "memoryContents" + ]; + TASK_SYSTEM_PROMPT = context` + ## \`task\` (subagent spawner) + + You have access to a \`task\` tool to launch short-lived subagents that handle isolated tasks. These agents are ephemeral — they live only for the duration of the task and return a single result. + + When to use the task tool: + - When a task is complex and multi-step, and can be fully delegated in isolation + - When a task is independent of other tasks and can run in parallel + - When a task requires focused reasoning or heavy token/context usage that would bloat the orchestrator thread + - When sandboxing improves reliability (e.g. code execution, structured searches, data formatting) + - When you only care about the output of the subagent, and not the intermediate steps (ex. performing a lot of research and then returned a synthesized report, performing a series of computations or lookups to achieve a concise, relevant answer.) + + Subagent lifecycle: + 1. **Spawn** → Provide clear role, instructions, and expected output + 2. **Run** → The subagent completes the task autonomously + 3. **Return** → The subagent provides a single structured result + 4. **Reconcile** → Incorporate or synthesize the result into the main thread + + When NOT to use the task tool: + - If you need to see the intermediate reasoning or steps after the subagent has completed (the task tool hides them) + - If the task is trivial (a few tool calls or simple lookup) + - If delegating does not reduce token usage, complexity, or context switching + - If splitting would add latency without benefit + + ## Important Task Tool Usage Notes to Remember + - Whenever possible, parallelize the work that you do. This is true for both tool_calls, and for tasks. Whenever you have independent steps to complete - make tool_calls, or kick off tasks (subagents) in parallel to accomplish them faster. This saves time for the user, which is incredibly important. + - Remember to use the \`task\` tool to silo independent tasks within a multi-part objective. + - You should use the \`task\` tool whenever you have a complex task that will take multiple steps, and is independent from other tasks that the agent needs to complete. These agents are highly competent and efficient. +`; + GENERAL_PURPOSE_SUBAGENT = { + name: "general-purpose", + description: DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + systemPrompt: DEFAULT_SUBAGENT_PROMPT + }; + INVALID_TOOL_MESSAGE_BLOCK_TYPES = [ + "tool_use", + "thinking", + "redacted_thinking" + ]; + filesValue = new ReducedValue2(exports_external.record(exports_external.string(), FileDataSchema).default(() => ({})), { + inputSchema: exports_external.record(exports_external.string(), FileDataSchema.nullable()).optional(), + reducer: fileDataReducer + }); + MemoryStateSchema = new StateSchema2({ + memoryContents: exports_external.record(exports_external.string(), exports_external.string()).optional(), + files: filesValue + }); + MEMORY_SYSTEM_PROMPT = context` + + {memory_contents} + + + + The above was loaded in from files in your filesystem. As you learn from your interactions with the user, you can save new knowledge by calling the \`edit_file\` tool. + + **Learning from feedback:** + - One of your MAIN PRIORITIES is to learn from your interactions with the user. These learnings can be implicit or explicit. This means that in the future, you will remember this important information. + - When you need to remember something, updating memory must be your FIRST, IMMEDIATE action - before responding to the user, before calling other tools, before doing anything else. Just update memory immediately. + - When user says something is better/worse, capture WHY and encode it as a pattern. + - Each correction is a chance to improve permanently - don't just fix the immediate issue, update your instructions. + - A great opportunity to update your memories is when the user interrupts a tool call and provides feedback. You should update your memories immediately before revising the tool call. + - Look for the underlying principle behind corrections, not just the specific mistake. + - The user might not explicitly ask you to remember something, but if they provide information that is useful for future use, you should update your memories immediately. + + **Asking for information:** + - If you lack context to perform an action (e.g. send a Slack DM, requires a user ID/email) you should explicitly ask the user for this information. + - It is preferred for you to ask for information, don't assume anything that you do not know! + - When the user provides information that is useful for future use, you should update your memories immediately. + + **When to update memories:** + - When the user explicitly asks you to remember something (e.g., "remember my email", "save this preference") + - When the user describes your role or how you should behave (e.g., "you are a web researcher", "always do X") + - When the user gives feedback on your work - capture what was wrong and how to improve + - When the user provides information required for tool use (e.g., slack channel ID, email addresses) + - When the user provides context useful for future tasks, such as how to use tools, or which actions to take in a particular situation + - When you discover new patterns or preferences (coding styles, conventions, workflows) + + **When to NOT update memories:** + - When the information is temporary or transient (e.g., "I'm running late", "I'm on my phone right now") + - When the information is a one-time task request (e.g., "Find me a recipe", "What's 25 * 4?") + - When the information is a simple question that doesn't reveal lasting preferences (e.g., "What day is it?", "Can you explain X?") + - When the information is an acknowledgment or small talk (e.g., "Sounds good!", "Hello", "Thanks for that") + - When the information is stale or irrelevant in future conversations + - Never store API keys, access tokens, passwords, or any other credentials in any file, memory, or system prompt. + - If the user asks where to put API keys or provides an API key, do NOT echo or save it. + + **Examples:** + Example 1 (remembering user information): + User: Can you connect to my google account? + Agent: Sure, I'll connect to your google account, what's your google account email? + User: john@example.com + Agent: Let me save this to my memory. + Tool Call: edit_file(...) -> remembers that the user's google account email is john@example.com + + Example 2 (remembering implicit user preferences): + User: Can you write me an example for creating a deep agent in LangChain? + Agent: Sure, I'll write you an example for creating a deep agent in LangChain + User: Can you do this in JavaScript + Agent: Let me save this to my memory. + Tool Call: edit_file(...) -> remembers that the user prefers to get LangChain code examples in JavaScript + Agent: Sure, here is the JavaScript example + + Example 3 (do not remember transient information): + User: I'm going to play basketball tonight so I will be offline for a few hours. + Agent: Okay I'll add a block to your calendar. + Tool Call: create_calendar_event(...) -> just calls a tool, does not commit anything to memory, as it is transient information + +`; + MAX_SKILL_FILE_SIZE = 10 * 1024 * 1024; + SKILL_MODULE_EXTENSIONS = [ + ".js", + ".mjs", + ".cjs", + ".ts", + ".mts", + ".cts", + ".jsx", + ".tsx" + ]; + SkillMetadataEntrySchema = exports_external.object({ + name: exports_external.string(), + description: exports_external.string(), + path: exports_external.string(), + license: exports_external.string().nullable().optional(), + compatibility: exports_external.string().nullable().optional(), + metadata: exports_external.record(exports_external.string(), exports_external.string()).optional(), + allowedTools: exports_external.array(exports_external.string()).optional(), + module: exports_external.string().optional() + }); + SkillsStateSchema = new StateSchema2({ + skillsMetadata: new ReducedValue2(exports_external.array(SkillMetadataEntrySchema).default(() => []), { + inputSchema: exports_external.array(SkillMetadataEntrySchema).optional(), + reducer: skillsMetadataReducer + }), + files: filesValue + }); + SKILLS_SYSTEM_PROMPT = context` + ## Skills System + + You have access to a skills library that provides specialized capabilities and domain knowledge. + + {skills_locations} + + **Available Skills:** + + {skills_list} + + **How to Use Skills (Progressive Disclosure):** + + Skills follow a **progressive disclosure** pattern - you know they exist (name + description above), but you only read the full instructions when needed: + + 1. **Recognize when a skill applies**: Check if the user's task matches any skill's description + 2. **Read the skill's full instructions**: Use \`read_file\` on the path shown in the skill list above. + Pass \`limit=${DEFAULT_SKILL_READ_LINE_LIMIT}\` since the default of ${100} lines is too small for most skill files. + 3. **Follow the skill's instructions**: SKILL.md contains step-by-step workflows, best practices, and examples + 4. **Access supporting files**: Skills may include scripts, configs, or reference docs - use absolute paths + + **When to Use Skills:** + - When the user's request matches a skill's domain (e.g., "research X" → web-research skill) + - When you need specialized knowledge or structured workflows + - When a skill provides proven patterns for complex tasks + + **Skills are Self-Documenting:** + - Each SKILL.md tells you exactly what the skill does and how to use it + - The skill list above shows the full path for each skill's SKILL.md file + + **Executing Skill Scripts:** + Skills may contain scripts or other executable files. Always use absolute paths from the skill list. + + **Example Workflow:** + + User: "Can you research the latest developments in quantum computing?" + + 1. Check available skills above → See "web-research" skill with its full path + 2. Read the full skill file: \`read_file(path, limit=${DEFAULT_SKILL_READ_LINE_LIMIT})\` + 3. Follow the skill's research workflow (search → organize → synthesize) + 4. Use any helper scripts with absolute paths + + Remember: Skills are tools to make you more capable and consistent. When in doubt, check if a skill exists for the task! +`; + CompletionCallbackStateSchema = object({ + [CALLBACK_THREAD_ID_KEY]: string2().optional() + }); + FALLBACK_TRIGGER = { + type: "tokens", + value: 170000 + }; + FALLBACK_KEEP = { + type: "messages", + value: 6 + }; + FALLBACK_TRUNCATE_ARGS = { + trigger: { + type: "messages", + value: 20 + }, + keep: { + type: "messages", + value: 20 + } + }; + PROFILE_TRIGGER = { + type: "fraction", + value: 0.85 + }; + PROFILE_KEEP = { + type: "fraction", + value: 0.1 + }; + PROFILE_TRUNCATE_ARGS = { + trigger: { + type: "fraction", + value: 0.85 + }, + keep: { + type: "fraction", + value: 0.1 + } + }; + SummarizationEventSchema = exports_external.object({ + cutoffIndex: exports_external.number(), + summaryMessage: exports_external.instanceof(HumanMessage), + filePath: exports_external.string().nullable() + }); + SummarizationStateSchema = exports_external.object({ + _summarizationSessionId: exports_external.string().optional(), + _summarizationEvent: SummarizationEventSchema.optional() + }); + AsyncTaskSchema = exports_external.object({ + taskId: exports_external.string(), + agentName: exports_external.string(), + threadId: exports_external.string(), + runId: exports_external.string(), + status: exports_external.string(), + createdAt: exports_external.string(), + description: exports_external.string().optional(), + updatedAt: exports_external.string().optional(), + checkedAt: exports_external.string().optional() + }); + AsyncTaskStateSchema = new StateSchema2({ asyncTasks: new ReducedValue2(exports_external.record(exports_external.string(), AsyncTaskSchema).default(() => ({})), { + inputSchema: exports_external.record(exports_external.string(), AsyncTaskSchema).optional(), + reducer: asyncTasksReducer + }) }); + ASYNC_TASK_TOOL_NAMES = [ + "start_async_task", + "check_async_task", + "update_async_task", + "cancel_async_task", + "list_async_tasks" + ]; + TERMINAL_STATUSES = new Set([ + "cancelled", + "success", + "error", + "timeout", + "interrupted" + ]); + NAMESPACE_COMPONENT_RE = /^[A-Za-z0-9\-_.@+:~]+$/; + SUPPORTS_NOFOLLOW = fs$1.constants.O_NOFOLLOW !== undefined; + URL_COMMIT_SUFFIX_RE = /:([0-9a-f]{8,64})$/i; + FNMATCH_OPTIONS = { bash: true }; + LocalShellBackend = class LocalShellBackend2 extends FilesystemBackend { + #timeout; + #maxOutputBytes; + #env; + #sandboxId; + #initialized = false; + constructor(options = {}) { + const { rootDir, virtualMode = false, timeout = 120, maxOutputBytes = 1e5, env, inheritEnv = false } = options; + super({ + rootDir, + virtualMode, + maxFileSizeMb: 10 + }); + this.#timeout = timeout; + this.#maxOutputBytes = maxOutputBytes; + const bytes = new Uint8Array(4); + crypto.getRandomValues(bytes); + this.#sandboxId = `local-${[...bytes].map((b) => b.toString(16).padStart(2, "0")).join("")}`; + if (inheritEnv) { + this.#env = { ...process.env }; + if (env) + Object.assign(this.#env, env); + } else + this.#env = env ?? {}; + } + get id() { + return this.#sandboxId; + } + get isInitialized() { + return this.#initialized; + } + get isRunning() { + return this.#initialized; + } + async initialize() { + if (this.#initialized) + throw new SandboxError("Backend is already initialized. Each LocalShellBackend instance can only be initialized once.", "ALREADY_INITIALIZED"); + await fs.mkdir(this.cwd, { recursive: true }); + this.#initialized = true; + } + async close() { + this.#initialized = false; + } + async read(filePath, offset = 0, limit = 500) { + const result = await super.read(filePath, offset, limit); + if (result.error?.includes("ENOENT")) + return { error: `File '${filePath}' not found` }; + return result; + } + async edit(filePath, oldString, newString, replaceAll = false) { + const result = await super.edit(filePath, oldString, newString, replaceAll); + if (result.error?.includes("ENOENT")) + return { + ...result, + error: `Error: File '${filePath}' not found` + }; + return result; + } + async ls(dirPath) { + const result = await super.ls(dirPath); + if (result.error) + return result; + if (this.virtualMode) + return result; + const cwdPrefix = this.cwd.endsWith(path$1.sep) ? this.cwd : this.cwd + path$1.sep; + return { files: (result.files || []).map((info) => ({ + ...info, + path: info.path.startsWith(cwdPrefix) ? info.path.slice(cwdPrefix.length) : info.path + })) }; + } + async glob(pattern, searchPath = "/") { + if (pattern.startsWith("/")) + pattern = pattern.substring(1); + const resolvedSearchPath = searchPath === "/" || searchPath === "" ? this.cwd : this.virtualMode ? path$1.resolve(this.cwd, searchPath.replace(/^\//, "")) : path$1.resolve(this.cwd, searchPath); + try { + if (!(await fs.stat(resolvedSearchPath)).isDirectory()) + return { files: [] }; + } catch { + return { files: [] }; + } + const formatPath = (rel) => this.virtualMode ? `/${rel}` : rel; + const globOpts = { + cwd: resolvedSearchPath, + absolute: false, + dot: true + }; + const [fileMatches, dirMatches] = await Promise.all([import_fast_glob.default(pattern, { + ...globOpts, + onlyFiles: true + }), import_fast_glob.default(pattern, { + ...globOpts, + onlyDirectories: true + })]); + const statFile = async (match2) => { + try { + const entryStat = await fs.stat(path$1.join(resolvedSearchPath, match2)); + if (entryStat.isFile()) + return { + path: formatPath(match2), + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString() + }; + } catch {} + return null; + }; + const statDir = async (match2) => { + try { + const entryStat = await fs.stat(path$1.join(resolvedSearchPath, match2)); + if (entryStat.isDirectory()) + return { + path: formatPath(match2), + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString() + }; + } catch {} + return null; + }; + const [fileInfos, dirInfos] = await Promise.all([Promise.all(fileMatches.map(statFile)), Promise.all(dirMatches.map(statDir))]); + const results = [...fileInfos, ...dirInfos].filter((info) => info !== null); + results.sort((a, b) => a.path.localeCompare(b.path)); + return { files: results }; + } + async execute(command) { + if (!command || typeof command !== "string") + return { + output: "Error: Command must be a non-empty string.", + exitCode: 1, + truncated: false + }; + return new Promise((resolve2) => { + let stdout = ""; + let stderr = ""; + let timedOut = false; + const child = cp.spawn(command, { + shell: true, + env: this.#env, + cwd: this.cwd + }); + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGTERM"); + }, this.#timeout * 1000); + child.stdout.on("data", (data) => { + stdout += data.toString(); + }); + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + child.on("error", (err) => { + clearTimeout(timer); + resolve2({ + output: `Error executing command: ${err.message}`, + exitCode: 1, + truncated: false + }); + }); + child.on("close", (code, signal) => { + clearTimeout(timer); + if (timedOut || signal === "SIGTERM") { + resolve2({ + output: `Error: Command timed out after ${this.#timeout.toFixed(1)} seconds.`, + exitCode: 124, + truncated: false + }); + return; + } + const outputParts = []; + if (stdout) + outputParts.push(stdout); + if (stderr) { + const stderrLines = stderr.trim().split(` +`); + outputParts.push(...stderrLines.map((line) => `[stderr] ${line}`)); + } + let output = outputParts.length > 0 ? outputParts.join(` +`) : ""; + let truncated = false; + if (output.length > this.#maxOutputBytes) { + output = output.slice(0, this.#maxOutputBytes); + output += ` + +... Output truncated at ${this.#maxOutputBytes} bytes.`; + truncated = true; + } + const exitCode = code ?? 1; + if (exitCode !== 0) + output = `${output.trimEnd()} + +Exit code: ${exitCode}`; + resolve2({ + output, + exitCode, + truncated + }); + }); + }); + } + static async create(options = {}) { + const { initialFiles, ...backendOptions } = options; + const backend = new LocalShellBackend2(backendOptions); + await backend.initialize(); + if (initialFiles) { + const encoder2 = new TextEncoder; + const files = Object.entries(initialFiles).map(([filePath, content]) => [filePath, encoder2.encode(content)]); + await backend.uploadFiles(files); + } + return backend; + } + }; + LangSmithSandbox = class LangSmithSandbox2 extends BaseSandbox { + #sandbox; + #defaultTimeout; + #isRunning = true; + constructor(options) { + super(); + this.#sandbox = options.sandbox; + this.#defaultTimeout = options.defaultTimeout ?? 1800; + } + get isRunning() { + return this.#isRunning; + } + get id() { + return this.#sandbox.name; + } + async execute(command, options) { + const effectiveTimeout = options?.timeout !== undefined ? options.timeout : this.#defaultTimeout; + const result = await this.#sandbox.run(command, { timeout: effectiveTimeout }); + const out = result.stdout ?? ""; + return { + output: result.stderr ? out ? `${out} +${result.stderr}` : result.stderr : out, + exitCode: result.exit_code, + truncated: false + }; + } + async downloadFiles(paths) { + const responses = []; + for (const path3 of paths) + try { + const content = await this.#sandbox.read(path3); + responses.push({ + path: path3, + content, + error: null + }); + } catch (err) { + if (err instanceof LangSmithResourceNotFoundError) + responses.push({ + path: path3, + content: null, + error: "file_not_found" + }); + else if (err instanceof LangSmithSandboxError) { + const error90 = String(err.message).toLowerCase().includes("is a directory") ? "is_directory" : "file_not_found"; + responses.push({ + path: path3, + content: null, + error: error90 + }); + } else + responses.push({ + path: path3, + content: null, + error: "invalid_path" + }); + } + return responses; + } + async uploadFiles(files) { + const responses = []; + for (const [path3, content] of files) + try { + await this.#sandbox.write(path3, content); + responses.push({ + path: path3, + error: null + }); + } catch { + responses.push({ + path: path3, + error: "permission_denied" + }); + } + return responses; + } + async close() { + await this.#sandbox.delete(); + this.#isRunning = false; + } + async start(options = {}) { + await this.#sandbox.start(options); + this.#isRunning = true; + } + async stop() { + await this.#sandbox.stop(); + this.#isRunning = false; + } + async captureSnapshot(name, options = {}) { + return this.#sandbox.captureSnapshot(name, options); + } + static async create(options) { + const { templateName, apiKey = process.env.LANGSMITH_API_KEY, defaultTimeout, snapshotId, ...createSandboxOptions } = options; + if (snapshotId && templateName) + throw new Error("snapshotId and templateName are mutually exclusive. Pass only one creation source."); + if (!snapshotId && !templateName) + throw new Error("Either snapshotId or templateName is required. snapshotId is recommended — template-based creation is deprecated."); + const sandboxOptions = { ...createSandboxOptions }; + if (templateName) + sandboxOptions.snapshotName = templateName; + return new LangSmithSandbox2({ + sandbox: await new SandboxClient({ apiKey }).createSandbox(snapshotId, sandboxOptions), + defaultTimeout + }); + } + }; + CONFIGURATION_ERROR_SYMBOL = Symbol.for("deepagents.configuration_error"); + ConfigurationError = class ConfigurationError2 extends Error { + [CONFIGURATION_ERROR_SYMBOL] = true; + name = "ConfigurationError"; + constructor(message, code, cause) { + super(message); + this.code = code; + this.cause = cause; + Object.setPrototypeOf(this, ConfigurationError2.prototype); + } + static isInstance(error90) { + return typeof error90 === "object" && error90 !== null && error90[CONFIGURATION_ERROR_SYMBOL] === true; + } + }; + REQUIRED_MIDDLEWARE_NAMES = new Set(["FilesystemMiddleware", "SubAgentMiddleware"]); + EMPTY_HARNESS_PROFILE = createHarnessProfile(); + POISONED_KEYS = new Set([ + "__proto__", + "constructor", + "prototype" + ]); + generalPurposeSubagentConfigSchema = exports_external.object({ + enabled: exports_external.boolean().optional(), + description: exports_external.string().optional(), + systemPrompt: exports_external.string().optional() + }).strict(); + harnessProfileConfigSchema = exports_external.object({ + baseSystemPrompt: exports_external.string().optional(), + systemPromptSuffix: exports_external.string().optional(), + toolDescriptionOverrides: exports_external.record(exports_external.string(), exports_external.string()).optional(), + excludedTools: exports_external.array(exports_external.string()).optional(), + excludedMiddleware: exports_external.array(exports_external.string()).optional(), + generalPurposeSubagent: generalPurposeSubagentConfigSchema.optional() + }).strict(); + CODEX_MODEL_SPECS = [ + "openai:gpt-5.1-codex", + "openai:gpt-5.2-codex", + "openai:gpt-5.3-codex" + ]; + PROFILE_REGISTRY_KEY = Symbol.for("deepagents.harness-profiles.v1"); + BASE_AGENT_PROMPT = context` + You are a Deep Agent, an AI assistant that helps users accomplish tasks using tools. You respond with text and tool calls. The user can see your responses and tool outputs in real time. + + ## Core Behavior + + - Be concise and direct. Don't over-explain unless asked. + - NEVER add unnecessary preamble (\"Sure!\", \"Great question!\", \"I'll now...\"). + - Don't say \"I'll now do X\" — just do it. + - If the request is ambiguous, ask questions before acting. + - If asked how to approach something, explain first, then act. + + ## Professional Objectivity + + - Prioritize accuracy over validating the user's beliefs + - Disagree respectfully when the user is incorrect + - Avoid unnecessary superlatives, praise, or emotional validation + + ## Doing Tasks + + When the user asks you to do something: + + 1. **Understand first** — read relevant files, check existing patterns. Quick but thorough — gather enough evidence to start, then iterate. + 2. **Act** — implement the solution. Work quickly but accurately. + 3. **Verify** — check your work against what was asked, not against your own output. Your first attempt is rarely correct — iterate. + + Keep working until the task is fully complete. Don't stop partway and explain what you would do — just do it. Only yield back to the user when the task is done or you're genuinely blocked. + + **When things go wrong:** + - If something fails repeatedly, stop and analyze *why* — don't keep retrying the same approach. + - If you're blocked, tell the user what's wrong and ask for guidance. + + ## Progress Updates + + For longer tasks, provide brief progress updates at reasonable intervals — a concise sentence recapping what you've done and what's next. +`; + BUILTIN_TOOL_NAMES = new Set([ + ...FILESYSTEM_TOOL_NAMES, + ...ASYNC_TASK_TOOL_NAMES, + "task", + "write_todos" + ]); + AgentMemoryStateSchema = exports_external.object({ + userMemory: exports_external.string().optional(), + projectMemory: exports_external.string().optional() + }); + SKILL_NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/; + FRONTMATTER_PATTERN = /^---\s*\n([\s\S]*?)\n---\s*\n/; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/output_parsers.js +function extractToolCalls2(content) { + const toolCalls = []; + for (const block of content) + if (block.type === "tool_use") + toolCalls.push({ + name: block.name, + args: block.input, + id: block.id, + type: "tool_call" + }); + return toolCalls; +} +var AnthropicToolsOutputParser; +var init_output_parsers3 = __esm(() => { + init_types3(); + init_output_parsers(); + AnthropicToolsOutputParser = class extends BaseLLMOutputParser { + static lc_name() { + return "AnthropicToolsOutputParser"; + } + lc_namespace = [ + "langchain", + "anthropic", + "output_parsers" + ]; + returnId = false; + keyName; + returnSingle = false; + zodSchema; + serializableSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + this.zodSchema = params.zodSchema; + this.serializableSchema = params.serializableSchema; + } + async _validateResult(result) { + let parsedResult = result; + if (typeof result === "string") + try { + parsedResult = JSON.parse(result); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); + } + else + parsedResult = result; + if (this.serializableSchema !== undefined) { + const validated = await this.serializableSchema["~standard"].validate(parsedResult); + if (validated.issues) + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(parsedResult, null, 2)}". Error: ${JSON.stringify(validated.issues)}`, JSON.stringify(parsedResult, null, 2)); + return validated.value; + } + if (this.zodSchema === undefined) + return parsedResult; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); + if (zodParsedResult.success) + return zodParsedResult.data; + else + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); + } + async parseResult(generations) { + const tools = generations.flatMap((generation) => { + const { message } = generation; + if (!Array.isArray(message.content)) + return []; + return extractToolCalls2(message.content)[0]; + }); + if (tools[0] === undefined) + throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); + const [tool2] = tools; + return await this._validateResult(tool2.args); + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/tools.js +function handleToolChoice(toolChoice) { + if (!toolChoice) + return; + else if (toolChoice === "any" || toolChoice === "required") + return { type: "any" }; + else if (toolChoice === "auto") + return { type: "auto" }; + else if (toolChoice === "none") + return { type: "none" }; + else if (typeof toolChoice === "string") + return { + type: "tool", + name: toolChoice + }; + else + return toolChoice; +} +var AnthropicToolExtrasSchema, ANTHROPIC_TOOL_BETAS; +var init_tools5 = __esm(() => { + init_v43(); + AnthropicToolExtrasSchema = object2({ + cache_control: custom3().optional().nullable(), + defer_loading: boolean5().optional(), + input_examples: array2(unknown2()).optional(), + allowed_callers: array2(unknown2()).optional(), + strict: boolean5().optional() + }); + ANTHROPIC_TOOL_BETAS = { + tool_search_tool_regex_20251119: "advanced-tool-use-2025-11-20", + tool_search_tool_bm25_20251119: "advanced-tool-use-2025-11-20", + memory_20250818: "context-management-2025-06-27", + web_fetch_20250910: "web-fetch-2025-09-10", + code_execution_20250825: "code-execution-2025-08-25", + computer_20251124: "computer-use-2025-11-24", + computer_20250124: "computer-use-2025-01-24", + mcp_toolset: "mcp-client-2025-11-20" + }; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/content.js +function _isAnthropicThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; +} +function _isAnthropicRedactedThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; +} +function _isAnthropicCompactionBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "compaction"; +} +function _isAnthropicSearchResultBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; +} +function _isAnthropicImageBlockParam(block) { + if (typeof block !== "object" || block == null) + return false; + if (!("type" in block) || block.type !== "image") + return false; + if (!("source" in block) || typeof block.source !== "object" || block.source == null) + return false; + if (!("type" in block.source)) + return false; + if (block.source.type === "base64") { + if (!("media_type" in block.source)) + return false; + if (typeof block.source.media_type !== "string") + return false; + if (!("data" in block.source)) + return false; + if (typeof block.source.data !== "string") + return false; + return true; + } + if (block.source.type === "url") { + if (!("url" in block.source)) + return false; + if (typeof block.source.url !== "string") + return false; + return true; + } + return false; +} +var standardContentBlockConverter; +var init_content2 = __esm(() => { + init_messages(); + standardContentBlockConverter = { + providerName: "anthropic", + fromStandardTextBlock(block) { + return { + type: "text", + text: block.text, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + }, + fromStandardImageBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ + dataUrl: block.url, + asTypedArray: false + }); + if (data) + return { + type: "image", + source: { + type: "base64", + data: data.data, + media_type: data.mime_type + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else + return { + type: "image", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + } else if (block.source_type === "base64") + return { + type: "image", + source: { + type: "base64", + data: block.data, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else + throw new Error(`Unsupported image source type: ${block.source_type}`); + }, + fromStandardFileBlock(block) { + const mime_type = (block.mime_type ?? "").split(";")[0]; + if (block.source_type === "url") { + if (mime_type === "application/pdf" || mime_type === "") + return { + type: "document", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); + } else if (block.source_type === "text") + if (mime_type === "text/plain" || mime_type === "") + return { + type: "document", + source: { + type: "text", + data: block.text, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else + throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); + else if (block.source_type === "base64") + if (mime_type === "application/pdf" || mime_type === "") + return { + type: "document", + source: { + type: "base64", + data: block.data, + media_type: "application/pdf" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else if ([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ].includes(mime_type)) + return { + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: block.data, + media_type: mime_type + } + }] + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else + throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); + else + throw new Error(`Unsupported file source type: ${block.source_type}`); + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/index.js +var iife4 = (fn) => fn(); +var init_utils17 = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/standard.js +function _isStandardAnnotation(annotation) { + return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; +} +function _formatStandardCitations(annotations) { + function* iterateAnnotations() { + for (const annotation of annotations) + if (_isStandardAnnotation(annotation)) { + if (annotation.source === "char") + yield { + type: "char_location", + file_id: annotation.url ?? "", + start_char_index: annotation.startIndex ?? 0, + end_char_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "page") + yield { + type: "page_location", + file_id: annotation.url ?? "", + start_page_number: annotation.startIndex ?? 0, + end_page_number: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "block") + yield { + type: "content_block_location", + file_id: annotation.url ?? "", + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "url") + yield { + type: "web_search_result_location", + url: annotation.url ?? "", + title: annotation.title ?? null, + encrypted_index: String(annotation.startIndex ?? 0), + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "search") + yield { + type: "search_result_location", + title: annotation.title ?? null, + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + search_result_index: 0, + source: annotation.source ?? "", + cited_text: annotation.citedText ?? "" + }; + } + } + return Array.from(iterateAnnotations()); +} +function _formatBase64Data(data) { + if (typeof data === "string") + return data; + else + return _encodeUint8Array(data); +} +function _encodeUint8Array(data) { + const output = []; + for (let i = 0, { length } = data;i < length; i++) + output.push(String.fromCharCode(data[i])); + return btoa(output.join("")); +} +function _normalizeMimeType(mimeType) { + return (mimeType ?? "").split(";")[0].toLowerCase(); +} +function _extractMetadataValue(metadata, key) { + if (metadata !== undefined && metadata !== null && typeof metadata === "object" && key in metadata) + return metadata[key]; +} +function _applyDocumentMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== undefined) + block.cache_control = cacheControl; + const citations = _extractMetadataValue(metadata, "citations"); + if (citations !== undefined) + block.citations = citations; + const context2 = _extractMetadataValue(metadata, "context"); + if (context2 !== undefined) + block.context = context2; + const title = _extractMetadataValue(metadata, "title"); + if (title !== undefined) + block.title = title; + return block; +} +function _applyImageMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== undefined) + block.cache_control = cacheControl; + return block; +} +function _hasAllowedImageMimeType(mimeType) { + return new Set([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ]).has(mimeType); +} +function _formatStandardContent(message) { + const result = []; + const responseMetadata = message.response_metadata; + const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; + for (const block of message.contentBlocks) + if (block.type === "text") + if (block.annotations) + result.push({ + type: "text", + text: block.text, + citations: _formatStandardCitations(block.annotations) + }); + else + result.push({ + type: "text", + text: block.text + }); + else if (block.type === "tool_call") + result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name, + input: block.args + }); + else if (block.type === "tool_call_chunk") { + const input = iife4(() => { + if (typeof block.args !== "string") + return block.args; + try { + return JSON.parse(block.args); + } catch { + return {}; + } + }); + result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name ?? "", + input + }); + } else if (block.type === "reasoning" && isAnthropicMessage) + result.push({ + type: "thinking", + thinking: block.reasoning, + signature: String(block.signature) + }); + else if (block.type === "server_tool_call" && isAnthropicMessage) { + if (block.name === "web_search") + result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + else if (block.name === "code_execution") + result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { + if (block.name === "web_search" && Array.isArray(block.output.urls)) { + const content = block.output.urls.map((url3) => ({ + type: "web_search_result", + title: "", + encrypted_content: "", + url: url3 + })); + result.push({ + type: "web_search_tool_result", + tool_use_id: block.toolCallId ?? "", + content + }); + } else if (block.name === "code_execution") + result.push({ + type: "code_execution_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + else if (block.name === "mcp_tool_result") + result.push({ + type: "mcp_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + } else if (block.type === "audio") + throw new Error("Anthropic does not support audio content blocks."); + else if (block.type === "file") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "application/pdf" || mimeType === "") { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "" || mimeType === "application/pdf") + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: "application/pdf" + } + }, metadata)); + else if (mimeType === "text/plain") + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, metadata)); + else if (_hasAllowedImageMimeType(mimeType)) + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }] + } + }, metadata)); + else + throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); + continue; + } + throw new Error("File content block must include a fileId, url, or data property."); + } else if (block.type === "image") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; + if (_hasAllowedImageMimeType(mimeType)) + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }, metadata)); + continue; + } + throw new Error("Image content block must include a fileId, url, or data property."); + } else if (block.type === "video") {} else if (block.type === "text-plain") { + if (block.data) + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, block.metadata)); + } else if (block.type === "non_standard" && isAnthropicMessage) + result.push(block.value); + return result; +} +var init_standard = __esm(() => { + init_utils17(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/message_inputs.js +function _formatImage(imageUrl) { + const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); + if (parsed) + return { + type: "base64", + media_type: parsed.mime_type, + data: parsed.data + }; + let parsedUrl; + try { + parsedUrl = new URL(imageUrl); + } catch { + throw new Error([ + `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join(` + +`)); + } + if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") + return { + type: "url", + url: imageUrl + }; + throw new Error([ + `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join(` + +`)); +} +function _ensureMessageContents(messages) { + const updatedMsgs = []; + for (const message of messages) + if (message._getType() === "tool") + if (typeof message.content === "string") { + const previousMessage = updatedMsgs[updatedMsgs.length - 1]; + if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") + previousMessage.content.push({ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }); + else + updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }] })); + } else + updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + ...message.content != null ? { content: _formatContent(message) } : {}, + tool_use_id: message.tool_call_id + }] })); + else + updatedMsgs.push(message); + return updatedMsgs; +} +function _convertLangChainToolCallToAnthropic(toolCall) { + if (toolCall.id === undefined) + throw new Error(`Anthropic requires all tool calls to have an "id".`); + return { + type: "tool_use", + id: toolCall.id, + name: toolCall.name, + input: toolCall.args + }; +} +function* _formatContentBlocks(content, toolCalls) { + const toolTypes = [ + "bash_code_execution_tool_result", + "input_json_delta", + "server_tool_use", + "text_editor_code_execution_tool_result", + "tool_result", + "tool_use", + "web_search_result", + "web_search_tool_result" + ]; + const textTypes = ["text", "text_delta"]; + for (const contentPart of content) { + if (isDataContentBlock(contentPart)) + yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); + const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : undefined; + if (contentPart.type === "image_url") { + let source; + if (typeof contentPart.image_url === "string") + source = _formatImage(contentPart.image_url); + else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") + source = _formatImage(contentPart.image_url.url); + if (source) + yield { + type: "image", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (_isAnthropicImageBlockParam(contentPart)) + yield contentPart; + else if (contentPart.type === "image") { + let source; + if ("url" in contentPart && typeof contentPart.url === "string") + source = _formatImage(contentPart.url); + else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) + source = { + type: "base64", + media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "image/jpeg", + data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") + }; + else if ("fileId" in contentPart && typeof contentPart.fileId === "string") + source = { + type: "file", + file_id: contentPart.fileId + }; + if (source) + yield { + type: "image", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "file") { + let source; + if ("url" in contentPart && typeof contentPart.url === "string") + source = { + type: "url", + url: contentPart.url + }; + else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) + source = { + type: "base64", + media_type: "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "application/pdf", + data: typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64") + }; + else if ("fileId" in contentPart && typeof contentPart.fileId === "string") + source = { + type: "file", + file_id: contentPart.fileId + }; + if (source) + yield { + type: "document", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "document") + yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicThinkingBlock(contentPart)) + yield { + type: "thinking", + thinking: contentPart.thinking, + signature: contentPart.signature, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicRedactedThinkingBlock(contentPart)) + yield { + type: "redacted_thinking", + data: contentPart.data, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicCompactionBlock(contentPart)) + yield { + type: "compaction", + content: contentPart.content, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicSearchResultBlock(contentPart)) + yield { + type: "search_result", + title: contentPart.title, + source: contentPart.source, + ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, + content: contentPart.content + }; + else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) + yield { + type: "text", + text: contentPart.text, + ...cacheControl ? { cache_control: cacheControl } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} + }; + else if (toolTypes.find((t) => t === contentPart.type)) { + const contentPartCopy = { ...contentPart }; + if (contentPartCopy.type === "input_json_delta") + continue; + if (contentPartCopy.type === "tool_use" && typeof contentPartCopy.input === "string") { + const matchingToolCall = toolCalls?.find((tc) => tc.id === contentPartCopy.id); + if (matchingToolCall) + contentPartCopy.input = matchingToolCall.args; + else + contentPartCopy.input = content.filter((nestedContentPart) => nestedContentPart.index === contentPartCopy.index && nestedContentPart.type === "input_json_delta" && typeof nestedContentPart.input === "string").reduce((accumulator, nestedContentPart) => accumulator + nestedContentPart.input, contentPartCopy.input); + } + if ("index" in contentPartCopy) + delete contentPartCopy.index; + if ("input" in contentPartCopy) { + if (typeof contentPartCopy.input === "string") + try { + contentPartCopy.input = JSON.parse(contentPartCopy.input); + } catch { + contentPartCopy.input = {}; + } + } + yield { + ...contentPartCopy, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "container_upload") + yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } +} +function _formatContent(message, toolCalls) { + const { content } = message; + if (typeof content === "string") + return content; + else + return Array.from(_formatContentBlocks(content, toolCalls)); +} +function _convertMessagesToAnthropicPayload(messages) { + const mergedMessages = _ensureMessageContents(messages); + let system; + if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") + system = messages[0].content; + return { + messages: mergeMessages((system !== undefined ? mergedMessages.slice(1) : mergedMessages).map((message) => { + let role; + if (message._getType() === "human") + role = "user"; + else if (message._getType() === "ai") + role = "assistant"; + else if (message._getType() === "tool") + role = "user"; + else if (message._getType() === "system") + throw new Error("System messages are only permitted as the first passed message."); + else + throw new Error(`Message type "${message.type}" is not supported.`); + if (AIMessage.isInstance(message) && message.response_metadata?.output_version === "v1") + return { + role, + content: _formatStandardContent(message) + }; + if (AIMessage.isInstance(message) && !!message.tool_calls?.length) + if (typeof message.content === "string") + if (message.content === "") + return { + role, + content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) + }; + else + return { + role, + content: [{ + type: "text", + text: message.content + }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] + }; + else { + const { content } = message; + const formattedContent = _formatContent(message, message.tool_calls); + const formattedContentArr = Array.isArray(formattedContent) ? formattedContent : [{ + type: "text", + text: formattedContent + }]; + const missingToolCalls = message.tool_calls.filter((toolCall) => !content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); + return { + role, + content: [...formattedContentArr, ...missingToolCalls.map(_convertLangChainToolCallToAnthropic)] + }; + } + else + return { + role, + content: _formatContent(message, AIMessage.isInstance(message) ? message.tool_calls : undefined) + }; + })), + system + }; +} +function mergeMessages(messages) { + if (!messages || messages.length <= 1) + return messages; + const result = []; + let currentMessage = messages[0]; + const normalizeContent = (content) => { + if (typeof content === "string") + return [{ + type: "text", + text: content + }]; + return content; + }; + const isToolResultMessage = (msg) => { + if (msg.role !== "user") + return false; + if (typeof msg.content === "string") + return false; + return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); + }; + for (let i = 1;i < messages.length; i += 1) { + const nextMessage = messages[i]; + if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) + currentMessage = { + ...currentMessage, + content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] + }; + else { + result.push(currentMessage); + currentMessage = nextMessage; + } + } + result.push(currentMessage); + return result; +} +var init_message_inputs = __esm(() => { + init_content2(); + init_standard(); + init_messages(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/params.js +function isThinkingEnabled(thinking) { + return thinking.type === "enabled" || thinking.type === "adaptive"; +} +function isOpus47Model(model) { + return model?.startsWith("claude-opus-4-7") ?? false; +} +function getTaskBudgetBetas(model, outputConfig) { + const hasTaskBudget = outputConfig && typeof outputConfig === "object" && "task_budget" in outputConfig && outputConfig.task_budget != null; + return isOpus47Model(model) && hasTaskBudget ? ["task-budgets-2026-03-13"] : []; +} +function validateInvocationParamCompatibility(fields) { + const { model, thinking, topK, topP, temperature } = fields; + const opus47 = isOpus47Model(model); + if (opus47 && thinking.type === "enabled") + throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead'); + if (opus47 && typeof thinking === "object" && thinking != null && "budget_tokens" in thinking) + throw new Error("thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead"); + if (opus47) { + if (topK !== undefined) + throw new Error("topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead"); + if (topP !== undefined && topP !== 1) + throw new Error("topP is not supported for claude-opus-4-7 when set to non-default values"); + if (temperature !== undefined && temperature !== 1) + throw new Error("temperature is not supported for claude-opus-4-7 when set to non-default values"); + } + if (isThinkingEnabled(thinking)) { + if (topK !== undefined) + throw new Error("topK is not supported when thinking is enabled"); + if (topP !== undefined) + throw new Error("topP is not supported when thinking is enabled"); + if (temperature !== undefined && temperature !== 1) + throw new Error("temperature is not supported when thinking is enabled"); + } +} +function getSamplingParams(fields) { + const { model, thinking, topK, topP, temperature } = fields; + const output = {}; + if (isThinkingEnabled(thinking) || isOpus47Model(model)) + return output; + if (temperature !== undefined) + output.temperature = temperature; + if (topK !== undefined) + output.top_k = topK; + if (topP !== undefined) + output.top_p = topP; + return output; +} +var init_params = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/message_outputs.js +function _makeMessageChunkFromAnthropicEvent(data, fields) { + const response_metadata = { model_provider: "anthropic" }; + if (data.type === "message_start") { + const { content, usage, ...additionalKwargs } = data.message; + const filteredAdditionalKwargs = {}; + for (const [key, value] of Object.entries(additionalKwargs)) + if (value !== undefined && value !== null) + filteredAdditionalKwargs[key] = value; + const { input_tokens, output_tokens, ...rest } = usage ?? {}; + const usageMetadata = buildUsageMetadata(usage); + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + additional_kwargs: filteredAdditionalKwargs, + usage_metadata: fields.streamUsage ? usageMetadata : undefined, + response_metadata: { + ...response_metadata, + usage: { ...rest } + }, + id: data.message.id + }) }; + } else if (data.type === "message_delta") { + const usageMetadata = { + input_tokens: 0, + output_tokens: data.usage.output_tokens, + total_tokens: data.usage.output_tokens + }; + const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : undefined; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + response_metadata: responseMetadata, + additional_kwargs: { ...data.delta }, + usage_metadata: fields.streamUsage ? usageMetadata : undefined + }) }; + } else if (data.type === "content_block_start" && [ + "tool_use", + "document", + "server_tool_use", + "web_search_tool_result" + ].includes(data.content_block.type)) { + const contentBlock = data.content_block; + let toolCallChunks; + if (contentBlock.type === "tool_use") + toolCallChunks = [{ + id: contentBlock.id, + index: data.index, + name: contentBlock.name, + args: "" + }]; + else + toolCallChunks = []; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block, + input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : undefined + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: toolCallChunks + }) }; + } else if (data.type === "content_block_delta" && [ + "text_delta", + "citations_delta", + "thinking_delta", + "signature_delta" + ].includes(data.delta.type)) + if (fields.coerceContentToString && "text" in data.delta) + return { chunk: new AIMessageChunk({ content: data.delta.text }) }; + else { + const contentBlock = data.delta; + if ("citation" in contentBlock) { + contentBlock.citations = [contentBlock.citation]; + delete contentBlock.citation; + } + if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") + return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "thinking" + }], + response_metadata + }) }; + return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "text" + }], + response_metadata + }) }; + } + else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + input: data.delta.partial_json, + type: data.delta.type + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: [{ + index: data.index, + args: data.delta.partial_json + }] + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "text") { + const content = data.content_block?.text; + if (content !== undefined) + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata, + additional_kwargs: {} + }) }; + } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "thinking") { + const content = data.content_block.thinking; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + } else if (data.type === "content_block_start" && _isAnthropicCompactionBlock(data.content_block)) + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + else if (data.type === "content_block_delta" && data.delta.type === "compaction_delta") + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.delta, + type: "compaction" + }], + response_metadata + }) }; + return null; +} +function anthropicResponseToChatMessages(messages, additionalKwargs) { + const response_metadata = { + ...additionalKwargs, + model_provider: "anthropic" + }; + const usage = additionalKwargs.usage; + const usageMetadata = usage != null ? buildUsageMetadata(usage) : undefined; + if (messages.length === 1 && messages[0].type === "text") + return [{ + text: messages[0].text, + message: new AIMessage({ + content: messages[0].text, + additional_kwargs: additionalKwargs, + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; + else + return [{ + text: "", + message: new AIMessage({ + content: messages, + additional_kwargs: additionalKwargs, + tool_calls: extractToolCalls2(messages), + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; +} +function buildUsageMetadata(usage) { + const cacheCreationInputTokens = usage.cache_creation_input_tokens ?? 0; + const cacheReadInputTokens = usage.cache_read_input_tokens ?? 0; + const totalInputTokens = usage.input_tokens + cacheCreationInputTokens + cacheReadInputTokens; + return { + input_tokens: totalInputTokens, + output_tokens: usage.output_tokens, + total_tokens: totalInputTokens + usage.output_tokens, + input_token_details: { + cache_creation: cacheCreationInputTokens, + cache_read: cacheReadInputTokens + } + }; +} +var init_message_outputs = __esm(() => { + init_output_parsers3(); + init_content2(); + init_messages(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/errors.js +function addLangChainErrorFields2(error90, lc_error_code) { + error90.lc_error_code = lc_error_code; + error90.message = `${error90.message} + +Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/ +`; + return error90; +} +function wrapAnthropicClientError(e) { + let error90; + if (e.status === 400 && typeof e.message === "string" && e.message.includes("prompt is too long")) + error90 = addLangChainErrorFields2(ContextOverflowError.fromError(e), "CONTEXT_OVERFLOW"); + else if (e.status === 400 && e.message.includes("tool")) + error90 = addLangChainErrorFields2(e, "INVALID_TOOL_RESULTS"); + else if (e.status === 401) + error90 = addLangChainErrorFields2(e, "MODEL_AUTHENTICATION"); + else if (e.status === 404) + error90 = addLangChainErrorFields2(e, "MODEL_NOT_FOUND"); + else if (e.status === 429) + error90 = addLangChainErrorFields2(e, "MODEL_RATE_LIMIT"); + else + error90 = e; + return error90; +} +var init_errors13 = __esm(() => { + init_errors3(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/profiles.js +var PROFILES; +var init_profiles2 = __esm(() => { + PROFILES = { + "claude-3-sonnet-20240229": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-5-20251101": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-opus-20240229": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-haiku-20241022": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-sonnet-20241022": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-6": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-0": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-7": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-haiku-20240307": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5-20250929": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-haiku-latest": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-0": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-sonnet-20240620": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-5": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1-20250805": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5-20251001": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-20250514": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-6": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-7-sonnet-20250219": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-20250514": { + maxInputTokens: 200000, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32000, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + } + }; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/stream_events.js +async function* convertAnthropicStream(source, options = {}) { + const shouldStreamUsage = options.streamUsage ?? true; + const blockAccumulators = /* @__PURE__ */ new Map; + let usageSnapshot; + let stopReason = null; + for await (const data of source) + switch (data.type) { + case "message_start": { + const { usage, id, model } = data.message; + if (usage && shouldStreamUsage) + usageSnapshot = buildUsageSnapshot(usage); + yield { + event: "message-start", + id, + ...usageSnapshot ? { usage: usageSnapshot } : {} + }; + yield { + event: "provider", + provider: "anthropic", + name: "message_start", + payload: { + model, + id + } + }; + break; + } + case "message_delta": + stopReason = data.delta.stop_reason; + if (shouldStreamUsage && data.usage) { + if (!usageSnapshot) + usageSnapshot = { + input_tokens: 0, + output_tokens: data.usage.output_tokens, + total_tokens: data.usage.output_tokens + }; + else + usageSnapshot = { + ...usageSnapshot, + output_tokens: usageSnapshot.output_tokens + data.usage.output_tokens, + total_tokens: usageSnapshot.input_tokens + usageSnapshot.output_tokens + data.usage.output_tokens + }; + yield { + event: "usage", + usage: usageSnapshot + }; + } + if ("context_management" in data.delta && data.delta.context_management) + yield { + event: "provider", + provider: "anthropic", + name: "context_management", + payload: data.delta.context_management + }; + break; + case "message_stop": + yield { + event: "message-finish", + reason: mapStopReason(stopReason), + ...usageSnapshot ? { usage: usageSnapshot } : {}, + metadata: { model_provider: "anthropic" } + }; + break; + case "content_block_start": { + const { index: index2, content_block } = data; + const mapped = mapBlockToContentBlock(content_block, index2); + blockAccumulators.set(index2, { ...mapped }); + yield { + event: "content-block-start", + index: index2, + content: mapped + }; + break; + } + case "content_block_delta": { + const { index: index2, delta } = data; + const acc = blockAccumulators.get(index2); + if (!acc) + break; + const { contentDelta, accumulated } = applyAnthropicDelta(acc, delta); + blockAccumulators.set(index2, accumulated); + yield { + event: "content-block-delta", + index: index2, + delta: contentDelta + }; + break; + } + case "content_block_stop": { + const { index: index2 } = data; + const acc = blockAccumulators.get(index2); + if (!acc) + break; + yield { + event: "content-block-finish", + index: index2, + content: finalizeBlock(acc) + }; + blockAccumulators.delete(index2); + break; + } + default: + yield { + event: "provider", + provider: "anthropic", + name: data.type, + payload: data + }; + break; + } +} +function mapStopReason(stopReason) { + switch (stopReason) { + case "end_turn": + case "stop_sequence": + return "stop"; + case "tool_use": + return "tool_use"; + case "max_tokens": + return "length"; + default: + return "stop"; + } +} +function buildUsageSnapshot(usage) { + const cacheCreation = usage.cache_creation_input_tokens ?? 0; + const cacheRead = usage.cache_read_input_tokens ?? 0; + const totalInput = usage.input_tokens + cacheCreation + cacheRead; + return { + input_tokens: totalInput, + output_tokens: usage.output_tokens, + total_tokens: totalInput + usage.output_tokens, + input_token_details: { + cache_creation: cacheCreation, + cache_read: cacheRead + } + }; +} +function mapBlockToContentBlock(block, index2) { + switch (block.type) { + case "text": + return { + type: "text", + text: block.text ?? "", + index: index2 + }; + case "thinking": + return { + type: "reasoning", + reasoning: block.thinking ?? "", + index: index2 + }; + case "redacted_thinking": + return { + type: "non_standard", + value: { ...block }, + index: index2 + }; + case "tool_use": + return { + type: "tool_call_chunk", + id: block.id, + name: block.name, + args: "", + index: index2 + }; + case "server_tool_use": + return { + type: "server_tool_call_chunk", + id: block.id, + name: block.name, + args: "", + index: index2 + }; + default: + return { + type: "non_standard", + value: { ...block }, + index: index2 + }; + } +} +function applyAnthropicDelta(accumulated, delta) { + switch (delta.type) { + case "text_delta": + return { + contentDelta: { + type: "text-delta", + text: delta.text + }, + accumulated: { + ...accumulated, + text: (accumulated.text ?? "") + delta.text + } + }; + case "thinking_delta": + return { + contentDelta: { + type: "reasoning-delta", + reasoning: delta.thinking + }, + accumulated: { + ...accumulated, + reasoning: (accumulated.reasoning ?? "") + delta.thinking + } + }; + case "input_json_delta": { + const newArgs = (accumulated.args ?? "") + delta.partial_json; + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + args: newArgs + } + }, + accumulated: { + ...accumulated, + args: newArgs + } + }; + } + case "citations_delta": { + const annotations = [...accumulated.annotations ?? [], delta.citation]; + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + annotations + } + }, + accumulated: { + ...accumulated, + annotations + } + }; + } + case "signature_delta": + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + signature: delta.signature + } + }, + accumulated: { + ...accumulated, + signature: delta.signature + } + }; + case "compaction_delta": + return { + contentDelta: { + type: "block-delta", + fields: { + type: "non_standard", + value: { + ...accumulated.value ?? {}, + compaction: delta + } + } + }, + accumulated: { + ...accumulated, + value: { + ...accumulated.value ?? {}, + compaction: delta + } + } + }; + default: + return { + contentDelta: { + type: "block-delta", + fields: { + type: accumulated.type, + ...delta + } + }, + accumulated + }; + } +} +function finalizeBlock(accumulated) { + if (accumulated.type === "tool_call_chunk" || accumulated.type === "server_tool_call_chunk") { + const finalType = accumulated.type === "tool_call_chunk" ? "tool_call" : "server_tool_call"; + let parsedArgs; + try { + parsedArgs = JSON.parse(accumulated.args || "{}"); + } catch { + return { + type: "invalid_tool_call", + id: accumulated.id, + name: accumulated.name, + args: accumulated.args, + error: "Failed to parse tool call arguments as JSON" + }; + } + return { + type: finalType, + id: accumulated.id, + name: accumulated.name, + args: parsedArgs + }; + } + const { index: _index, ...rest } = accumulated; + return rest; +} +var init_stream_events = () => {}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f3) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f3) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f3) { + if (kind === "a" && !f3) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver); +} +var init_tslib = () => {}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +var uuid43 = function() { + const { crypto: crypto3 } = globalThis; + if (crypto3?.randomUUID) { + uuid43 = crypto3.randomUUID.bind(crypto3); + return crypto3.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto3 ? () => crypto3.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16)); +}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error90 = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error90.stack = err.stack; + if (err.cause && !error90.cause) + error90.cause = err.cause; + if (err.name) + error90.name = err.name; + return error90; + } + } catch {} + try { + return new Error(JSON.stringify(err)); + } catch {} + } + return new Error(err); +}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/error.mjs +var AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError; +var init_error5 = __esm(() => { + AnthropicError = class AnthropicError extends Error { + }; + APIError = class APIError extends AnthropicError { + constructor(status, error90, message, headers, type) { + super(`${APIError.makeMessage(status, error90, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get("request-id"); + this.error = error90; + this.type = type ?? null; + } + static makeMessage(status, error90, message) { + const msg = error90?.message ? typeof error90.message === "string" ? error90.message : JSON.stringify(error90.message) : error90 ? JSON.stringify(error90) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error90 = errorResponse; + const type = error90?.["error"]?.["type"]; + if (status === 400) { + return new BadRequestError(status, error90, message, headers, type); + } + if (status === 401) { + return new AuthenticationError(status, error90, message, headers, type); + } + if (status === 403) { + return new PermissionDeniedError(status, error90, message, headers, type); + } + if (status === 404) { + return new NotFoundError(status, error90, message, headers, type); + } + if (status === 409) { + return new ConflictError(status, error90, message, headers, type); + } + if (status === 422) { + return new UnprocessableEntityError(status, error90, message, headers, type); + } + if (status === 429) { + return new RateLimitError(status, error90, message, headers, type); + } + if (status >= 500) { + return new InternalServerError(status, error90, message, headers, type); + } + return new APIError(status, error90, message, headers, type); + } + }; + APIUserAbortError = class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || "Request was aborted.", undefined); + } + }; + APIConnectionError = class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || "Connection error.", undefined); + if (cause) + this.cause = cause; + } + }; + APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } + }; + BadRequestError = class BadRequestError extends APIError { + }; + AuthenticationError = class AuthenticationError extends APIError { + }; + PermissionDeniedError = class PermissionDeniedError extends APIError { + }; + NotFoundError = class NotFoundError extends APIError { + }; + ConflictError = class ConflictError extends APIError { + }; + UnprocessableEntityError = class UnprocessableEntityError extends APIError { + }; + RateLimitError = class RateLimitError extends APIError { + }; + InternalServerError = class InternalServerError extends APIError { + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +function maybeObj(x) { + if (typeof x !== "object") { + return {}; + } + return x ?? {}; +} +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var startsWithSchemeRegexp, isAbsoluteURL = (url3) => { + return startsWithSchemeRegexp.test(url3); +}, isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val)), isReadonlyArray, validatePositiveInteger = (name, n4) => { + if (typeof n4 !== "number" || !Number.isInteger(n4)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n4 < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n4; +}, safeJSON = (text) => { + try { + return JSON.parse(text); + } catch (err) { + return; + } +}, pop = (obj, key) => { + const value = obj[key]; + delete obj[key]; + return value; +}; +var init_values6 = __esm(() => { + init_error5(); + startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; + isReadonlyArray = isArray2; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +var sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/version.mjs +var VERSION = "0.95.2"; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match2 = pattern.exec(navigator.userAgent); + if (match2) { + const major = match2[1] || 0; + const minor = match2[2] || 0; + const patch = match2[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var isRunningInBrowser = () => { + return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined"; +}, getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; +}, normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; +}, normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; +}, _platformHeaders, getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); +}; +var init_detect_platform = () => {}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream2 = globalThis.ReadableStream; + if (typeof ReadableStream2 === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream2(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() {}, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +function ReadableStreamToAsyncIterable(stream2) { + if (stream2[Symbol.asyncIterator]) + return stream2; + const reader = stream2.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); + return result; + } catch (e) { + reader.releaseLock(); + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +async function CancelReadableStream(stream2) { + if (stream2 === null || typeof stream2 !== "object") + return; + if (stream2[Symbol.asyncIterator]) { + await stream2[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream2.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/request-options.mjs +var FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; +}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs +var default_format = "RFC3986", default_formatter = (v) => String(v), formatters, RFC1738 = "RFC1738"; +var init_formats = __esm(() => { + formatters = { + RFC1738: (v) => String(v).replace(/%20/g, "+"), + RFC3986: default_formatter + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val, fn) { + if (isArray2(val)) { + const mapped = []; + for (let i = 0;i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +} +var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)), hex_table, limit = 1024, encode3 = (str, _defaultEncoder, charset, _kind, format3) => { + if (str.length === 0) { + return str; + } + let string7 = str; + if (typeof str === "symbol") { + string7 = Symbol.prototype.toString.call(str); + } else if (typeof str !== "string") { + string7 = String(str); + } + if (charset === "iso-8859-1") { + return escape(string7).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j = 0;j < string7.length; j += limit) { + const segment = string7.length >= limit ? string7.slice(j, j + limit) : string7; + const arr3 = []; + for (let i = 0;i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format3 === RFC1738 && (c === 40 || c === 41)) { + arr3[arr3.length] = segment.charAt(i); + continue; + } + if (c < 128) { + arr3[arr3.length] = hex_table[c]; + continue; + } + if (c < 2048) { + arr3[arr3.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; + continue; + } + if (c < 55296 || c >= 57344) { + arr3[arr3.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + continue; + } + i += 1; + c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023); + arr3[arr3.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; + } + out += arr3.join(""); + } + return out; +}; +var init_utils18 = __esm(() => { + init_formats(); + init_values6(); + hex_table = /* @__PURE__ */ (() => { + const array3 = []; + for (let i = 0;i < 256; ++i) { + array3.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); + } + return array3; + })(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs +function is_non_nullish_primitive(v) { + return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint"; +} +function inner_stringify(object3, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder2, filter, sort, allowDots, serializeDate, format3, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object3; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== undefined && !find_flag) { + const pos = tmp_sc.get(object3); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter === "function") { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder2 && !encodeValuesOnly ? encoder2(prefix, defaults.encoder, charset, "key", format3) : prefix; + } + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder2) { + const key_value = encodeValuesOnly ? prefix : encoder2(prefix, defaults.encoder, charset, "key", format3); + return [ + formatter?.(key_value) + "=" + formatter?.(encoder2(obj, defaults.encoder, charset, "value", format3)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === "undefined") { + return values; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder2) { + obj = maybe_map(obj, encoder2); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : undefined }]; + } else if (isArray2(filter)) { + obj_keys = filter; + } else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j = 0;j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object3, step); + const valueSideChannel = new WeakMap; + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder2, filter, sort, allowDots, serializeDate, format3, formatter, encodeValuesOnly, charset, valueSideChannel)); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format3 = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format3 = opts.format; + } + const formatter = formatters[format3]; + let filter = defaults.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter, + format: format3, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify5(object3, opts = {}) { + let obj = object3; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === "function") { + filter = options.filter; + obj = filter("", obj); + } else if (isArray2(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = new WeakMap; + for (let i = 0;i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify(obj[key], key, generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} +var array_prefix_generators, push_to_array = function(arr3, value_or_array) { + Array.prototype.push.apply(arr3, isArray2(value_or_array) ? value_or_array : [value_or_array]); +}, toISOString, defaults, sentinel; +var init_stringify4 = __esm(() => { + init_utils18(); + init_formats(); + init_values6(); + array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } + }; + defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode3, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + indices: false, + serializeDate(date10) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date10); + }, + skipNulls: false, + strictNullHandling: false + }; + sentinel = {}; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs +function stringifyQuery(query3) { + return stringify5(query3, { arrayFormat: "brackets" }); +} +var init_query = __esm(() => { + init_stringify4(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs +function requireSecureTokenEndpoint(baseURL) { + if (!baseURL) + return; + let u; + try { + u = new URL(baseURL); + } catch (err) { + throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`); + } + if (u.protocol === "https:") + return; + const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1" || host === "::1")) { + return; + } + throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`); +} +async function parseTokenResponse(resp, requestId) { + const text = await readLimitedText(resp); + let data; + try { + data = JSON.parse(text); + } catch { + throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId); + } + if (!data.access_token) { + throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + } + if (data.token_type && data.token_type.toLowerCase() !== "bearer") { + throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId); + } + return data; +} +function redactSensitive(body) { + if (body == null) + return body; + if (typeof body === "string") { + let parsed; + try { + parsed = JSON.parse(body); + } catch { + if (body.length <= MAX_ERROR_BODY_CHARS) + return body; + return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`; + } + return JSON.stringify(redactSensitive(parsed)); + } + if (typeof body === "object" && !Array.isArray(body)) { + const out = {}; + for (const [k, v] of Object.entries(body)) { + if (SAFE_ERROR_KEYS.has(k)) + out[k] = v; + } + return out; + } + return null; +} +async function checkCredentialsFileSafety(path3, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) { + if (typeof process === "undefined" || process.platform === "win32") + return; + const fs2 = await import("node:fs"); + let resolved = path3; + let st; + try { + resolved = await fs2.promises.realpath(path3); + st = await fs2.promises.stat(resolved); + } catch { + return; + } + const mode = st.mode & 511; + if (mode & 18) { + throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`); + } + if (mode & 36) { + throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); run \`chmod 600 ${resolved}\` before retrying.`); + } + if (typeof process.getuid === "function" && st.uid !== process.getuid()) { + onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); verify this is intentional.`); + } +} +async function writeCredentialsFileAtomic(targetPath, data) { + const fs2 = await import("node:fs"); + const path3 = await import("node:path"); + const dir = path3.dirname(targetPath); + await fs2.promises.mkdir(dir, { recursive: true, mode: 448 }); + const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + try { + const fh = await fs2.promises.open(tmpPath, "w", 384); + try { + await fh.writeFile(JSON.stringify(data, null, 2)); + await fh.sync(); + } finally { + await fh.close(); + } + await fs2.promises.rename(tmpPath, targetPath); + } catch (err) { + await fs2.promises.unlink(tmpPath).catch(() => {}); + throw err; + } + try { + const dirFh = await fs2.promises.open(dir, "r"); + try { + await dirFh.sync(); + } finally { + await dirFh.close(); + } + } catch {} +} +async function readLimitedText(resp) { + if (!resp.body) { + return ""; + } + const reader = resp.body.getReader(); + const chunks = []; + let received = 0; + for (;; ) { + const { done, value } = await reader.read(); + if (done) + break; + if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) { + const remaining = MAX_TOKEN_RESPONSE_BYTES - received; + if (remaining > 0) + chunks.push(value.subarray(0, remaining)); + await reader.cancel(); + break; + } + chunks.push(value); + received += value.length; + } + let merged; + if (chunks.length === 1) { + merged = chunks[0]; + } else { + merged = new Uint8Array(chunks.reduce((n4, c) => n4 + c.length, 0)); + let offset = 0; + for (const c of chunks) { + merged.set(c, offset); + offset += c.length; + } + } + return new TextDecoder("utf-8").decode(merged); +} +var GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer", GRANT_TYPE_REFRESH_TOKEN = "refresh_token", TOKEN_ENDPOINT = "/v1/oauth/token", OAUTH_API_BETA_HEADER = "oauth-2025-04-20", FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01", ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120, MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30, ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5, MAX_TOKEN_RESPONSE_BYTES, MAX_ERROR_BODY_CHARS = 2000, SAFE_ERROR_KEYS, WorkloadIdentityError; +var init_types16 = __esm(() => { + init_error5(); + MAX_TOKEN_RESPONSE_BYTES = 1 << 20; + SAFE_ERROR_KEYS = new Set(["error", "error_description", "error_uri"]); + WorkloadIdentityError = class WorkloadIdentityError extends AnthropicError { + constructor(message, statusCode = null, body = null, requestId = null) { + super(message); + this.statusCode = statusCode; + this.body = body; + this.requestId = requestId; + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs +function nowAsSeconds() { + return Math.floor(Date.now() / 1000); +} + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs +class TokenCache { + constructor(provider, onAdvisoryRefreshError) { + this.cached = null; + this.pendingRefresh = null; + this.nextForce = false; + this.lastAdvisoryError = 0; + this.provider = provider; + this.onAdvisoryRefreshError = onAdvisoryRefreshError; + } + async getToken() { + const force = this.nextForce; + this.nextForce = false; + const cached3 = this.cached; + if (force || cached3 == null) { + const token2 = await this.refresh(force); + return token2.token; + } + if (cached3.expiresAt == null) { + return cached3.token; + } + const remaining = cached3.expiresAt - nowAsSeconds(); + if (remaining > ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) { + return cached3.token; + } + if (remaining > MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) { + this.backgroundRefresh(); + return cached3.token; + } + const token = await this.refresh(); + return token.token; + } + invalidate() { + this.cached = null; + this.nextForce = true; + } + refresh(force = false) { + if (this.pendingRefresh && !force) { + return this.pendingRefresh; + } + return this.doRefresh(force); + } + backgroundRefresh() { + if (this.pendingRefresh) { + return; + } + if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) { + return; + } + this.doRefresh().catch((err) => { + this.lastAdvisoryError = nowAsSeconds(); + this.onAdvisoryRefreshError?.(err); + }); + } + doRefresh(force = false) { + this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then((token) => { + this.cached = token; + this.pendingRefresh = null; + return token; + }, (err) => { + this.pendingRefresh = null; + throw err; + }); + return this.pendingRefresh; + } +} +var init_token_cache = __esm(() => { + init_types16(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +var readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() || undefined; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim() || undefined; + } + return; +}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +function concatBytes2(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index2 = 0; + for (const buffer of buffers) { + output.set(buffer, index2); + index2 += buffer.length; + } + return output; +} +function encodeUTF8(str) { + let encoder2; + return (encodeUTF8_ ?? (encoder2 = new globalThis.TextEncoder, encodeUTF8_ = encoder2.encode.bind(encoder2)))(str); +} +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder, decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); +} +var encodeUTF8_, decodeUTF8_; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs +var init_base64 = __esm(() => { + init_error5(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +function noop() {} +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger[fnLevel].bind(logger); + } +} +function loggerFor(client2) { + const logger = client2.logger; + const logLevel = client2.logLevel ?? "off"; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger, logLevel), + warn: makeLogFn("warn", logger, logLevel), + info: makeLogFn("info", logger, logLevel), + debug: makeLogFn("debug", logger, logLevel) + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client2) => { + if (!maybeLevel) { + return; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client2).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return; +}, noopLogger, cachedLoggers, formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +var init_log = __esm(() => { + init_values6(); + levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 + }; + noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop + }; + cachedLoggers = /* @__PURE__ */ new WeakMap; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils.mjs +var init_utils19 = __esm(() => { + init_values6(); + init_base64(); + init_log(); + init_query(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/credentials.mjs +function validateProfileName(name) { + if (!name) { + throw new Error("profile name is empty"); + } + if (name === "." || name === "..") { + throw new Error(`profile name "${name}" is not allowed`); + } + if (name.includes("/") || name.includes("\\")) { + throw new Error(`profile name "${name}" must not contain path separators`); + } + if (!PROFILE_NAME_PATTERN.test(name)) { + throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`); + } +} +var CREDENTIALS_FILE_VERSION = "1.0", PROFILE_NAME_PATTERN, loadConfigWithSource = async (profile) => { + var _a3, _b; + const rootConfigPath = await getRootConfigPath(); + if (rootConfigPath === null) { + return null; + } + const profileName = profile ?? await getActiveProfileName(); + if (profileName === null) { + return null; + } + validateProfileName(profileName); + const fs2 = await import("node:fs"); + const path3 = await import("node:path"); + const configPath = path3.join(rootConfigPath, "configs", `${profileName}.json`); + let configRaw; + try { + configRaw = await fs2.promises.readFile(configPath, "utf-8"); + } catch (err) { + if (err?.code !== "ENOENT") { + throw new Error(`failed to read config file ${configPath}: ${err}`); + } + configRaw = null; + } + if (configRaw === null) { + const organizationId = readEnv("ANTHROPIC_ORGANIZATION_ID"); + const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + const federationRuleId = readEnv("ANTHROPIC_FEDERATION_RULE_ID"); + if (federationRuleId && organizationId) { + return { + fromFile: false, + config: { + organization_id: organizationId, + workspace_id: readEnv("ANTHROPIC_WORKSPACE_ID"), + base_url: readEnv("ANTHROPIC_BASE_URL"), + authentication: { + type: "oidc_federation", + federation_rule_id: federationRuleId, + service_account_id: readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID"), + identity_token: identityTokenFile ? { source: "file", path: identityTokenFile } : undefined, + scope: readEnv("ANTHROPIC_SCOPE") + } + } + }; + } + return null; + } + let config3; + try { + config3 = JSON.parse(configRaw); + } catch (err) { + throw new Error(`failed to parse config file ${configPath}: ${err}`); + } + if (!config3.authentication) { + throw new Error(`config file ${configPath} is missing "authentication"`); + } + const authType = config3.authentication.type; + if (authType !== "oidc_federation" && authType !== "user_oauth") { + throw new Error(`authentication.type "${authType}" is not a known authentication type`); + } + config3.organization_id ?? (config3.organization_id = readEnv("ANTHROPIC_ORGANIZATION_ID")); + config3.workspace_id ?? (config3.workspace_id = readEnv("ANTHROPIC_WORKSPACE_ID")); + config3.base_url ?? (config3.base_url = readEnv("ANTHROPIC_BASE_URL")); + (_a3 = config3.authentication).scope ?? (_a3.scope = readEnv("ANTHROPIC_SCOPE")); + if (config3.authentication.type === "oidc_federation") { + if (!config3.authentication.identity_token) { + const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + if (identityTokenFile) { + config3.authentication.identity_token = { + source: "file", + path: identityTokenFile + }; + } + } + if (!config3.authentication.federation_rule_id) { + config3.authentication.federation_rule_id = readEnv("ANTHROPIC_FEDERATION_RULE_ID") ?? ""; + } + (_b = config3.authentication).service_account_id ?? (_b.service_account_id = readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID")); + } + return { config: config3, fromFile: true }; +}, getCredentialsPath = async (config3, profile) => { + if (config3?.authentication.credentials_path) { + return config3.authentication.credentials_path; + } + const rootConfigPath = await getRootConfigPath(); + if (!rootConfigPath) { + return null; + } + const profileName = profile ?? await getActiveProfileName(); + if (!profileName) { + return null; + } + validateProfileName(profileName); + const path3 = await import("node:path"); + return path3.join(rootConfigPath, "credentials", `${profileName}.json`); +}, getRootConfigPath = async () => { + if (!supportsLocalConfigFiles()) { + return null; + } + const path3 = await import("node:path"); + const configDir = readEnv("ANTHROPIC_CONFIG_DIR"); + if (configDir) { + return configDir; + } + const os2 = getPlatformHeaders()["X-Stainless-OS"]; + if (os2 === "Windows") { + const appData = readEnv("APPDATA"); + if (appData) { + return path3.join(appData, "Anthropic"); + } + const userProfile = readEnv("USERPROFILE"); + if (userProfile) { + return path3.join(userProfile, "AppData", "Roaming", "Anthropic"); + } + return null; + } + const xdgConfigHome = readEnv("XDG_CONFIG_HOME"); + if (xdgConfigHome) { + return path3.join(xdgConfigHome, "anthropic"); + } + const home = readEnv("HOME"); + if (home) { + return path3.join(home, ".config", "anthropic"); + } + return null; +}, supportsLocalConfigFiles = () => { + const runtime = getPlatformHeaders()["X-Stainless-Runtime"]; + return runtime === "node" || runtime === "deno"; +}, getActiveProfileName = async () => { + const rootConfigPath = await getRootConfigPath(); + if (!rootConfigPath) { + return null; + } + const profileName = readEnv("ANTHROPIC_PROFILE"); + if (profileName) { + return profileName; + } + const fs2 = await import("node:fs"); + const path3 = await import("node:path"); + const filePath = path3.join(rootConfigPath, "active_config"); + try { + return (await fs2.promises.readFile(filePath, "utf-8")).trim() || "default"; + } catch (err) { + if (err?.code !== "ENOENT") { + throw new Error(`failed to read ${filePath}: ${err}`); + } + return "default"; + } +}; +var init_credentials = __esm(() => { + init_detect_platform(); + init_utils19(); + PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs +function identityTokenFromFile(path3) { + if (!path3) { + throw new AnthropicError("Identity token file path is empty"); + } + return async () => { + const fs2 = await import("node:fs"); + let content; + try { + content = await fs2.promises.readFile(path3, "utf-8"); + } catch (err) { + throw new AnthropicError(`Failed to read identity token file at ${path3}: ${err}`); + } + const token = content.trim(); + if (!token) { + throw new AnthropicError(`Identity token file at ${path3} is empty`); + } + return token; + }; +} +function identityTokenFromValue(token) { + if (!token) { + throw new AnthropicError("Identity token value is empty"); + } + return () => token; +} +var init_identity_token = __esm(() => { + init_error5(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs +function oidcFederationProvider(config3) { + return async () => { + requireSecureTokenEndpoint(config3.baseURL); + const jwt3 = await config3.identityTokenProvider(); + if (jwt3.length > 16 * 1024) { + throw new WorkloadIdentityError(`Identity token is ${Math.ceil(jwt3.length / 1024)} KiB, exceeds the 16 KiB assertion limit`); + } + const body = { + grant_type: GRANT_TYPE_JWT_BEARER, + assertion: jwt3, + federation_rule_id: config3.federationRuleId, + organization_id: config3.organizationId + }; + if (config3.serviceAccountId) { + body["service_account_id"] = config3.serviceAccountId; + } + if (config3.workspaceId) { + body["workspace_id"] = config3.workspaceId; + } + const url3 = `${config3.baseURL}${TOKEN_ENDPOINT}`; + let resp; + try { + resp = await config3.fetch(url3, { + method: "POST", + headers: { + "Content-Type": "application/json", + "anthropic-beta": `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`, + "User-Agent": config3.userAgent || `anthropic-sdk-typescript/${VERSION} oidcFederationProvider` + }, + body: JSON.stringify(body) + }); + } catch (err) { + throw new WorkloadIdentityError(`Failed to reach token endpoint ${url3}: ${err}`); + } + const requestId = resp.headers.get("Request-Id"); + if (!resp.ok) { + const text = await resp.text().catch(() => ""); + const redacted = redactSensitive(text); + let hint = ""; + if (resp.status === 401) { + const hintMiddle = config3.workspaceId ? "" : "If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "; + hint = ` Ensure your federation rule matches your identity token. ${hintMiddle}View your authentication events in the Workload identity page of Claude Console for more details.`; + } + throw new WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ""}: ${redacted}${hint}`, resp.status, redacted, requestId); + } + const data = await parseTokenResponse(resp, requestId); + const expiresIn = Number(data.expires_in); + if (!Number.isFinite(expiresIn)) { + throw new WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + } + return { + token: data.access_token, + expiresAt: nowAsSeconds() + expiresIn + }; + }; +} +var init_oidc_federation = __esm(() => { + init_types16(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs +function userOAuthProvider(config3) { + return async (opts) => { + const fs2 = await import("node:fs"); + await checkCredentialsFileSafety(config3.credentialsPath, config3.onSafetyWarning); + let raw2; + try { + raw2 = await fs2.promises.readFile(config3.credentialsPath, "utf-8"); + } catch (err) { + throw new WorkloadIdentityError(`Credentials file not found at ${config3.credentialsPath}: ${err}`); + } + let creds; + try { + creds = JSON.parse(raw2); + } catch (err) { + throw new WorkloadIdentityError(`Credentials file at ${config3.credentialsPath} is not valid JSON: ${err}`); + } + const accessToken = creds.access_token; + if (!accessToken) { + throw new WorkloadIdentityError(`Credentials file at ${config3.credentialsPath} must include 'access_token'`); + } + const expiresAt = creds.expires_at; + if (!opts?.forceRefresh && (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) { + return { token: accessToken, expiresAt: expiresAt ?? null }; + } + const refreshToken = creds.refresh_token; + if (!config3.clientId || !refreshToken) { + throw new WorkloadIdentityError(`Access token at ${config3.credentialsPath} has expired and no refresh is available (client_id ${config3.clientId ? "set" : "empty"}, refresh_token ${refreshToken ? "set" : "empty"})`); + } + requireSecureTokenEndpoint(config3.baseURL); + const body = { + grant_type: GRANT_TYPE_REFRESH_TOKEN, + refresh_token: refreshToken, + client_id: config3.clientId + }; + const url3 = `${config3.baseURL}${TOKEN_ENDPOINT}`; + let resp; + try { + resp = await config3.fetch(url3, { + method: "POST", + headers: { + "Content-Type": "application/json", + "anthropic-beta": OAUTH_API_BETA_HEADER, + "User-Agent": config3.userAgent || `anthropic-sdk-typescript/${VERSION} userOAuthProvider` + }, + body: JSON.stringify(body) + }); + } catch (err) { + throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`); + } + const requestId = resp.headers.get("Request-Id"); + if (!resp.ok) { + const text = await resp.text().catch(() => ""); + throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId); + } + const data = await parseTokenResponse(resp, requestId); + const expiresIn = Number(data.expires_in); + if (!Number.isFinite(expiresIn)) { + throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId); + } + const newExpiresAt = nowAsSeconds() + expiresIn; + const newRefreshToken = data.refresh_token || refreshToken; + await writeCredentialsFileAtomic(config3.credentialsPath, { + ...creds, + version: CREDENTIALS_FILE_VERSION, + type: "oauth_token", + access_token: data.access_token, + expires_at: newExpiresAt, + refresh_token: newRefreshToken + }); + return { token: data.access_token, expiresAt: newExpiresAt }; + }; +} +var init_user_oauth = __esm(() => { + init_credentials(); + init_types16(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs +function resolveCredentialsFromConfig(config3, options) { + const credentialsPath = config3.authentication.credentials_path ?? null; + const effectiveBaseURL = (config3.base_url || options.baseURL).replace(/\/+$/, ""); + const provider = buildProvider(config3, credentialsPath, effectiveBaseURL, options); + const extraHeaders = {}; + if (config3.workspace_id && config3.authentication.type === "user_oauth") { + extraHeaders["anthropic-workspace-id"] = config3.workspace_id; + } + return { provider, extraHeaders, baseURL: config3.base_url || undefined }; +} +async function defaultCredentials(options, profile) { + const loaded = await loadConfigWithSource(profile); + if (!loaded) { + return null; + } + const { config: config3, fromFile } = loaded; + const withPath = config3.authentication.credentials_path || !fromFile ? config3 : { + ...config3, + authentication: { + ...config3.authentication, + credentials_path: await getCredentialsPath(config3, profile) ?? undefined + } + }; + return resolveCredentialsFromConfig(withPath, options); +} +function buildProvider(config3, credentialsPath, baseURL, options) { + switch (config3.authentication.type) { + case "oidc_federation": { + const auth = config3.authentication; + const identityProvider = resolveIdentityTokenProvider(auth); + if (!identityProvider) { + throw new WorkloadIdentityError("oidc_federation config requires an identity token (set authentication.identity_token, " + "ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)"); + } + if (!auth.federation_rule_id) { + throw new WorkloadIdentityError("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence)."); + } + if (!config3.organization_id) { + throw new WorkloadIdentityError("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)"); + } + const exchange = oidcFederationProvider({ + identityTokenProvider: identityProvider, + federationRuleId: auth.federation_rule_id, + organizationId: config3.organization_id, + serviceAccountId: auth.service_account_id, + workspaceId: config3.workspace_id, + baseURL, + fetch: options.fetch, + userAgent: options.userAgent + }); + if (credentialsPath) { + return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning); + } + return exchange; + } + case "user_oauth": { + if (!credentialsPath) { + throw new WorkloadIdentityError("user_oauth config requires authentication.credentials_path " + "(or load via a profile so it defaults to /credentials/.json)"); + } + return userOAuthProvider({ + credentialsPath, + clientId: config3.authentication.client_id, + baseURL, + fetch: options.fetch, + userAgent: options.userAgent, + onSafetyWarning: options.onSafetyWarning + }); + } + default: { + const t = config3.authentication.type; + throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`); + } + } +} +function resolveIdentityTokenProvider(auth) { + if (auth.identity_token) { + const source = auth.identity_token.source; + if (source !== "file") { + throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`); + } + if (!auth.identity_token.path) { + throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`); + } + return identityTokenFromFile(auth.identity_token.path); + } + const tokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); + if (tokenFile) { + return identityTokenFromFile(tokenFile); + } + const tokenValue = readEnv("ANTHROPIC_IDENTITY_TOKEN"); + if (tokenValue) { + return identityTokenFromValue(tokenValue); + } + return null; +} +function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) { + return async (opts) => { + const fs2 = await import("node:fs"); + await checkCredentialsFileSafety(credentialsPath, onSafetyWarning); + let existing; + try { + const raw2 = await fs2.promises.readFile(credentialsPath, "utf-8"); + existing = JSON.parse(raw2); + const token = existing?.["access_token"]; + if (token && !opts?.forceRefresh) { + const expiresAt = existing?.["expires_at"]; + if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) { + return { token, expiresAt: expiresAt ?? null }; + } + } + } catch (err) { + const code = err?.code; + if (code !== "ENOENT" && !(err instanceof SyntaxError)) { + onCacheWriteError?.(err); + } + } + const result = await exchange(opts); + try { + await writeCredentialsFileAtomic(credentialsPath, { + ...existing ?? {}, + version: CREDENTIALS_FILE_VERSION, + type: "oauth_token", + access_token: result.token, + expires_at: result.expiresAt + }); + } catch (err) { + onCacheWriteError?.(err); + } + return result; + }; +} +var init_credential_chain = __esm(() => { + init_credentials(); + init_types16(); + init_identity_token(); + init_oidc_federation(); + init_user_oauth(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +class LineDecoder { + constructor() { + _LineDecoder_buffer.set(this, undefined); + _LineDecoder_carriageReturnIndex.set(this, undefined); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array, "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes2([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + return []; + } + return this.decode(` +`); + } +} +function findNewlineIndex(buffer, startIndex) { + const newline = 10; + const carriage = 13; + for (let i = startIndex ?? 0;i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; + } + } + return null; +} +function findDoubleNewlineIndex(buffer) { + const newline = 10; + const carriage = 13; + for (let i = 0;i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) { + return i + 4; + } + } + return -1; +} +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; +var init_line = __esm(() => { + init_tslib(); + _LineDecoder_buffer = new WeakMap, _LineDecoder_carriageReturnIndex = new WeakMap; + LineDecoder.NEWLINE_CHARS = new Set([` +`, "\r"]); + LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/streaming.mjs +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder3; + const lineDecoder = new LineDecoder; + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +async function* iterSSEChunks(iterator) { + let data = new Uint8Array; + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} + +class SSEDecoder3 { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith("\r")) { + line = line.substring(0, line.length - 1); + } + if (!line) { + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join(` +`), + raw: this.chunks + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(":")) { + return null; + } + let [fieldname, _, value] = partition(line, ":"); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (fieldname === "event") { + this.event = value; + } else if (fieldname === "data") { + this.data.push(value); + } + return null; + } +} +function partition(str, delimiter) { + const index2 = str.indexOf(delimiter); + if (index2 !== -1) { + return [str.substring(0, index2), delimiter, str.substring(index2 + delimiter.length)]; + } + return [str, "", ""]; +} +var _Stream_client, Stream; +var init_streaming = __esm(() => { + init_tslib(); + init_error5(); + init_line(); + init_values6(); + init_log(); + init_error5(); + Stream = class Stream { + constructor(iterator, controller, client2) { + this.iterator = iterator; + _Stream_client.set(this, undefined); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client2, "f"); + } + static fromSSEResponse(response, controller, client2) { + let consumed = false; + const logger = client2 ? loggerFor(client2) : console; + async function* iterator() { + if (consumed) { + throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (sse.event === "completion") { + try { + yield JSON.parse(sse.data); + } catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated") { + try { + yield JSON.parse(sse.data); + } catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === "ping") { + continue; + } + if (sse.event === "error") { + const body = safeJSON(sse.data) ?? sse.data; + const type = body?.error?.type; + throw new APIError(undefined, body, undefined, response.headers, type); + } + } + done = true; + } catch (e) { + if (isAbortError(e)) + return; + throw e; + } finally { + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client2); + } + static fromReadableStream(readableStream, controller, client2) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder; + const iter = ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } catch (e) { + if (isAbortError(e)) + return; + throw e; + } finally { + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client2); + } + [(_Stream_client = new WeakMap, Symbol.asyncIterator)]() { + return this.iterator(); + } + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue2) => { + return { + next: () => { + if (queue2.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue2.shift(); + } + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")) + ]; + } + toReadableStream() { + const self2 = this; + let iter; + return makeReadableStream({ + async start() { + iter = self2[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encodeUTF8(JSON.stringify(value) + ` +`); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + } + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/parse.mjs +async function defaultParseResponse(client2, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client2).debug("response", response.status, response.url, response.headers, response.body); + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return; + } + const json3 = await response.json(); + return addRequestID(json3, response); + } + const text = await response.text(); + return text; + })(); + loggerFor(client2).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, "_request_id", { + value: response.headers.get("request-id"), + enumerable: false + }); +} +var init_parse7 = __esm(() => { + init_streaming(); + init_log(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/api-promise.mjs +var _APIPromise_client, APIPromise; +var init_api_promise = __esm(() => { + init_tslib(); + init_parse7(); + APIPromise = class APIPromise extends Promise { + constructor(client2, responsePromise, parseResponse = defaultParseResponse) { + super((resolve2) => { + resolve2(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, undefined); + __classPrivateFieldSet(this, _APIPromise_client, client2, "f"); + } + _thenUnwrap(transform3) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client2, props) => addRequestID(transform3(await this.parseResponse(client2, props), props), props.response)); + } + asResponse() { + return this.responsePromise.then((p) => p.response); + } + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get("request-id") }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } + }; + _APIPromise_client = new WeakMap; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/pagination.mjs +var _AbstractPage_client, AbstractPage, PagePromise, Page, PageCursor; +var init_pagination = __esm(() => { + init_tslib(); + init_error5(); + init_parse7(); + init_api_promise(); + init_values6(); + AbstractPage = class AbstractPage { + constructor(client2, response, body, options) { + _AbstractPage_client.set(this, undefined); + __classPrivateFieldSet(this, _AbstractPage_client, client2, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async* iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async* [(_AbstractPage_client = new WeakMap, Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } + }; + PagePromise = class PagePromise extends APIPromise { + constructor(client2, request, Page) { + super(client2, request, async (client3, props) => new Page(client3, props.response, await defaultParseResponse(client3, props), props.options)); + } + async* [Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } + }; + Page = class Page extends AbstractPage { + constructor(client2, response, body, options) { + super(client2, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + if (this.options.query?.["before_id"]) { + const first_id = this.first_id; + if (!first_id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + before_id: first_id + } + }; + } + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after_id: cursor + } + }; + } + }; + PageCursor = class PageCursor extends AbstractPage { + constructor(client2, response, body, options) { + super(client2, response, body, options); + this.data = body.data || []; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor + } + }; + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/uploads.mjs +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value, stripPath) { + const val = typeof value === "object" && value !== null && (("name" in value) && value.name && String(value.name) || ("url" in value) && value.url && String(value.url) || ("filename" in value) && value.filename && String(value.filename) || ("path" in value) && value.path && String(value.path)) || ""; + return stripPath ? val.split(/[\\/]/).pop() || undefined : val; +} +function supportsFormData(fetchObject) { + const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached3 = supportsFormDataMap.get(fetch2); + if (cached3) + return cached3; + const promise3 = (async () => { + try { + const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor; + const data = new FormData; + if (data.toString() === await new FetchResponse(data).text()) { + return false; + } + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch2, promise3); + return promise3; +} +var checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process3 } = globalThis; + const isOldNode = typeof process3?.versions?.node === "string" && parseInt(process3.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } +}, isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", multipartFormRequestOptions = async (opts, fetch2, stripFilenames = true) => { + return { ...opts, body: await createForm(opts.body, fetch2, stripFilenames) }; +}, supportsFormDataMap, createForm = async (body, fetch2, stripFilenames = true) => { + if (!await supportsFormData(fetch2)) { + throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + } + const form = new FormData; + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames))); + return form; +}, isNamedBlob = (value) => value instanceof Blob && ("name" in value), addFormValue = async (form, key, value, stripFilenames) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + form.append(key, String(value)); + } else if (value instanceof Response) { + let options = {}; + const contentType = value.headers.get("Content-Type"); + if (contentType) { + options = { type: contentType }; + } + form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); + } else if (isAsyncIterable2(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); + } else if (isNamedBlob(value)) { + form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames))); + } else if (typeof value === "object") { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); + } else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +var init_uploads = __esm(() => { + supportsFormDataMap = /* @__PURE__ */ new WeakMap; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/to-file.mjs +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + name || (name = getName(value, true)); + if (isFileLike(value)) { + if (value instanceof File && name == null && options == null) { + return value; + } + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options + }); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes2(blob), name, options); + } + const parts = await getBytes2(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && ("type" in part) && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes2(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable2(value)) { + for await (const chunk of value) { + parts.push(...await getBytes2(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`; +} +var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; +var init_to_file = __esm(() => { + init_uploads(); + init_uploads(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/uploads.mjs +var init_uploads2 = __esm(() => { + init_to_file(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/shared.mjs +var init_shared = () => {}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/core/resource.mjs +class APIResource { + constructor(client2) { + this._client = client2; + } +} + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/headers.mjs +function* iterateHeaders2(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values: values2, nulls } = headers; + yield* values2.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values2 = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values2) { + if (value === undefined) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var brand_privateNullableHeaders, buildHeaders = (newHeaders) => { + const targetHeaders = new Headers; + const nullHeaders = new Set; + for (const headers of newHeaders) { + const seenHeaders = new Set; + for (const [name, value] of iterateHeaders2(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +var init_headers = __esm(() => { + init_values6(); + brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders"); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY, createPathTagFunction = (pathEncoder = encodeURIPath) => function path3(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path4 = statics.reduce((previousValue, currentValue, index2) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index2]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index2 !== params.length && (value == null || typeof value === "object" && value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index2 === params.length ? "" : encoded); + }, ""); + const pathOnly = path4.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match2; + while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match2.index, + length: match2[0].length, + error: `Value "${match2[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new AnthropicError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e) => e.error).join(` +`)} +${path4} +${underline}`); + } + return path4; +}, path3; +var init_path = __esm(() => { + init_error5(); + EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); + path3 = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/environments.mjs +var Environments; +var init_environments = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Environments = class Environments extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/environments?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/environments/${environmentID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(environmentID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/environments/${environmentID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/environments?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/environments/${environmentID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(environmentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/environments/${environmentID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs +function wasCreatedByStainlessHelper(value) { + return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value; +} +function collectStainlessHelpers(tools, messages) { + const helpers = new Set; + if (tools) { + for (const tool2 of tools) { + if (wasCreatedByStainlessHelper(tool2)) { + helpers.add(tool2[SDK_HELPER_SYMBOL]); + } + } + } + if (messages) { + for (const message of messages) { + if (wasCreatedByStainlessHelper(message)) { + helpers.add(message[SDK_HELPER_SYMBOL]); + } + if (Array.isArray(message.content)) { + for (const block of message.content) { + if (wasCreatedByStainlessHelper(block)) { + helpers.add(block[SDK_HELPER_SYMBOL]); + } + } + } + } + } + return Array.from(helpers); +} +function stainlessHelperHeader(tools, messages) { + const helpers = collectStainlessHelpers(tools, messages); + if (helpers.length === 0) + return {}; + return { "x-stainless-helper": helpers.join(", ") }; +} +function stainlessHelperHeaderFromFile(file3) { + if (wasCreatedByStainlessHelper(file3)) { + return { "x-stainless-helper": file3[SDK_HELPER_SYMBOL] }; + } + return {}; +} +var SDK_HELPER_SYMBOL; +var init_stainless_helper_header = __esm(() => { + SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper"); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +var Files; +var init_files = __esm(() => { + init_pagination(); + init_headers(); + init_stainless_helper_header(); + init_uploads(); + init_path(); + Files = class Files extends APIResource { + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/files?beta=true", Page, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/files/${fileID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/files/${fileID}/content?beta=true`, { + ...options, + headers: buildHeaders([ + { + "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(), + Accept: "application/binary" + }, + options?.headers + ]), + __binaryResponse: true + }); + } + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/files/${fileID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + upload(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/files?beta=true", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + stainlessHelperHeaderFromFile(body.file), + options?.headers + ]) + }, this._client)); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +var Models; +var init_models = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Models = class Models extends APIResource { + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/models/${modelID}?beta=true`, { + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/models?beta=true", Page, { + query: query4, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs +var UserProfiles; +var init_user_profiles = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + UserProfiles = class UserProfiles extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/user_profiles?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, + options?.headers + ]) + }); + } + retrieve(userProfileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/user_profiles/${userProfileID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, + options?.headers + ]) + }); + } + update(userProfileID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/user_profiles/${userProfileID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/user_profiles?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, + options?.headers + ]) + }); + } + createEnrollmentURL(userProfileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "user-profiles-2026-03-24"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/standardwebhooks@1.0.0/node_modules/standardwebhooks/dist/timing_safe_equal.js +var require_timing_safe_equal = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.timingSafeEqual = undefined; + function assert6(expr, msg = "") { + if (!expr) { + throw new Error(msg); + } + } + function timingSafeEqual(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + if (!(a instanceof DataView)) { + a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a); + } + if (!(b instanceof DataView)) { + b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b); + } + assert6(a instanceof DataView); + assert6(b instanceof DataView); + const length = a.byteLength; + let out = 0; + let i = -1; + while (++i < length) { + out |= a.getUint8(i) ^ b.getUint8(i); + } + return out === 0; + } + exports.timingSafeEqual = timingSafeEqual; +}); + +// ../../node_modules/.pnpm/@stablelib+base64@1.0.1/node_modules/@stablelib/base64/lib/base64.js +var require_base64 = __commonJS((exports) => { + var __extends = exports && exports.__extends || function() { + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) + if (b2.hasOwnProperty(p)) + d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + return function(d, b) { + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __); + }; + }(); + Object.defineProperty(exports, "__esModule", { value: true }); + var INVALID_BYTE = 256; + var Coder = function() { + function Coder2(_paddingCharacter) { + if (_paddingCharacter === undefined) { + _paddingCharacter = "="; + } + this._paddingCharacter = _paddingCharacter; + } + Coder2.prototype.encodedLength = function(length) { + if (!this._paddingCharacter) { + return (length * 8 + 5) / 6 | 0; + } + return (length + 2) / 3 * 4 | 0; + }; + Coder2.prototype.encode = function(data) { + var out = ""; + var i = 0; + for (;i < data.length - 2; i += 3) { + var c = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; + out += this._encodeByte(c >>> 3 * 6 & 63); + out += this._encodeByte(c >>> 2 * 6 & 63); + out += this._encodeByte(c >>> 1 * 6 & 63); + out += this._encodeByte(c >>> 0 * 6 & 63); + } + var left = data.length - i; + if (left > 0) { + var c = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0); + out += this._encodeByte(c >>> 3 * 6 & 63); + out += this._encodeByte(c >>> 2 * 6 & 63); + if (left === 2) { + out += this._encodeByte(c >>> 1 * 6 & 63); + } else { + out += this._paddingCharacter || ""; + } + out += this._paddingCharacter || ""; + } + return out; + }; + Coder2.prototype.maxDecodedLength = function(length) { + if (!this._paddingCharacter) { + return (length * 6 + 7) / 8 | 0; + } + return length / 4 * 3 | 0; + }; + Coder2.prototype.decodedLength = function(s) { + return this.maxDecodedLength(s.length - this._getPaddingLength(s)); + }; + Coder2.prototype.decode = function(s) { + if (s.length === 0) { + return new Uint8Array(0); + } + var paddingLength = this._getPaddingLength(s); + var length = s.length - paddingLength; + var out = new Uint8Array(this.maxDecodedLength(length)); + var op = 0; + var i = 0; + var haveBad = 0; + var v0 = 0, v14 = 0, v2 = 0, v32 = 0; + for (;i < length - 4; i += 4) { + v0 = this._decodeChar(s.charCodeAt(i + 0)); + v14 = this._decodeChar(s.charCodeAt(i + 1)); + v2 = this._decodeChar(s.charCodeAt(i + 2)); + v32 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v0 << 2 | v14 >>> 4; + out[op++] = v14 << 4 | v2 >>> 2; + out[op++] = v2 << 6 | v32; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v14 & INVALID_BYTE; + haveBad |= v2 & INVALID_BYTE; + haveBad |= v32 & INVALID_BYTE; + } + if (i < length - 1) { + v0 = this._decodeChar(s.charCodeAt(i)); + v14 = this._decodeChar(s.charCodeAt(i + 1)); + out[op++] = v0 << 2 | v14 >>> 4; + haveBad |= v0 & INVALID_BYTE; + haveBad |= v14 & INVALID_BYTE; + } + if (i < length - 2) { + v2 = this._decodeChar(s.charCodeAt(i + 2)); + out[op++] = v14 << 4 | v2 >>> 2; + haveBad |= v2 & INVALID_BYTE; + } + if (i < length - 3) { + v32 = this._decodeChar(s.charCodeAt(i + 3)); + out[op++] = v2 << 6 | v32; + haveBad |= v32 & INVALID_BYTE; + } + if (haveBad !== 0) { + throw new Error("Base64Coder: incorrect characters for decoding"); + } + return out; + }; + Coder2.prototype._encodeByte = function(b) { + var result = b; + result += 65; + result += 25 - b >>> 8 & 0 - 65 - 26 + 97; + result += 51 - b >>> 8 & 26 - 97 - 52 + 48; + result += 61 - b >>> 8 & 52 - 48 - 62 + 43; + result += 62 - b >>> 8 & 62 - 43 - 63 + 47; + return String.fromCharCode(result); + }; + Coder2.prototype._decodeChar = function(c) { + var result = INVALID_BYTE; + result += (42 - c & c - 44) >>> 8 & -INVALID_BYTE + c - 43 + 62; + result += (46 - c & c - 48) >>> 8 & -INVALID_BYTE + c - 47 + 63; + result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; + result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; + result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; + return result; + }; + Coder2.prototype._getPaddingLength = function(s) { + var paddingLength = 0; + if (this._paddingCharacter) { + for (var i = s.length - 1;i >= 0; i--) { + if (s[i] !== this._paddingCharacter) { + break; + } + paddingLength++; + } + if (s.length < 4 || paddingLength > 2) { + throw new Error("Base64Coder: incorrect padding"); + } + } + return paddingLength; + }; + return Coder2; + }(); + exports.Coder = Coder; + var stdCoder = new Coder; + function encode4(data) { + return stdCoder.encode(data); + } + exports.encode = encode4; + function decode3(s) { + return stdCoder.decode(s); + } + exports.decode = decode3; + var URLSafeCoder = function(_super) { + __extends(URLSafeCoder2, _super); + function URLSafeCoder2() { + return _super !== null && _super.apply(this, arguments) || this; + } + URLSafeCoder2.prototype._encodeByte = function(b) { + var result = b; + result += 65; + result += 25 - b >>> 8 & 0 - 65 - 26 + 97; + result += 51 - b >>> 8 & 26 - 97 - 52 + 48; + result += 61 - b >>> 8 & 52 - 48 - 62 + 45; + result += 62 - b >>> 8 & 62 - 45 - 63 + 95; + return String.fromCharCode(result); + }; + URLSafeCoder2.prototype._decodeChar = function(c) { + var result = INVALID_BYTE; + result += (44 - c & c - 46) >>> 8 & -INVALID_BYTE + c - 45 + 62; + result += (94 - c & c - 96) >>> 8 & -INVALID_BYTE + c - 95 + 63; + result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52; + result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0; + result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26; + return result; + }; + return URLSafeCoder2; + }(Coder); + exports.URLSafeCoder = URLSafeCoder; + var urlSafeCoder = new URLSafeCoder; + function encodeURLSafe(data) { + return urlSafeCoder.encode(data); + } + exports.encodeURLSafe = encodeURLSafe; + function decodeURLSafe(s) { + return urlSafeCoder.decode(s); + } + exports.decodeURLSafe = decodeURLSafe; + exports.encodedLength = function(length) { + return stdCoder.encodedLength(length); + }; + exports.maxDecodedLength = function(length) { + return stdCoder.maxDecodedLength(length); + }; + exports.decodedLength = function(s) { + return stdCoder.decodedLength(s); + }; +}); + +// ../../node_modules/.pnpm/fast-sha256@1.3.0/node_modules/fast-sha256/sha256.js +var require_sha256 = __commonJS((exports, module) => { + (function(root, factory) { + var exports2 = {}; + factory(exports2); + var sha2562 = exports2["default"]; + for (var k in exports2) { + sha2562[k] = exports2[k]; + } + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = sha2562; + } else if (typeof define === "function" && define.amd) { + define(function() { + return sha2562; + }); + } else { + root.sha256 = sha2562; + } + })(exports, function(exports2) { + exports2.__esModule = true; + exports2.digestLength = 32; + exports2.blockSize = 64; + var K2 = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + function hashBlocks(w, v, p, pos, len) { + var a, b, c, d, e, f3, g, h, u, i, j, t1, t2; + while (len >= 64) { + a = v[0]; + b = v[1]; + c = v[2]; + d = v[3]; + e = v[4]; + f3 = v[5]; + g = v[6]; + h = v[7]; + for (i = 0;i < 16; i++) { + j = pos + i * 4; + w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255; + } + for (i = 16;i < 64; i++) { + u = w[i - 2]; + t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; + u = w[i - 15]; + t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; + w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0); + } + for (i = 0;i < 64; i++) { + t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f3 ^ ~e & g) | 0) + (h + (K2[i] + w[i] | 0) | 0) | 0; + t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0; + h = g; + g = f3; + f3 = e; + e = d + t1 | 0; + d = c; + c = b; + b = a; + a = t1 + t2 | 0; + } + v[0] += a; + v[1] += b; + v[2] += c; + v[3] += d; + v[4] += e; + v[5] += f3; + v[6] += g; + v[7] += h; + pos += 64; + len -= 64; + } + return pos; + } + var Hash = function() { + function Hash2() { + this.digestLength = exports2.digestLength; + this.blockSize = exports2.blockSize; + this.state = new Int32Array(8); + this.temp = new Int32Array(64); + this.buffer = new Uint8Array(128); + this.bufferLength = 0; + this.bytesHashed = 0; + this.finished = false; + this.reset(); + } + Hash2.prototype.reset = function() { + this.state[0] = 1779033703; + this.state[1] = 3144134277; + this.state[2] = 1013904242; + this.state[3] = 2773480762; + this.state[4] = 1359893119; + this.state[5] = 2600822924; + this.state[6] = 528734635; + this.state[7] = 1541459225; + this.bufferLength = 0; + this.bytesHashed = 0; + this.finished = false; + return this; + }; + Hash2.prototype.clean = function() { + for (var i = 0;i < this.buffer.length; i++) { + this.buffer[i] = 0; + } + for (var i = 0;i < this.temp.length; i++) { + this.temp[i] = 0; + } + this.reset(); + }; + Hash2.prototype.update = function(data, dataLength) { + if (dataLength === undefined) { + dataLength = data.length; + } + if (this.finished) { + throw new Error("SHA256: can't update because hash was finished."); + } + var dataPos = 0; + this.bytesHashed += dataLength; + if (this.bufferLength > 0) { + while (this.bufferLength < 64 && dataLength > 0) { + this.buffer[this.bufferLength++] = data[dataPos++]; + dataLength--; + } + if (this.bufferLength === 64) { + hashBlocks(this.temp, this.state, this.buffer, 0, 64); + this.bufferLength = 0; + } + } + if (dataLength >= 64) { + dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength); + dataLength %= 64; + } + while (dataLength > 0) { + this.buffer[this.bufferLength++] = data[dataPos++]; + dataLength--; + } + return this; + }; + Hash2.prototype.finish = function(out) { + if (!this.finished) { + var bytesHashed = this.bytesHashed; + var left = this.bufferLength; + var bitLenHi = bytesHashed / 536870912 | 0; + var bitLenLo = bytesHashed << 3; + var padLength = bytesHashed % 64 < 56 ? 64 : 128; + this.buffer[left] = 128; + for (var i = left + 1;i < padLength - 8; i++) { + this.buffer[i] = 0; + } + this.buffer[padLength - 8] = bitLenHi >>> 24 & 255; + this.buffer[padLength - 7] = bitLenHi >>> 16 & 255; + this.buffer[padLength - 6] = bitLenHi >>> 8 & 255; + this.buffer[padLength - 5] = bitLenHi >>> 0 & 255; + this.buffer[padLength - 4] = bitLenLo >>> 24 & 255; + this.buffer[padLength - 3] = bitLenLo >>> 16 & 255; + this.buffer[padLength - 2] = bitLenLo >>> 8 & 255; + this.buffer[padLength - 1] = bitLenLo >>> 0 & 255; + hashBlocks(this.temp, this.state, this.buffer, 0, padLength); + this.finished = true; + } + for (var i = 0;i < 8; i++) { + out[i * 4 + 0] = this.state[i] >>> 24 & 255; + out[i * 4 + 1] = this.state[i] >>> 16 & 255; + out[i * 4 + 2] = this.state[i] >>> 8 & 255; + out[i * 4 + 3] = this.state[i] >>> 0 & 255; + } + return this; + }; + Hash2.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + Hash2.prototype._saveState = function(out) { + for (var i = 0;i < this.state.length; i++) { + out[i] = this.state[i]; + } + }; + Hash2.prototype._restoreState = function(from, bytesHashed) { + for (var i = 0;i < this.state.length; i++) { + this.state[i] = from[i]; + } + this.bytesHashed = bytesHashed; + this.finished = false; + this.bufferLength = 0; + }; + return Hash2; + }(); + exports2.Hash = Hash; + var HMAC = function() { + function HMAC2(key) { + this.inner = new Hash; + this.outer = new Hash; + this.blockSize = this.inner.blockSize; + this.digestLength = this.inner.digestLength; + var pad = new Uint8Array(this.blockSize); + if (key.length > this.blockSize) { + new Hash().update(key).finish(pad).clean(); + } else { + for (var i = 0;i < key.length; i++) { + pad[i] = key[i]; + } + } + for (var i = 0;i < pad.length; i++) { + pad[i] ^= 54; + } + this.inner.update(pad); + for (var i = 0;i < pad.length; i++) { + pad[i] ^= 54 ^ 92; + } + this.outer.update(pad); + this.istate = new Uint32Array(8); + this.ostate = new Uint32Array(8); + this.inner._saveState(this.istate); + this.outer._saveState(this.ostate); + for (var i = 0;i < pad.length; i++) { + pad[i] = 0; + } + } + HMAC2.prototype.reset = function() { + this.inner._restoreState(this.istate, this.inner.blockSize); + this.outer._restoreState(this.ostate, this.outer.blockSize); + return this; + }; + HMAC2.prototype.clean = function() { + for (var i = 0;i < this.istate.length; i++) { + this.ostate[i] = this.istate[i] = 0; + } + this.inner.clean(); + this.outer.clean(); + }; + HMAC2.prototype.update = function(data) { + this.inner.update(data); + return this; + }; + HMAC2.prototype.finish = function(out) { + if (this.outer.finished) { + this.outer.finish(out); + } else { + this.inner.finish(out); + this.outer.update(out, this.digestLength).finish(out); + } + return this; + }; + HMAC2.prototype.digest = function() { + var out = new Uint8Array(this.digestLength); + this.finish(out); + return out; + }; + return HMAC2; + }(); + exports2.HMAC = HMAC; + function hash2(data) { + var h = new Hash().update(data); + var digest = h.digest(); + h.clean(); + return digest; + } + exports2.hash = hash2; + exports2["default"] = hash2; + function hmac(key, data) { + var h = new HMAC(key).update(data); + var digest = h.digest(); + h.clean(); + return digest; + } + exports2.hmac = hmac; + function fillBuffer(buffer, hmac2, info, counter) { + var num = counter[0]; + if (num === 0) { + throw new Error("hkdf: cannot expand more"); + } + hmac2.reset(); + if (num > 1) { + hmac2.update(buffer); + } + if (info) { + hmac2.update(info); + } + hmac2.update(counter); + hmac2.finish(buffer); + counter[0]++; + } + var hkdfSalt = new Uint8Array(exports2.digestLength); + function hkdf(key, salt, info, length) { + if (salt === undefined) { + salt = hkdfSalt; + } + if (length === undefined) { + length = 32; + } + var counter = new Uint8Array([1]); + var okm = hmac(salt, key); + var hmac_ = new HMAC(okm); + var buffer = new Uint8Array(hmac_.digestLength); + var bufpos = buffer.length; + var out = new Uint8Array(length); + for (var i = 0;i < length; i++) { + if (bufpos === buffer.length) { + fillBuffer(buffer, hmac_, info, counter); + bufpos = 0; + } + out[i] = buffer[bufpos++]; + } + hmac_.clean(); + buffer.fill(0); + counter.fill(0); + return out; + } + exports2.hkdf = hkdf; + function pbkdf2(password, salt, iterations, dkLen) { + var prf = new HMAC(password); + var len = prf.digestLength; + var ctr = new Uint8Array(4); + var t = new Uint8Array(len); + var u = new Uint8Array(len); + var dk = new Uint8Array(dkLen); + for (var i = 0;i * len < dkLen; i++) { + var c = i + 1; + ctr[0] = c >>> 24 & 255; + ctr[1] = c >>> 16 & 255; + ctr[2] = c >>> 8 & 255; + ctr[3] = c >>> 0 & 255; + prf.reset(); + prf.update(salt); + prf.update(ctr); + prf.finish(u); + for (var j = 0;j < len; j++) { + t[j] = u[j]; + } + for (var j = 2;j <= iterations; j++) { + prf.reset(); + prf.update(u).finish(u); + for (var k = 0;k < len; k++) { + t[k] ^= u[k]; + } + } + for (var j = 0;j < len && i * len + j < dkLen; j++) { + dk[i * len + j] = t[j]; + } + } + for (var i = 0;i < len; i++) { + t[i] = u[i] = 0; + } + for (var i = 0;i < 4; i++) { + ctr[i] = 0; + } + prf.clean(); + return dk; + } + exports2.pbkdf2 = pbkdf2; + }); +}); + +// ../../node_modules/.pnpm/standardwebhooks@1.0.0/node_modules/standardwebhooks/dist/index.js +var require_dist4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Webhook = exports.WebhookVerificationError = undefined; + var timing_safe_equal_1 = require_timing_safe_equal(); + var base647 = require_base64(); + var sha2562 = require_sha256(); + var WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60; + + class ExtendableError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, ExtendableError.prototype); + this.name = "ExtendableError"; + this.stack = new Error(message).stack; + } + } + + class WebhookVerificationError extends ExtendableError { + constructor(message) { + super(message); + Object.setPrototypeOf(this, WebhookVerificationError.prototype); + this.name = "WebhookVerificationError"; + } + } + exports.WebhookVerificationError = WebhookVerificationError; + + class Webhook { + constructor(secret, options) { + if (!secret) { + throw new Error("Secret can't be empty."); + } + if ((options === null || options === undefined ? undefined : options.format) === "raw") { + if (secret instanceof Uint8Array) { + this.key = secret; + } else { + this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0)); + } + } else { + if (typeof secret !== "string") { + throw new Error("Expected secret to be of type string"); + } + if (secret.startsWith(Webhook.prefix)) { + secret = secret.substring(Webhook.prefix.length); + } + this.key = base647.decode(secret); + } + } + verify(payload, headers_) { + const headers = {}; + for (const key of Object.keys(headers_)) { + headers[key.toLowerCase()] = headers_[key]; + } + const msgId = headers["webhook-id"]; + const msgSignature = headers["webhook-signature"]; + const msgTimestamp = headers["webhook-timestamp"]; + if (!msgSignature || !msgId || !msgTimestamp) { + throw new WebhookVerificationError("Missing required headers"); + } + const timestamp = this.verifyTimestamp(msgTimestamp); + const computedSignature = this.sign(msgId, timestamp, payload); + const expectedSignature = computedSignature.split(",")[1]; + const passedSignatures = msgSignature.split(" "); + const encoder2 = new globalThis.TextEncoder; + for (const versionedSignature of passedSignatures) { + const [version6, signature] = versionedSignature.split(","); + if (version6 !== "v1") { + continue; + } + if ((0, timing_safe_equal_1.timingSafeEqual)(encoder2.encode(signature), encoder2.encode(expectedSignature))) { + return JSON.parse(payload.toString()); + } + } + throw new WebhookVerificationError("No matching signature found"); + } + sign(msgId, timestamp, payload) { + if (typeof payload === "string") {} else if (payload.constructor.name === "Buffer") { + payload = payload.toString(); + } else { + throw new Error("Expected payload to be of type string or Buffer."); + } + const encoder2 = new TextEncoder; + const timestampNumber = Math.floor(timestamp.getTime() / 1000); + const toSign = encoder2.encode(`${msgId}.${timestampNumber}.${payload}`); + const expectedSignature = base647.encode(sha2562.hmac(this.key, toSign)); + return `v1,${expectedSignature}`; + } + verifyTimestamp(timestampHeader) { + const now = Math.floor(Date.now() / 1000); + const timestamp = parseInt(timestampHeader, 10); + if (isNaN(timestamp)) { + throw new WebhookVerificationError("Invalid Signature Headers"); + } + if (now - timestamp > WEBHOOK_TOLERANCE_IN_SECONDS) { + throw new WebhookVerificationError("Message timestamp too old"); + } + if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) { + throw new WebhookVerificationError("Message timestamp too new"); + } + return new Date(timestamp * 1000); + } + } + exports.Webhook = Webhook; + Webhook.prefix = "whsec_"; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/webhooks.mjs +var import_standardwebhooks, Webhooks; +var init_webhooks = __esm(() => { + import_standardwebhooks = __toESM(require_dist4(), 1); + Webhooks = class Webhooks extends APIResource { + unwrap(body, { headers, key }) { + if (headers !== undefined) { + const keyStr = key === undefined ? this._client.webhookKey : key; + if (keyStr === null) + throw new Error("Webhook key must not be null in order to unwrap"); + const wh = new import_standardwebhooks.Webhook(keyStr); + wh.verify(body, headers); + } + return JSON.parse(body); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs +var Versions; +var init_versions3 = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Versions = class Versions extends APIResource { + list(agentID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/agents/${agentID}/versions?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs +var Agents; +var init_agents3 = __esm(() => { + init_versions3(); + init_versions3(); + init_pagination(); + init_headers(); + init_path(); + Agents = class Agents extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions(this._client); + } + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/agents?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(agentID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.get(path3`/v1/agents/${agentID}?beta=true`, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(agentID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/agents/${agentID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/agents?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(agentID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/agents/${agentID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; + Agents.Versions = Versions; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs +var Memories; +var init_memories = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Memories = class Memories extends APIResource { + create(memoryStoreID, params, options) { + const { view: view3, betas, ...body } = params; + return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, { + query: { view: view3 }, + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(memoryID, params, options) { + const { memory_store_id, betas, ...query4 } = params; + return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(memoryID, params, options) { + const { memory_store_id, view: view3, betas, ...body } = params; + return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query: { view: view3 }, + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(memoryStoreID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(memoryID, params, options) { + const { memory_store_id, expected_content_sha256, betas } = params; + return this._client.delete(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, { + query: { expected_content_sha256 }, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs +var MemoryVersions; +var init_memory_versions = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + MemoryVersions = class MemoryVersions extends APIResource { + retrieve(memoryVersionID, params, options) { + const { memory_store_id, betas, ...query4 } = params; + return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(memoryStoreID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + redact(memoryVersionID, params, options) { + const { memory_store_id, betas } = params; + return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs +var MemoryStores; +var init_memory_stores = __esm(() => { + init_memories(); + init_memories(); + init_memory_versions(); + init_memory_versions(); + init_pagination(); + init_headers(); + init_path(); + MemoryStores = class MemoryStores extends APIResource { + constructor() { + super(...arguments); + this.memories = new Memories(this._client); + this.memoryVersions = new MemoryVersions(this._client); + } + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/memory_stores?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(memoryStoreID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/memory_stores?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(memoryStoreID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; + MemoryStores.Memories = Memories; + MemoryStores.MemoryVersions = MemoryVersions; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/error.mjs +var init_error6 = __esm(() => { + init_error5(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs +var JSONLDecoder; +var init_jsonl = __esm(() => { + init_error5(); + init_line(); + JSONLDecoder = class JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async* decoder() { + const lineDecoder = new LineDecoder; + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); + } + } + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); + } + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new AnthropicError(`Attempted to iterate over a response with no body`); + } + return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +var Batches; +var init_batches = __esm(() => { + init_pagination(); + init_headers(); + init_jsonl(); + init_error6(); + init_path(); + Batches = class Batches extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/messages/batches?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/messages/batches?beta=true", Page, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + const { betas } = params ?? {}; + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([ + { + "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), + Accept: "application/binary" + }, + options?.headers + ]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/internal/constants.mjs +var MODEL_NONSTREAMING_TOKENS; +var init_constants8 = __esm(() => { + MODEL_NONSTREAMING_TOKENS = { + "claude-opus-4-20250514": 8192, + "claude-opus-4-0": 8192, + "claude-4-opus-20250514": 8192, + "anthropic.claude-opus-4-20250514-v1:0": 8192, + "claude-opus-4@20250514": 8192, + "claude-opus-4-1-20250805": 8192, + "anthropic.claude-opus-4-1-20250805-v1:0": 8192, + "claude-opus-4-1@20250805": 8192 + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs +function getOutputFormat(params) { + return params?.output_format ?? params?.output_config?.format; +} +function maybeParseBetaMessage(message, params, opts) { + const outputFormat = getOutputFormat(params); + if (!params || !("parse" in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") { + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return null; + }, + enumerable: false + }); + } + return block; + }), + parsed_output: null + }; + } + return parseBetaMessage(message, params, opts); +} +function parseBetaMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseBetaOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return parsedOutput; + }, + enumerable: false + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseBetaOutputFormat(params, content) { + const outputFormat = getOutputFormat(params); + if (outputFormat?.type !== "json_schema") { + return null; + } + try { + if ("parse" in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } catch (error91) { + throw new AnthropicError(`Failed to parse structured output: ${error91}`); + } +} +var init_beta_parser = __esm(() => { + init_error5(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +var tokenize = (input) => { + let current = 0; + let tokens = []; + while (current < input.length) { + let char = input[current]; + if (char === "\\") { + current++; + continue; + } + if (char === "{") { + tokens.push({ + type: "brace", + value: "{" + }); + current++; + continue; + } + if (char === "}") { + tokens.push({ + type: "brace", + value: "}" + }); + current++; + continue; + } + if (char === "[") { + tokens.push({ + type: "paren", + value: "[" + }); + current++; + continue; + } + if (char === "]") { + tokens.push({ + type: "paren", + value: "]" + }); + current++; + continue; + } + if (char === ":") { + tokens.push({ + type: "separator", + value: ":" + }); + current++; + continue; + } + if (char === ",") { + tokens.push({ + type: "delimiter", + value: "," + }); + current++; + continue; + } + if (char === '"') { + let value = ""; + let danglingQuote = false; + char = input[++current]; + while (char !== '"') { + if (current === input.length) { + danglingQuote = true; + break; + } + if (char === "\\") { + current++; + if (current === input.length) { + danglingQuote = true; + break; + } + value += char + input[current]; + char = input[++current]; + } else { + value += char; + char = input[++current]; + } + } + char = input[++current]; + if (!danglingQuote) { + tokens.push({ + type: "string", + value + }); + } + continue; + } + let WHITESPACE = /\s/; + if (char && WHITESPACE.test(char)) { + current++; + continue; + } + let NUMBERS = /[0-9]/; + if (char && NUMBERS.test(char) || char === "-" || char === ".") { + let value = ""; + if (char === "-") { + value += char; + char = input[++current]; + } + while (char && NUMBERS.test(char) || char === ".") { + value += char; + char = input[++current]; + } + tokens.push({ + type: "number", + value + }); + continue; + } + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ""; + while (char && LETTERS.test(char)) { + if (current === input.length) { + break; + } + value += char; + char = input[++current]; + } + if (value == "true" || value == "false" || value === "null") { + tokens.push({ + type: "name", + value + }); + } else { + current++; + continue; + } + continue; + } + current++; + } + return tokens; +}, strip2 = (tokens) => { + if (tokens.length === 0) { + return tokens; + } + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case "separator": + tokens = tokens.slice(0, tokens.length - 1); + return strip2(tokens); + break; + case "number": + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") { + tokens = tokens.slice(0, tokens.length - 1); + return strip2(tokens); + } + case "string": + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === "delimiter") { + tokens = tokens.slice(0, tokens.length - 1); + return strip2(tokens); + } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") { + tokens = tokens.slice(0, tokens.length - 1); + return strip2(tokens); + } + break; + case "delimiter": + tokens = tokens.slice(0, tokens.length - 1); + return strip2(tokens); + break; + } + return tokens; +}, unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === "brace") { + if (token.value === "{") { + tail.push("}"); + } else { + tail.splice(tail.lastIndexOf("}"), 1); + } + } + if (token.type === "paren") { + if (token.value === "[") { + tail.push("]"); + } else { + tail.splice(tail.lastIndexOf("]"), 1); + } + } + }); + if (tail.length > 0) { + tail.reverse().map((item) => { + if (item === "}") { + tokens.push({ + type: "brace", + value: "}" + }); + } else if (item === "]") { + tokens.push({ + type: "paren", + value: "]" + }); + } + }); + } + return tokens; +}, generate = (tokens) => { + let output = ""; + tokens.map((token) => { + switch (token.type) { + case "string": + output += '"' + token.value + '"'; + break; + default: + output += token.value; + break; + } + }); + return output; +}, partialParse = (input) => JSON.parse(generate(unstrip(strip2(tokenize(input))))); +var init_parser = () => {}; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/streaming.mjs +var init_streaming2 = __esm(() => { + init_streaming(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +function tracksToolInput(content) { + return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use"; +} +function checkNever(x) {} +var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY = "__json_buf", BetaMessageStream; +var init_BetaMessageStream = __esm(() => { + init_tslib(); + init_parser(); + init_error6(); + init_streaming2(); + init_beta_parser(); + BetaMessageStream = class BetaMessageStream { + constructor(params, opts) { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, undefined); + _BetaMessageStream_params.set(this, null); + this.controller = new AbortController; + _BetaMessageStream_connectedPromise.set(this, undefined); + _BetaMessageStream_resolveConnectedPromise.set(this, () => {}); + _BetaMessageStream_rejectConnectedPromise.set(this, () => {}); + _BetaMessageStream_endPromise.set(this, undefined); + _BetaMessageStream_resolveEndPromise.set(this, () => {}); + _BetaMessageStream_rejectEndPromise.set(this, () => {}); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, undefined); + _BetaMessageStream_request_id.set(this, undefined); + _BetaMessageStream_logger.set(this, undefined); + _BetaMessageStream_handleError.set(this, (error91) => { + __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (isAbortError(error91)) { + error91 = new APIUserAbortError; + } + if (error91 instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit("abort", error91); + } + if (error91 instanceof AnthropicError) { + return this._emit("error", error91); + } + if (error91 instanceof Error) { + const anthropicError = new AnthropicError(error91.message); + anthropicError.cause = error91; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error91))); + }); + __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve2, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve2, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => {}); + __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => {}); + __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + } + async withResponse() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) { + throw new Error("Could not resolve a `Response` object"); + } + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + static fromReadableStream(stream2) { + const runner = new BetaMessageStream(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new BetaMessageStream(params, { logger }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit("message", message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); + this._connected(response); + for await (const event of stream2) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError; + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index2 = listeners.findIndex((l) => l.listener === listener); + if (index2 >= 0) + listeners.splice(index2, 1); + return this; + } + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + emitted(event) { + return new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") + this.once("error", reject); + this.once(event, resolve2); + }); + } + async done() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + return; + if (event === "end") { + __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error91 = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error91); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error91); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error91); + this._emit("end"); + return; + } + if (event === "error") { + const error91 = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error91); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error91); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error91); + this._emit("end"); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream2 = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream2) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError; + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + [(_BetaMessageStream_currentMessageSnapshot = new WeakMap, _BetaMessageStream_params = new WeakMap, _BetaMessageStream_connectedPromise = new WeakMap, _BetaMessageStream_resolveConnectedPromise = new WeakMap, _BetaMessageStream_rejectConnectedPromise = new WeakMap, _BetaMessageStream_endPromise = new WeakMap, _BetaMessageStream_resolveEndPromise = new WeakMap, _BetaMessageStream_rejectEndPromise = new WeakMap, _BetaMessageStream_listeners = new WeakMap, _BetaMessageStream_ended = new WeakMap, _BetaMessageStream_errored = new WeakMap, _BetaMessageStream_aborted = new WeakMap, _BetaMessageStream_catchingPromiseCreated = new WeakMap, _BetaMessageStream_response = new WeakMap, _BetaMessageStream_request_id = new WeakMap, _BetaMessageStream_logger = new WeakMap, _BetaMessageStream_handleError = new WeakMap, _BetaMessageStream_instances = new WeakSet, _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError("stream ended without producing a content block with type=text"); + } + return textBlocks.join(" "); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": { + if (content.type === "text") { + this._emit("text", event.delta.text, content.text || ""); + } + break; + } + case "citations_delta": { + if (content.type === "text") { + this._emit("citation", event.delta.citation, content.citations ?? []); + } + break; + } + case "input_json_delta": { + if (tracksToolInput(content) && content.input) { + this._emit("inputJson", event.delta.partial_json, content.input); + } + break; + } + case "thinking_delta": { + if (content.type === "thinking") { + this._emit("thinking", event.delta.thinking, content.thinking); + } + break; + } + case "signature_delta": { + if (content.type === "thinking") { + this._emit("signature", content.signature); + } + break; + } + case "compaction_delta": { + if (content.type === "compaction" && content.content) { + this._emit("compaction", content.content); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case "message_stop": { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + break; + } + case "content_block_stop": { + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + } + case "message_start": { + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case "content_block_start": + case "message_delta": + break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) { + let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case "message_stop": + return snapshot; + case "message_delta": + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + snapshot.context_management = event.context_management; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + if (event.usage.iterations != null) { + snapshot.usage.iterations = event.usage.iterations; + } + return snapshot; + case "content_block_start": + snapshot.content.push(event.content_block); + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + } + break; + } + case "citations_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + } + break; + } + case "input_json_delta": { + if (snapshotContent && tracksToolInput(snapshotContent)) { + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ""; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true + }); + if (jsonBuf) { + try { + newContent.input = partialParse(jsonBuf); + } catch (err) { + const error91 = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error91); + } + } + snapshot.content[event.index] = newContent; + } + break; + } + case "thinking_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + } + break; + } + case "signature_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + } + break; + } + case "compaction_delta": { + if (snapshotContent?.type === "compaction") { + snapshot.content[event.index] = { + ...snapshotContent, + content: (snapshotContent.content || "") + event.delta.content + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; + } + case "content_block_stop": + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + } + }; + } + toReadableStream() { + const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs +var ToolError; +var init_ToolError = __esm(() => { + ToolError = class ToolError extends Error { + constructor(content) { + const message = typeof content === "string" ? content : content.map((block) => { + if (block.type === "text") + return block.text; + return `[${block.type}]`; + }).join(" "); + super(message); + this.name = "ToolError"; + this.content = content; + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs +var DEFAULT_TOKEN_THRESHOLD = 1e5, DEFAULT_SUMMARY_PROMPT3 = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.`; + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs +function promiseWithResolvers() { + let resolve2; + let reject; + const promise3 = new Promise((res, rej) => { + resolve2 = res; + reject = rej; + }); + return { promise: promise3, resolve: resolve2, reject }; +} +async function generateToolResponse(params, lastMessage = params.messages.at(-1), requestOptions) { + if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") { + return null; + } + const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use"); + if (toolUseBlocks.length === 0) { + return null; + } + const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { + const tool2 = params.tools.find((t) => ("name" in t ? t.name : t.mcp_server_name) === toolUse.name); + if (!tool2 || !("run" in tool2)) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: `Error: Tool '${toolUse.name}' not found`, + is_error: true + }; + } + try { + let input = toolUse.input; + if ("parse" in tool2 && tool2.parse) { + input = tool2.parse(input); + } + const result = await tool2.run(input, { + toolUseBlock: toolUse, + signal: requestOptions?.signal + }); + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: result + }; + } catch (error91) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: error91 instanceof ToolError ? error91.content : `Error: ${error91 instanceof Error ? error91.message : String(error91)}`, + is_error: true + }; + } + })); + return { + role: "user", + content: toolResults + }; +} +var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse, BetaToolRunner; +var init_BetaToolRunner = __esm(() => { + init_tslib(); + init_ToolError(); + init_error5(); + init_headers(); + init_stainless_helper_header(); + BetaToolRunner = class BetaToolRunner { + constructor(client2, params, options) { + _BetaToolRunner_instances.add(this); + this.client = client2; + _BetaToolRunner_consumed.set(this, false); + _BetaToolRunner_mutated.set(this, false); + _BetaToolRunner_state.set(this, undefined); + _BetaToolRunner_options.set(this, undefined); + _BetaToolRunner_message.set(this, undefined); + _BetaToolRunner_toolResponse.set(this, undefined); + _BetaToolRunner_completion.set(this, undefined); + _BetaToolRunner_iterationCount.set(this, 0); + __classPrivateFieldSet(this, _BetaToolRunner_state, { + params: { + ...params, + messages: structuredClone(params.messages) + } + }, "f"); + const helpers = collectStainlessHelpers(params.tools, params.messages); + const helperValue = ["BetaToolRunner", ...helpers].join(", "); + __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...options, + headers: buildHeaders([{ "x-stainless-helper": helperValue }, options?.headers]) + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + if (params.compactionControl?.enabled) { + console.warn("Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. " + 'Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. ' + "See https://platform.claude.com/docs/en/build-with-claude/compaction"); + } + } + async* [(_BetaToolRunner_consumed = new WeakMap, _BetaToolRunner_mutated = new WeakMap, _BetaToolRunner_state = new WeakMap, _BetaToolRunner_options = new WeakMap, _BetaToolRunner_message = new WeakMap, _BetaToolRunner_toolResponse = new WeakMap, _BetaToolRunner_completion = new WeakMap, _BetaToolRunner_iterationCount = new WeakMap, _BetaToolRunner_instances = new WeakSet, _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact2() { + const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; + if (!compactionControl || !compactionControl.enabled) { + return false; + } + let tokensUsed = 0; + if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) { + try { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0); + tokensUsed = totalInputTokens + message.usage.output_tokens; + } catch { + return false; + } + } + const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; + if (tokensUsed < threshold) { + return false; + } + const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; + const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT3; + const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; + if (messages[messages.length - 1].role === "assistant") { + const lastMessage = messages[messages.length - 1]; + if (Array.isArray(lastMessage.content)) { + const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use"); + if (nonToolBlocks.length === 0) { + messages.pop(); + } else { + lastMessage.content = nonToolBlocks; + } + } + } + const response = await this.client.beta.messages.create({ + model, + messages: [ + ...messages, + { + role: "user", + content: [ + { + type: "text", + text: summaryPrompt + } + ] + } + ], + max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens + }, { + signal: __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal, + headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, { "x-stainless-helper": "compaction" }]) + }); + if (response.content[0]?.type !== "text") { + throw new AnthropicError("Expected text response for compaction"); + } + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ + { + role: "user", + content: response.content + } + ]; + return true; + }, Symbol.asyncIterator)]() { + var _a3; + if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + throw new AnthropicError("Cannot iterate over a consumed stream"); + } + __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + try { + while (true) { + let stream2; + try { + if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { + break; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a3 = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a3++, _a3), "f"); + __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); + const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + if (params.stream) { + stream2 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); + __classPrivateFieldSet(this, _BetaToolRunner_message, stream2.finalMessage(), "f"); + __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => {}); + yield stream2; + } else { + __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + } + const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); + if (!isCompacted) { + if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); + } + const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); + if (toolMessage) { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); + } else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + break; + } + } + } finally { + if (stream2) { + stream2.abort(); + } + } + } + if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { + throw new AnthropicError("ToolRunner concluded without a message from the server"); + } + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); + } catch (error91) { + __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => {}); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error91); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + throw error91; + } + } + setMessagesParams(paramsOrMutator) { + if (typeof paramsOrMutator === "function") { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); + } else { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + } + setRequestOptions(optionsOrMutator) { + if (typeof optionsOrMutator === "function") { + __classPrivateFieldSet(this, _BetaToolRunner_options, optionsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + } else { + __classPrivateFieldSet(this, _BetaToolRunner_options, { ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), ...optionsOrMutator }, "f"); + } + } + async generateToolResponse(signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1); + if (!message) { + return null; + } + return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message, signal); + } + done() { + return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + } + async runUntilDone() { + if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + for await (const _ of this) {} + } + return this.done(); + } + get params() { + return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + } + pushMessages(...messages) { + this.setMessagesParams((params) => ({ + ...params, + messages: [...params.messages, ...messages] + })); + } + then(onfulfilled, onrejected) { + return this.runUntilDone().then(onfulfilled, onrejected); + } + }; + _BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage, signal = __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal) { + if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + } + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage, { + ...__classPrivateFieldGet(this, _BetaToolRunner_options, "f"), + signal + }), "f"); + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs +function transformOutputFormat(params) { + if (!params.output_format) { + return params; + } + if (params.output_config?.format) { + throw new AnthropicError("Both output_format and output_config.format were provided. " + "Please use only output_config.format (output_format is deprecated)."); + } + const { output_format, ...rest } = params; + return { + ...rest, + output_config: { + ...params.output_config, + format: output_format + } + }; +} +var DEPRECATED_MODELS, MODELS_TO_WARN_WITH_THINKING_ENABLED, Messages; +var init_messages11 = __esm(() => { + init_error6(); + init_batches(); + init_constants8(); + init_headers(); + init_stainless_helper_header(); + init_beta_parser(); + init_BetaMessageStream(); + init_BetaToolRunner(); + init_ToolError(); + init_batches(); + init_BetaToolRunner(); + init_ToolError(); + DEPRECATED_MODELS = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026" + }; + MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-mythos-preview", "claude-opus-4-6"]; + Messages = class Messages extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches(this._client); + } + create(params, options) { + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]} +Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) && body.thinking && body.thinking.type === "enabled") { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages?beta=true", { + body, + timeout: timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + helperHeader, + options?.headers + ]), + stream: modifiedParams.stream ?? false + }); + } + parse(params, options) { + options = { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() }, + options?.headers + ]) + }; + return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + } + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); + } + countTokens(params, options) { + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + return this._client.post("/v1/messages/count_tokens?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() }, + options?.headers + ]) + }); + } + toolRunner(body, options) { + return new BetaToolRunner(this._client, body, options); + } + }; + Messages.Batches = Batches; + Messages.BetaToolRunner = BetaToolRunner; + Messages.ToolError = ToolError; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs +var Events; +var init_events = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Events = class Events extends APIResource { + list(sessionID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/sessions/${sessionID}/events?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + send(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/sessions/${sessionID}/events?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + stream(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/sessions/${sessionID}/events/stream?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]), + stream: true + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs +var Resources; +var init_resources = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Resources = class Resources extends APIResource { + retrieve(resourceID, params, options) { + const { session_id, betas } = params; + return this._client.get(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(resourceID, params, options) { + const { session_id, betas, ...body } = params; + return this._client.post(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(sessionID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/sessions/${sessionID}/resources?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(resourceID, params, options) { + const { session_id, betas } = params; + return this._client.delete(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + add(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/sessions/${sessionID}/resources?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/events.mjs +var Events2; +var init_events2 = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Events2 = class Events2 extends APIResource { + list(threadID, params, options) { + const { session_id, betas, ...query4 } = params; + return this._client.getAPIList(path3`/v1/sessions/${session_id}/threads/${threadID}/events?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + stream(threadID, params, options) { + const { session_id, betas } = params; + return this._client.get(path3`/v1/sessions/${session_id}/threads/${threadID}/stream?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]), + stream: true + }); + } + }; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/threads.mjs +var Threads; +var init_threads2 = __esm(() => { + init_events2(); + init_events2(); + init_pagination(); + init_headers(); + init_path(); + Threads = class Threads extends APIResource { + constructor() { + super(...arguments); + this.events = new Events2(this._client); + } + retrieve(threadID, params, options) { + const { session_id, betas } = params; + return this._client.get(path3`/v1/sessions/${session_id}/threads/${threadID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(sessionID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/sessions/${sessionID}/threads?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(threadID, params, options) { + const { session_id, betas } = params; + return this._client.post(path3`/v1/sessions/${session_id}/threads/${threadID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; + Threads.Events = Events2; +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs +var Sessions; +var init_sessions = __esm(() => { + init_events(); + init_events(); + init_resources(); + init_resources(); + init_threads2(); + init_threads2(); + init_pagination(); + init_headers(); + init_path(); + Sessions = class Sessions extends APIResource { + constructor() { + super(...arguments); + this.events = new Events(this._client); + this.resources = new Resources(this._client); + this.threads = new Threads(this._client); + } + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/sessions?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/sessions/${sessionID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) }); - }; - inst.exclude = (values2, params) => { - const newEntries = { ...def.entries }; - for (const value of values2) { - if (keys.has(value)) { - delete newEntries[value]; - } else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum3({ - ...def, - checks: [], - ...exports_util2.normalizeParams(params), - entries: newEntries + } + update(sessionID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/sessions/${sessionID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) }); - }; - }); - ZodLiteral3 = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => { - $ZodLiteral2.init(inst, def); - ZodType3.init(inst, def); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - } - }); - }); - ZodFile2 = /* @__PURE__ */ $constructor2("ZodFile", (inst, def) => { - $ZodFile2.init(inst, def); - ZodType3.init(inst, def); - inst.min = (size, params) => inst.check(_minSize2(size, params)); - inst.max = (size, params) => inst.check(_maxSize2(size, params)); - inst.mime = (types3, params) => inst.check(_mime2(Array.isArray(types3) ? types3 : [types3], params)); - }); - ZodTransform2 = /* @__PURE__ */ $constructor2("ZodTransform", (inst, def) => { - $ZodTransform2.init(inst, def); - ZodType3.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.addIssue = (issue3) => { - if (typeof issue3 === "string") { - payload.issues.push(exports_util2.issue(issue3, payload.value, def)); - } else { - const _issue = issue3; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - _issue.continue ?? (_issue.continue = true); - payload.issues.push(exports_util2.issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - return payload; - }); - } - payload.value = output; - return payload; - }; - }); - ZodOptional3 = /* @__PURE__ */ $constructor2("ZodOptional", (inst, def) => { - $ZodOptional2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNullable3 = /* @__PURE__ */ $constructor2("ZodNullable", (inst, def) => { - $ZodNullable2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodDefault3 = /* @__PURE__ */ $constructor2("ZodDefault", (inst, def) => { - $ZodDefault2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; - }); - ZodPrefault2 = /* @__PURE__ */ $constructor2("ZodPrefault", (inst, def) => { - $ZodPrefault2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodNonOptional2 = /* @__PURE__ */ $constructor2("ZodNonOptional", (inst, def) => { - $ZodNonOptional2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodSuccess2 = /* @__PURE__ */ $constructor2("ZodSuccess", (inst, def) => { - $ZodSuccess2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodCatch3 = /* @__PURE__ */ $constructor2("ZodCatch", (inst, def) => { - $ZodCatch2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; - }); - ZodNaN3 = /* @__PURE__ */ $constructor2("ZodNaN", (inst, def) => { - $ZodNaN2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodPipe2 = /* @__PURE__ */ $constructor2("ZodPipe", (inst, def) => { - $ZodPipe2.init(inst, def); - ZodType3.init(inst, def); - inst.in = def.in; - inst.out = def.out; - }); - ZodReadonly3 = /* @__PURE__ */ $constructor2("ZodReadonly", (inst, def) => { - $ZodReadonly2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral2.init(inst, def); - ZodType3.init(inst, def); - }); - ZodLazy3 = /* @__PURE__ */ $constructor2("ZodLazy", (inst, def) => { - $ZodLazy2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.getter(); - }); - ZodPromise3 = /* @__PURE__ */ $constructor2("ZodPromise", (inst, def) => { - $ZodPromise2.init(inst, def); - ZodType3.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - }); - ZodCustom2 = /* @__PURE__ */ $constructor2("ZodCustom", (inst, def) => { - $ZodCustom2.init(inst, def); - ZodType3.init(inst, def); - }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/sessions?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/sessions/${sessionID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(sessionID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/sessions/${sessionID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; + Sessions.Events = Events; + Sessions.Resources = Resources; + Sessions.Threads = Threads; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/compat.js -function setErrorMap3(map3) { - config2({ - customError: map3 - }); -} -function getErrorMap3() { - return config2().customError; -} -var ZodIssueCode3; -var init_compat3 = __esm(() => { - init_core5(); - ZodIssueCode3 = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom" +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs +var Versions2; +var init_versions4 = __esm(() => { + init_pagination(); + init_headers(); + init_uploads(); + init_path(); + Versions2 = class Versions2 extends APIResource { + create(skillID, params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post(path3`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }, this._client)); + } + retrieve(version6, params, options) { + const { skill_id, betas } = params; + return this._client.get(path3`/v1/skills/${skill_id}/versions/${version6}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + list(skillID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/skills/${skillID}/versions?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + delete(version6, params, options) { + const { skill_id, betas } = params; + return this._client.delete(path3`/v1/skills/${skill_id}/versions/${version6}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } }; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/coerce.js -var exports_coerce2 = {}; -__export(exports_coerce2, { - string: () => string6, - number: () => number6, - date: () => date9, - boolean: () => boolean6, - bigint: () => bigint6 -}); -function string6(params) { - return _coercedString2(ZodString3, params); -} -function number6(params) { - return _coercedNumber2(ZodNumber3, params); -} -function boolean6(params) { - return _coercedBoolean2(ZodBoolean3, params); -} -function bigint6(params) { - return _coercedBigint2(ZodBigInt3, params); -} -function date9(params) { - return _coercedDate2(ZodDate3, params); -} -var init_coerce2 = __esm(() => { - init_core5(); - init_schemas4(); +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs +var Skills; +var init_skills = __esm(() => { + init_versions4(); + init_versions4(); + init_pagination(); + init_headers(); + init_uploads(); + init_path(); + Skills = class Skills extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions2(this._client); + } + create(params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }, this._client, false)); + } + retrieve(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/skills?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + delete(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + }; + Skills.Versions = Versions2; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js -var exports_external3 = {}; -__export(exports_external3, { - xid: () => xid4, - void: () => _void4, - uuidv7: () => uuidv72, - uuidv6: () => uuidv62, - uuidv4: () => uuidv42, - uuid: () => uuid11, - url: () => url2, - uppercase: () => _uppercase2, - unknown: () => unknown2, - union: () => union2, - undefined: () => _undefined6, - ulid: () => ulid4, - uint64: () => uint642, - uint32: () => uint322, - tuple: () => tuple2, - trim: () => _trim2, - treeifyError: () => treeifyError2, - transform: () => transform2, - toUpperCase: () => _toUpperCase2, - toLowerCase: () => _toLowerCase2, - toJSONSchema: () => toJSONSchema2, - templateLiteral: () => templateLiteral2, - symbol: () => symbol2, - superRefine: () => superRefine2, - success: () => success2, - stringbool: () => stringbool2, - stringFormat: () => stringFormat2, - string: () => string5, - strictObject: () => strictObject2, - startsWith: () => _startsWith2, - size: () => _size2, - setErrorMap: () => setErrorMap3, - set: () => set2, - safeParseAsync: () => safeParseAsync4, - safeParse: () => safeParse4, - registry: () => registry3, - regexes: () => exports_regexes2, - regex: () => _regex2, - refine: () => refine2, - record: () => record2, - readonly: () => readonly2, - property: () => _property2, - promise: () => promise2, - prettifyError: () => prettifyError2, - preprocess: () => preprocess2, - prefault: () => prefault2, - positive: () => _positive2, - pipe: () => pipe2, - partialRecord: () => partialRecord2, - parseAsync: () => parseAsync4, - parse: () => parse13, - overwrite: () => _overwrite2, - optional: () => optional2, - object: () => object2, - number: () => number5, - nullish: () => nullish4, - nullable: () => nullable2, - null: () => _null6, - normalize: () => _normalize2, - nonpositive: () => _nonpositive2, - nonoptional: () => nonoptional2, - nonnegative: () => _nonnegative2, - never: () => never2, - negative: () => _negative2, - nativeEnum: () => nativeEnum2, - nanoid: () => nanoid4, - nan: () => nan2, - multipleOf: () => _multipleOf2, - minSize: () => _minSize2, - minLength: () => _minLength2, - mime: () => _mime2, - maxSize: () => _maxSize2, - maxLength: () => _maxLength2, - map: () => map2, - lte: () => _lte2, - lt: () => _lt2, - lowercase: () => _lowercase2, - looseObject: () => looseObject2, - locales: () => exports_locales2, - literal: () => literal2, - length: () => _length2, - lazy: () => lazy2, - ksuid: () => ksuid4, - keyof: () => keyof2, - jwt: () => jwt2, - json: () => json2, - iso: () => exports_iso2, - ipv6: () => ipv64, - ipv4: () => ipv44, - intersection: () => intersection2, - int64: () => int642, - int32: () => int322, - int: () => int2, - instanceof: () => _instanceof2, - includes: () => _includes2, - guid: () => guid4, - gte: () => _gte2, - gt: () => _gt2, - globalRegistry: () => globalRegistry2, - getErrorMap: () => getErrorMap3, - function: () => _function2, - formatError: () => formatError3, - float64: () => float642, - float32: () => float322, - flattenError: () => flattenError2, - file: () => file2, - enum: () => _enum4, - endsWith: () => _endsWith2, - emoji: () => emoji4, - email: () => email4, - e164: () => e1644, - discriminatedUnion: () => discriminatedUnion2, - date: () => date8, - custom: () => custom3, - cuid2: () => cuid24, - cuid: () => cuid6, - core: () => exports_core4, - config: () => config2, - coerce: () => exports_coerce2, - clone: () => clone2, - cidrv6: () => cidrv64, - cidrv4: () => cidrv44, - check: () => check2, - catch: () => _catch4, - boolean: () => boolean5, - bigint: () => bigint5, - base64url: () => base64url4, - base64: () => base646, - array: () => array2, - any: () => any2, - _default: () => _default5, - _ZodString: () => _ZodString2, - ZodXID: () => ZodXID2, - ZodVoid: () => ZodVoid3, - ZodUnknown: () => ZodUnknown3, - ZodUnion: () => ZodUnion3, - ZodUndefined: () => ZodUndefined3, - ZodUUID: () => ZodUUID2, - ZodURL: () => ZodURL2, - ZodULID: () => ZodULID2, - ZodType: () => ZodType3, - ZodTuple: () => ZodTuple3, - ZodTransform: () => ZodTransform2, - ZodTemplateLiteral: () => ZodTemplateLiteral2, - ZodSymbol: () => ZodSymbol3, - ZodSuccess: () => ZodSuccess2, - ZodStringFormat: () => ZodStringFormat2, - ZodString: () => ZodString3, - ZodSet: () => ZodSet3, - ZodRecord: () => ZodRecord3, - ZodRealError: () => ZodRealError2, - ZodReadonly: () => ZodReadonly3, - ZodPromise: () => ZodPromise3, - ZodPrefault: () => ZodPrefault2, - ZodPipe: () => ZodPipe2, - ZodOptional: () => ZodOptional3, - ZodObject: () => ZodObject3, - ZodNumberFormat: () => ZodNumberFormat2, - ZodNumber: () => ZodNumber3, - ZodNullable: () => ZodNullable3, - ZodNull: () => ZodNull3, - ZodNonOptional: () => ZodNonOptional2, - ZodNever: () => ZodNever3, - ZodNanoID: () => ZodNanoID2, - ZodNaN: () => ZodNaN3, - ZodMap: () => ZodMap3, - ZodLiteral: () => ZodLiteral3, - ZodLazy: () => ZodLazy3, - ZodKSUID: () => ZodKSUID2, - ZodJWT: () => ZodJWT2, - ZodIssueCode: () => ZodIssueCode3, - ZodIntersection: () => ZodIntersection3, - ZodISOTime: () => ZodISOTime2, - ZodISODuration: () => ZodISODuration2, - ZodISODateTime: () => ZodISODateTime2, - ZodISODate: () => ZodISODate2, - ZodIPv6: () => ZodIPv62, - ZodIPv4: () => ZodIPv42, - ZodGUID: () => ZodGUID2, - ZodFile: () => ZodFile2, - ZodError: () => ZodError4, - ZodEnum: () => ZodEnum3, - ZodEmoji: () => ZodEmoji2, - ZodEmail: () => ZodEmail2, - ZodE164: () => ZodE1642, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion3, - ZodDefault: () => ZodDefault3, - ZodDate: () => ZodDate3, - ZodCustomStringFormat: () => ZodCustomStringFormat2, - ZodCustom: () => ZodCustom2, - ZodCatch: () => ZodCatch3, - ZodCUID2: () => ZodCUID22, - ZodCUID: () => ZodCUID3, - ZodCIDRv6: () => ZodCIDRv62, - ZodCIDRv4: () => ZodCIDRv42, - ZodBoolean: () => ZodBoolean3, - ZodBigIntFormat: () => ZodBigIntFormat2, - ZodBigInt: () => ZodBigInt3, - ZodBase64URL: () => ZodBase64URL2, - ZodBase64: () => ZodBase642, - ZodArray: () => ZodArray3, - ZodAny: () => ZodAny3, - TimePrecision: () => TimePrecision2, - NEVER: () => NEVER3, - $output: () => $output2, - $input: () => $input2, - $brand: () => $brand2 +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs +var Credentials; +var init_credentials2 = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Credentials = class Credentials extends APIResource { + create(vaultID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/vaults/${vaultID}/credentials?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.get(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(credentialID, params, options) { + const { vault_id, betas, ...body } = params; + return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(vaultID, params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList(path3`/v1/vaults/${vaultID}/credentials?beta=true`, PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.delete(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + mcpOAuthValidate(credentialID, params, options) { + const { vault_id, betas } = params; + return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}/mcp_oauth_validate?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; }); -var init_external3 = __esm(() => { - init_core5(); - init_core5(); - init_en3(); - init_core5(); - init_locales2(); - init_iso2(); - init_iso2(); - init_coerce2(); - init_schemas4(); - init_checks4(); - init_errors12(); - init_parse7(); - init_compat3(); - config2(en_default3()); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs +var Vaults; +var init_vaults = __esm(() => { + init_credentials2(); + init_credentials2(); + init_pagination(); + init_headers(); + init_path(); + Vaults = class Vaults extends APIResource { + constructor() { + super(...arguments); + this.credentials = new Credentials(this._client); + } + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/vaults?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + retrieve(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/vaults/${vaultID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + update(vaultID, params, options) { + const { betas, ...body } = params; + return this._client.post(path3`/v1/vaults/${vaultID}?beta=true`, { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/vaults?beta=true", PageCursor, { + query: query4, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + delete(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path3`/v1/vaults/${vaultID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + archive(vaultID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path3`/v1/vaults/${vaultID}/archive?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() }, + options?.headers + ]) + }); + } + }; + Vaults.Credentials = Credentials; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/index.js -var init_classic2 = __esm(() => { - init_external3(); - init_external3(); +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +var Beta; +var init_beta = __esm(() => { + init_environments(); + init_environments(); + init_files(); + init_files(); + init_models(); + init_models(); + init_user_profiles(); + init_user_profiles(); + init_webhooks(); + init_webhooks(); + init_agents3(); + init_agents3(); + init_memory_stores(); + init_memory_stores(); + init_messages11(); + init_messages11(); + init_sessions(); + init_sessions(); + init_skills(); + init_skills(); + init_vaults(); + init_vaults(); + Beta = class Beta extends APIResource { + constructor() { + super(...arguments); + this.models = new Models(this._client); + this.messages = new Messages(this._client); + this.agents = new Agents(this._client); + this.environments = new Environments(this._client); + this.sessions = new Sessions(this._client); + this.vaults = new Vaults(this._client); + this.memoryStores = new MemoryStores(this._client); + this.files = new Files(this._client); + this.skills = new Skills(this._client); + this.webhooks = new Webhooks(this._client); + this.userProfiles = new UserProfiles(this._client); + } + }; + Beta.Models = Models; + Beta.Messages = Messages; + Beta.Agents = Agents; + Beta.Environments = Environments; + Beta.Sessions = Sessions; + Beta.Vaults = Vaults; + Beta.MemoryStores = MemoryStores; + Beta.Files = Files; + Beta.Skills = Skills; + Beta.Webhooks = Webhooks; + Beta.UserProfiles = UserProfiles; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/index.js -var init_v44 = __esm(() => { - init_classic2(); +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/completions.mjs +var Completions; +var init_completions = __esm(() => { + init_headers(); + Completions = class Completions extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/complete", { + body, + timeout: this._client._options.timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + options?.headers + ]), + stream: params.stream ?? false + }); + } + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/graph.js -function isCompiledGraph2(x) { - return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; -} -function _escapeMermaidKeywords2(key) { - if (key === "subgraph") - return `"${key}"`; - return key; +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/parser.mjs +function getOutputFormat2(params) { + return params?.output_config?.format; } -var Branch2 = class { - path; - ends; - constructor(options) { - if (Runnable.isRunnable(options.path)) - this.path = options.path; - else - this.path = _coerceToRunnable(options.path); - this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n4) => { - acc[n4] = n4; - return acc; - }, {}) : options.pathMap; - } - run(writer2, reader) { - return ChannelWrite3.registerWriter(new RunnableCallable3({ - name: "", - trace: false, - func: async (input, config3) => { - try { - return await this._route(input, config3, writer2, reader); - } catch (e) { - if (e.name === NodeInterrupt2.unminifiable_name) - console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation. -NodeInterrupt should only be thrown inside a node, not in edge conditions.`); - throw e; +function maybeParseMessage(message, params, opts) { + const outputFormat = getOutputFormat2(params); + if (!params || !("parse" in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") { + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return parsedBlock; } - } - })); - } - async _route(input, config3, writer2, reader) { - let result = await this.path.invoke(reader ? reader(config3) : input, config3); - if (!Array.isArray(result)) - result = [result]; - let destinations; - if (this.ends) - destinations = result.map((r) => _isSend2(r) ? r : this.ends[r]); - else - destinations = result; - if (destinations.some((dest) => !dest)) - throw new Error("Branch condition returned unknown or null destination"); - if (destinations.filter(_isSend2).some((packet) => packet.node === "__end__")) - throw new InvalidUpdateError2("Cannot send a packet to the END node"); - return await writer2(destinations, config3) ?? input; - } -}, Graph$12 = class { - nodes; - edges; - branches; - entryPoint; - compiled = false; - constructor() { - this.nodes = {}; - this.edges = /* @__PURE__ */ new Set; - this.branches = {}; + return block; + }), + parsed_output: null + }; } - warnIfCompiled(message) { - if (this.compiled) - console.warn(message); + return parseMessage(message, params, opts); +} +function parseMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + return parsedBlock; + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseOutputFormat(params, content) { + const outputFormat = getOutputFormat2(params); + if (outputFormat?.type !== "json_schema") { + return null; } - get allEdges() { - return this.edges; + try { + if ("parse" in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } catch (error91) { + throw new AnthropicError(`Failed to parse structured output: ${error91}`); } - addNode(...args) { - function isMutlipleNodes(args2) { - return args2.length >= 1 && typeof args2[0] !== "string"; +} +var init_parser2 = __esm(() => { + init_error5(); +}); + +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +function tracksToolInput2(content) { + return content.type === "tool_use" || content.type === "server_tool_use"; +} +function checkNever2(x) {} +var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2 = "__json_buf", MessageStream; +var init_MessageStream = __esm(() => { + init_tslib(); + init_error6(); + init_streaming2(); + init_parser(); + init_parser2(); + MessageStream = class MessageStream { + constructor(params, opts) { + _MessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _MessageStream_currentMessageSnapshot.set(this, undefined); + _MessageStream_params.set(this, null); + this.controller = new AbortController; + _MessageStream_connectedPromise.set(this, undefined); + _MessageStream_resolveConnectedPromise.set(this, () => {}); + _MessageStream_rejectConnectedPromise.set(this, () => {}); + _MessageStream_endPromise.set(this, undefined); + _MessageStream_resolveEndPromise.set(this, () => {}); + _MessageStream_rejectEndPromise.set(this, () => {}); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, undefined); + _MessageStream_request_id.set(this, undefined); + _MessageStream_logger.set(this, undefined); + _MessageStream_handleError.set(this, (error91) => { + __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (isAbortError(error91)) { + error91 = new APIUserAbortError; + } + if (error91 instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); + return this._emit("abort", error91); + } + if (error91 instanceof AnthropicError) { + return this._emit("error", error91); + } + if (error91 instanceof Error) { + const anthropicError = new AnthropicError(error91.message); + anthropicError.cause = error91; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error91))); + }); + __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve2, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve2, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => {}); + __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => {}); + __classPrivateFieldSet(this, _MessageStream_params, params, "f"); + __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _MessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); + } + async withResponse() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); + if (!response) { + throw new Error("Could not resolve a `Response` object"); + } + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + static fromReadableStream(stream2) { + const runner = new MessageStream(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new MessageStream(params, { logger }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit("message", message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); + this._connected(response); + for await (const event of stream2) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError; + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_response, response, "f"); + __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); } - const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) - throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - for (const reservedChar of ["|", ":"]) - if (key.includes(reservedChar)) - throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) - throw new Error(`Node \`${key}\` already present.`); - if (key === "__end__") - throw new Error(`Node \`${key}\` is reserved.`); - const runnable = _coerceToRunnable(action); - this.nodes[key] = { - runnable, - metadata: options?.metadata, - subgraphs: isPregelLike2(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends - }; + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; } - return this; - } - addEdge(startKey, endKey) { - this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (startKey === "__end__") - throw new Error("END cannot be a start node"); - if (endKey === "__start__") - throw new Error("START cannot be an end node"); - if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) - throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); - this.edges.add([startKey, endKey]); - return this; - } - addConditionalEdges(source, path4, pathMap) { - const options = typeof source === "object" ? source : { - source, - path: path4, - pathMap - }; - this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - if (!Runnable.isRunnable(options.path)) - options.path = _coerceToRunnable(options.path); - const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); - if (this.branches[options.source] && this.branches[options.source][name]) - throw new Error(`Condition \`${name}\` already present for node \`${source}\``); - this.branches[options.source] ??= {}; - this.branches[options.source][name] = new Branch2(options); - return this; - } - setEntryPoint(key) { - this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(START2, key); - } - setFinishPoint(key) { - this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(key, END2); - } - compile({ checkpointer, interruptBefore, interruptAfter, name, transformers } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const compiled = new CompiledGraph2({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - [START2]: new EphemeralValue3, - [END2]: new EphemeralValue3 - }, - inputChannels: START2, - outputChannels: END2, - streamChannels: [], - streamMode: "values", - name, - streamTransformers: transformers - }); - for (const [key, node] of Object.entries(this.nodes)) - compiled.attachNode(key, node); - for (const [start, end] of this.edges) - compiled.attachEdge(start, end); - for (const [start, branches] of Object.entries(this.branches)) - for (const [name2, branch] of Object.entries(branches)) - compiled.attachBranch(start, name2, branch); - return compiled.validate(); - } - validate(interrupt3) { - const allSources = new Set([...this.allEdges].map(([src, _]) => src)); - for (const [start] of Object.entries(this.branches)) - allSources.add(start); - for (const source of allSources) - if (source !== "__start__" && !(source in this.nodes)) - throw new Error(`Found edge starting at unknown node \`${source}\``); - const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); - for (const [start, branches] of Object.entries(this.branches)) - for (const branch of Object.values(branches)) - if (branch.ends != null) - for (const end of Object.values(branch.ends)) - allTargets.add(end); - else { - allTargets.add(END2); - for (const node of Object.keys(this.nodes)) - if (node !== start) - allTargets.add(node); - } - for (const node of Object.values(this.nodes)) - for (const target of node.ends ?? []) - allTargets.add(target); - for (const node of Object.keys(this.nodes)) - if (!allTargets.has(node)) - throw new UnreachableNodeError2([ - `Node \`${node}\` is not reachable.`, - "", - "If you are returning Command objects from your node,", - 'make sure you are passing names of potential destination nodes as an "ends" array', - 'into ".addNode(..., { ends: ["node1", "node2"] })".' - ].join(` -`), { lc_error_code: "UNREACHABLE_NODE" }); - for (const target of allTargets) - if (target !== "__end__" && !(target in this.nodes)) - throw new Error(`Found edge ending at unknown node \`${target}\``); - if (interrupt3) { - for (const node of interrupt3) - if (!(node in this.nodes)) - throw new Error(`Interrupt node \`${node}\` is not present`); + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index2 = listeners.findIndex((l) => l.listener === listener); + if (index2 >= 0) + listeners.splice(index2, 1); + return this; } - this.compiled = true; - } -}, CompiledGraph2; -var init_graph4 = __esm(() => { - init_constants8(); - init_errors10(); - init_utils17(); - init_write2(); - init_read2(); - init_subgraph2(); - init_pregel2(); - init_ephemeral_value2(); - init_runnables(); - init_graph(); - init_v44(); - init_wrapper(); - CompiledGraph2 = class extends Pregel2 { - builder; - constructor({ builder, ...rest }) { - super(rest); - this.builder = builder; + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; } - withConfig(config3) { - return super.withConfig(config3); + emitted(event) { + return new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") + this.once("error", reject); + this.once(event, resolve2); + }); } - attachNode(key, node) { - this.channels[key] = new EphemeralValue3; - this.nodes[key] = new PregelNode3({ - channels: [], - triggers: [], - metadata: node.metadata, - subgraphs: node.subgraphs, - ends: node.ends - }).pipe(node.runnable).pipe(new ChannelWrite3([{ - channel: key, - value: PASSTHROUGH2 - }], [TAG_HIDDEN2])); - this.streamChannels.push(key); + async done() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); } - attachEdge(start, end) { - if (end === "__end__") { - if (start === "__start__") - throw new Error("Cannot have an edge from START to END"); - this.nodes[start].writers.push(new ChannelWrite3([{ - channel: END2, - value: PASSTHROUGH2 - }], [TAG_HIDDEN2])); - } else { - this.nodes[end].triggers.push(start); - this.nodes[end].channels.push(start); + get currentMessage() { + return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + } + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + } + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) + return; + if (event === "end") { + __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error91 = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error91); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error91); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error91); + this._emit("end"); + return; + } + if (event === "error") { + const error91 = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error91); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error91); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error91); + this._emit("end"); } } - attachBranch(start, name, branch) { - if (start === "__start__" && !this.nodes["__start__"]) - this.nodes[START2] = Channel2.subscribeTo(START2, { tags: [TAG_HIDDEN2] }); - this.nodes[start].pipe(branch.run((dests) => { - return new ChannelWrite3(dests.map((dest) => { - if (_isSend2(dest)) - return dest; - return { - channel: dest === "__end__" ? END2 : `branch:${start}:${name}:${dest}`, - value: PASSTHROUGH2 - }; - }), [TAG_HIDDEN2]); - })); - const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); - for (const end of ends) - if (end !== "__end__") { - const channelName = `branch:${start}:${name}:${end}`; - this.channels[channelName] = new EphemeralValue3; - this.nodes[end].triggers.push(channelName); - this.nodes[end].channels.push(channelName); + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream2 = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream2) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError; + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); } + } } - async getGraphAsync(config3) { - const xray = config3?.xray; - const graph = new Graph; - const startNodes = { [START2]: graph.addNode({ schema: exports_external3.any() }, START2) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) - subgraphs = Object.fromEntries((await gatherIterator2(this.getSubgraphsAsync())).filter((x) => isCompiledGraph2(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === "__end__" && endNodes["__end__"] === undefined) - endNodes[END2] = graph.addNode({ schema: exports_external3.any() }, END2); - if (startNodes[start] === undefined) - return; - if (endNodes[end] === undefined) - throw new Error(`End node ${end} not found!`); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); + [(_MessageStream_currentMessageSnapshot = new WeakMap, _MessageStream_params = new WeakMap, _MessageStream_connectedPromise = new WeakMap, _MessageStream_resolveConnectedPromise = new WeakMap, _MessageStream_rejectConnectedPromise = new WeakMap, _MessageStream_endPromise = new WeakMap, _MessageStream_resolveEndPromise = new WeakMap, _MessageStream_rejectEndPromise = new WeakMap, _MessageStream_listeners = new WeakMap, _MessageStream_ended = new WeakMap, _MessageStream_errored = new WeakMap, _MessageStream_aborted = new WeakMap, _MessageStream_catchingPromiseCreated = new WeakMap, _MessageStream_response = new WeakMap, _MessageStream_request_id = new WeakMap, _MessageStream_logger = new WeakMap, _MessageStream_handleError = new WeakMap, _MessageStream_instances = new WeakSet, _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords2(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) - metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) - metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) - metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== undefined ? await subgraphs[key].getGraphAsync({ - ...config3, - xray: newXrayValue - }) : node.getGraph(config3); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - let _isRunnableInterface = function(thing) { - return thing ? thing.lc_runnable : false; - }, _nodeDataStr = function(id, data) { - if (id !== undefined && !validate7(id)) - return id; - else if (_isRunnableInterface(data)) - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); - } - else - return data.name ?? "UnknownSchema"; - }; - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === undefined) - throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - if (s !== undefined) - startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; + return this.receivedMessages.at(-1); + }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError("stream ended without producing a content block with type=text"); + } + return textBlocks.join(" "); + }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": { + if (content.type === "text") { + this._emit("text", event.delta.text, content.text || ""); + } + break; + } + case "citations_delta": { + if (content.type === "text") { + this._emit("citation", event.delta.citation, content.citations ?? []); + } + break; + } + case "input_json_delta": { + if (tracksToolInput2(content) && content.input) { + this._emit("inputJson", event.delta.partial_json, content.input); + } + break; + } + case "thinking_delta": { + if (content.type === "thinking") { + this._emit("thinking", event.delta.thinking, content.thinking); + } + break; + } + case "signature_delta": { + if (content.type === "thinking") { + this._emit("signature", content.signature); + } + break; + } + default: + checkNever2(event.delta); } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; + break; + } + case "message_stop": { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); + break; + } + case "content_block_stop": { + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + } + case "message_start": { + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; } + case "content_block_start": + case "message_delta": + break; } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) - return -1; - else if (b > a) - return 1; - else - return 0; - }); - for (const [start, end] of sortedEdges) - addEdge(_escapeMermaidKeywords2(start), _escapeMermaidKeywords2(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords2(k), _escapeMermaidKeywords2(k)])), - [END2]: END2 - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== undefined) - ends = branch.ends; - else - ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) - addEdge(_escapeMermaidKeywords2(start), _escapeMermaidKeywords2(end), label, true); + }, _MessageStream_endRequest = function _MessageStream_endRequest2() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) { + let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); } + return event.message; } - for (const [key, node] of Object.entries(this.builder.nodes)) - if (node.ends !== undefined) - for (const end of node.ends) - addEdge(_escapeMermaidKeywords2(key), _escapeMermaidKeywords2(end), undefined, true); - return graph; - } - getGraph(config3) { - const xray = config3?.xray; - const graph = new Graph; - const startNodes = { [START2]: graph.addNode({ schema: exports_external3.any() }, START2) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) - subgraphs = Object.fromEntries(gatherIteratorSync2(this.getSubgraphs()).filter((x) => isCompiledGraph2(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === "__end__" && endNodes["__end__"] === undefined) - endNodes[END2] = graph.addNode({ schema: exports_external3.any() }, END2); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : undefined, conditional); + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords2(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) - metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) - metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) - metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== undefined ? subgraphs[key].getGraph({ - ...config3, - xray: newXrayValue - }) : node.getGraph(config3); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - let _isRunnableInterface = function(thing) { - return thing ? thing.lc_runnable : false; - }, _nodeDataStr = function(id, data) { - if (id !== undefined && !validate7(id)) - return id; - else if (_isRunnableInterface(data)) - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); + switch (event.type) { + case "message_stop": + return snapshot; + case "message_delta": + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case "content_block_start": + snapshot.content.push({ ...event.content_block }); + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + } + break; + } + case "citations_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + } + break; + } + case "input_json_delta": { + if (snapshotContent && tracksToolInput2(snapshotContent)) { + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || ""; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY2, { + value: jsonBuf, + enumerable: false, + writable: true + }); + if (jsonBuf) { + newContent.input = partialParse(jsonBuf); } - else - return data.name ?? "UnknownSchema"; - }; - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === undefined) - throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - if (s !== undefined) - startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; + snapshot.content[event.index] = newContent; + } + break; + } + case "thinking_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + } + break; + } + case "signature_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + } + break; + } + default: + checkNever2(event.delta); } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; + return snapshot; } + case "content_block_stop": + return snapshot; } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) - return -1; - else if (b > a) - return 1; - else - return 0; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } }); - for (const [start, end] of sortedEdges) - addEdge(_escapeMermaidKeywords2(start), _escapeMermaidKeywords2(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords2(k), _escapeMermaidKeywords2(k)])), - [END2]: END2 - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== undefined) - ends = branch.ends; - else - ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) - addEdge(_escapeMermaidKeywords2(start), _escapeMermaidKeywords2(end), label, true); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); } - } - return graph; + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + } + }; + } + toReadableStream() { + const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/types.js -function isStandardSchema3(schema) { - return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "validate" in schema["~standard"]; -} -function isStandardJSONSchema2(schema) { - return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"] === "object" && schema["~standard"] !== null && "jsonSchema" in schema["~standard"]; -} -function isSerializableSchema3(schema) { - return isStandardSchema3(schema) && isStandardJSONSchema2(schema); -} -var init_types14 = () => {}; - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/adapter.js -function getJsonSchemaFromSchema2(schema) { - if (isStandardJSONSchema2(schema)) - try { - return schema["~standard"].jsonSchema.input({ target: "draft-07" }); - } catch { - return; +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +var Batches2; +var init_batches2 = __esm(() => { + init_pagination(); + init_headers(); + init_jsonl(); + init_error6(); + init_path(); + Batches2 = class Batches2 extends APIResource { + create(body, options) { + return this._client.post("/v1/messages/batches", { body, ...options }); } -} -function getSchemaDefaultGetter2(schema) { - if (schema == null) - return; - if (!isStandardSchema3(schema)) - return; - try { - const result = schema["~standard"].validate(undefined); - if (result && typeof result === "object" && !(("then" in result) && typeof result.then === "function")) { - const syncResult = result; - if (!syncResult.issues) { - const defaultValue = syncResult.value; - return () => defaultValue; + retrieve(messageBatchID, options) { + return this._client.get(path3`/v1/messages/batches/${messageBatchID}`, options); + } + list(query4 = {}, options) { + return this._client.getAPIList("/v1/messages/batches", Page, { query: query4, ...options }); + } + delete(messageBatchID, options) { + return this._client.delete(path3`/v1/messages/batches/${messageBatchID}`, options); + } + cancel(messageBatchID, options) { + return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel`, options); + } + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); } + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); } - } catch {} -} -var init_adapter2 = __esm(() => { - init_types14(); + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/untracked_value.js -var MISSING2, UntrackedValueChannel3; -var init_untracked_value2 = __esm(() => { - init_errors10(); - init_base17(); - MISSING2 = Symbol.for("langgraph.channel.missing"); - UntrackedValueChannel3 = class UntrackedValueChannel4 extends BaseChannel2 { - lc_graph_name = "UntrackedValue"; - guard; - _value = MISSING2; - initialValueFactory; - constructor(options) { - super(); - this.guard = options?.guard ?? true; - this.initialValueFactory = options?.initialValueFactory; - if (this.initialValueFactory) - this._value = this.initialValueFactory(); +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +var Messages2, DEPRECATED_MODELS2, MODELS_TO_WARN_WITH_THINKING_ENABLED2; +var init_messages12 = __esm(() => { + init_headers(); + init_stainless_helper_header(); + init_MessageStream(); + init_parser2(); + init_batches2(); + init_batches2(); + init_constants8(); + Messages2 = class Messages2 extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches2(this._client); } - fromCheckpoint(_checkpoint) { - return new UntrackedValueChannel4({ - guard: this.guard, - initialValueFactory: this.initialValueFactory + create(body, options) { + if (body.model in DEPRECATED_MODELS2) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]} +Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (MODELS_TO_WARN_WITH_THINKING_ENABLED2.includes(body.model) && body.thinking && body.thinking.type === "enabled") { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages", { + body, + timeout: timeout ?? 600000, + ...options, + headers: buildHeaders([helperHeader, options?.headers]), + stream: body.stream ?? false }); } - update(values2) { - if (values2.length === 0) - return false; - if (values2.length !== 1 && this.guard) - throw new InvalidUpdateError2("UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this._value = values2[values2.length - 1]; - return true; + parse(params, options) { + return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); } - get() { - if (this._value === MISSING2) - throw new EmptyChannelError2; - return this._value; + stream(body, options) { + return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); } - checkpoint() {} - isAvailable() { - return this._value !== MISSING2; + countTokens(body, options) { + return this._client.post("/v1/messages/count_tokens", { body, ...options }); } }; + DEPRECATED_MODELS2 = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026", + "claude-3-5-haiku-latest": "February 19th, 2026", + "claude-3-5-haiku-20241022": "February 19th, 2026", + "claude-opus-4-0": "June 15th, 2026", + "claude-opus-4-20250514": "June 15th, 2026", + "claude-sonnet-4-0": "June 15th, 2026", + "claude-sonnet-4-20250514": "June 15th, 2026" + }; + MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-mythos-preview", "claude-opus-4-6"]; + Messages2.Batches = Batches2; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/values/reduced.js -var REDUCED_VALUE_SYMBOL2, ReducedValue2; -var init_reduced2 = __esm(() => { - REDUCED_VALUE_SYMBOL2 = Symbol.for("langgraph.state.reduced_value"); - ReducedValue2 = class { - [REDUCED_VALUE_SYMBOL2] = true; - valueSchema; - inputSchema; - reducer; - jsonSchemaExtra; - constructor(valueSchema, init) { - this.reducer = init.reducer; - this.jsonSchemaExtra = init.jsonSchemaExtra; - this.valueSchema = valueSchema; - this.inputSchema = "inputSchema" in init ? init.inputSchema : valueSchema; - this.jsonSchemaExtra = init.jsonSchemaExtra; +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/models.mjs +var Models2; +var init_models2 = __esm(() => { + init_pagination(); + init_headers(); + init_path(); + Models2 = class Models2 extends APIResource { + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path3`/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + options?.headers + ]) + }); } - static isInstance(value) { - return typeof value === "object" && value !== null && REDUCED_VALUE_SYMBOL2 in value && value[REDUCED_VALUE_SYMBOL2] === true; + list(params = {}, options) { + const { betas, ...query4 } = params ?? {}; + return this._client.getAPIList("/v1/models", Page, { + query: query4, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined }, + options?.headers + ]) + }); } }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/values/untracked.js -var UNTRACKED_VALUE_SYMBOL2, UntrackedValue2; -var init_untracked2 = __esm(() => { - UNTRACKED_VALUE_SYMBOL2 = Symbol.for("langgraph.state.untracked_value"); - UntrackedValue2 = class { - [UNTRACKED_VALUE_SYMBOL2] = true; - schema; - guard; - constructor(schema, init) { - this.schema = schema; - this.guard = init?.guard ?? true; - } - static isInstance(value) { - return typeof value === "object" && value !== null && UNTRACKED_VALUE_SYMBOL2 in value; - } - }; +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/resources/index.mjs +var init_resources2 = __esm(() => { + init_beta(); + init_completions(); + init_messages12(); + init_models2(); + init_shared(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js -var areSetsEqual2 = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)), NamedBarrierValue3, NamedBarrierValueAfterFinish3; -var init_named_barrier_value2 = __esm(() => { - init_errors10(); - init_base17(); - NamedBarrierValue3 = class NamedBarrierValue4 extends BaseChannel2 { - lc_graph_name = "NamedBarrierValue"; - names; - seen; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set; +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/client.mjs +class BaseAnthropic { + get credentials() { + return this._authState.provider; + } + constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey, authToken, webhookKey = readEnv("ANTHROPIC_WEBHOOK_SIGNING_KEY") ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + this._requestAuthFlags = new WeakMap; + _BaseAnthropic_encoder.set(this, undefined); + if (apiKey === undefined) { + apiKey = opts.profile != null ? null : readEnv("ANTHROPIC_API_KEY") ?? null; } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValue4(this.names); - if (typeof checkpoint !== "undefined") - empty.seen = new Set(checkpoint); - return empty; + if (authToken === undefined) { + authToken = opts.profile != null ? null : readEnv("ANTHROPIC_AUTH_TOKEN") ?? null; } - update(values2) { - let updated = false; - for (const nodeName of values2) - if (this.names.has(nodeName)) { - if (!this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } - } else - throw new InvalidUpdateError2(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; + if (opts.profile != null && (opts.credentials != null || opts.config != null)) { + throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`."); } - get() { - if (!areSetsEqual2(this.names, this.seen)) - throw new EmptyChannelError2; + const options = { + apiKey, + authToken, + webhookKey, + ...opts, + baseURL: baseURL || `https://api.anthropic.com` + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new AnthropicError(`It looks like you're running in a browser-like environment. + +This is disabled by default, as it risks exposing your secret API credentials to attackers. +If you understand the risks and have appropriate mitigations in place, +you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., + +new Anthropic({ apiKey, dangerouslyAllowBrowser: true }); +`); } - checkpoint() { - return [...this.seen]; + this.baseURL = options.baseURL; + this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL; + this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); + const customHeadersEnv = readEnv("ANTHROPIC_CUSTOM_HEADERS"); + if (customHeadersEnv) { + const parsed = {}; + for (const line of customHeadersEnv.split(` +`)) { + const colon = line.indexOf(":"); + if (colon >= 0) { + parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim(); + } + } + options.defaultHeaders = { ...parsed, ...options.defaultHeaders }; } - consume() { - if (this.seen && this.names && areSetsEqual2(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set; - return true; + const inherited = opts.__auth; + delete options.__auth; + delete options.__baseURLIsExplicit; + this._options = options; + this.apiKey = typeof apiKey === "string" ? apiKey : null; + this.authToken = authToken; + this.webhookKey = webhookKey; + if (inherited) { + this._authState = inherited; + if (!this._baseURLIsExplicit && inherited.baseURL) { + this.baseURL = inherited.baseURL; + } + } else { + this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} }; + if (this.apiKey == null && this.authToken == null) { + const credentials = options.credentials ?? null; + if (credentials) { + this._authState.provider = credentials; + this._authState.tokenCache = this._makeTokenCache(credentials); + } else if (options.config != null) { + const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions()); + this._authState.provider = result.provider; + this._authState.tokenCache = this._makeTokenCache(result.provider); + this._authState.extraHeaders = result.extraHeaders; + this._applyCredentialBaseURL(result.baseURL); + } else if (options.profile != null) { + this._authState.resolution = this._resolveDefaultCredentials(options.profile); + } else { + this._authState.resolution = this._resolveDefaultCredentials(); + } } - return false; } - isAvailable() { - return !!this.names && areSetsEqual2(this.names, this.seen); + } + _applyCredentialBaseURL(baseURL) { + if (!baseURL) + return; + const normalized = baseURL.replace(/\/+$/, ""); + this._authState.baseURL = normalized; + if (!this._baseURLIsExplicit) { + this.baseURL = normalized; } - }; - NamedBarrierValueAfterFinish3 = class NamedBarrierValueAfterFinish4 extends BaseChannel2 { - lc_graph_name = "NamedBarrierValueAfterFinish"; - names; - seen; - finished; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set; - this.finished = false; + } + _credentialResolverOptions() { + return { + baseURL: this.baseURL, + fetch: this.fetch, + userAgent: this.getUserAgent(), + onCacheWriteError: (err) => { + loggerFor(this).debug("credential cache write failed (best-effort)", err); + }, + onSafetyWarning: (msg) => { + loggerFor(this).warn(msg); + } + }; + } + _makeTokenCache(provider) { + return new TokenCache(provider, (err) => { + loggerFor(this).debug("advisory token refresh failed; serving cached token", err); + }); + } + withOptions(options) { + const overridesStructuredAuth = "credentials" in options || "config" in options || "profile" in options; + const overridesAuth = "apiKey" in options || "authToken" in options || overridesStructuredAuth; + const internal = { + ...this._options, + ...this._baseURLIsExplicit ? { baseURL: this.baseURL } : {}, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + authToken: this.authToken, + webhookKey: this.webhookKey, + credentials: this.credentials, + ...overridesStructuredAuth ? { credentials: undefined, config: undefined, profile: undefined } : {}, + ...options, + __auth: overridesAuth ? undefined : this._authState, + __baseURLIsExplicit: "baseURL" in options ? true : this._baseURLIsExplicit + }; + return new this.constructor(internal); + } + async _resolveDefaultCredentials(profile) { + try { + const result = await defaultCredentials(this._credentialResolverOptions(), profile); + if (result) { + this._authState.provider = result.provider; + this._authState.tokenCache = this._makeTokenCache(result.provider); + this._authState.extraHeaders = result.extraHeaders; + this._applyCredentialBaseURL(result.baseURL); + } else if (profile != null) { + throw new AnthropicError(`Profile "${profile}" could not be resolved (no /configs/${profile}.json found).`); + } + } catch (err) { + this._authState.error = err; + } finally { + this._authState.resolution = null; + } + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values: values2, nulls }) { + if (values2.get("x-api-key") || values2.get("authorization")) { + return; + } + if (this._authState.error) { + throw this._authState.error; + } + if (this._authState.tokenCache || this._authState.resolution) { + return; + } + if (this.apiKey && values2.get("x-api-key")) { + return; + } + if (nulls.has("x-api-key")) { + return; + } + if (this.authToken && values2.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); + } + _authFlags(opts) { + let flags = this._requestAuthFlags.get(opts); + if (!flags) { + flags = { usedTokenCache: false, didRefreshFor401: false }; + this._requestAuthFlags.set(opts, flags); + } + return flags; + } + async authHeaders(opts) { + if (this._authState.resolution) { + await this._authState.resolution; + } + if (this._authState.error) { + return; + } + if (this._authState.tokenCache && this.apiKey == null) { + const token = await this._authState.tokenCache.getToken(); + this._authFlags(opts).usedTokenCache = true; + return buildHeaders([{ Authorization: `Bearer ${token}` }]); + } + return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) { + return; + } + return buildHeaders([{ "X-Api-Key": this.apiKey }]); + } + async bearerAuth(opts) { + if (this.authToken == null) { + return; + } + return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + } + stringifyQuery(query4) { + return stringifyQuery(query4); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid43()}`; + } + makeStatusError(status, error91, message, headers) { + return APIError.generate(status, error91, message, headers); + } + buildURL(path4, query4, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url3 = isAbsoluteURL(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4)); + const defaultQuery = this.defaultQuery(); + const pathQuery = Object.fromEntries(url3.searchParams); + if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) { + query4 = { ...pathQuery, ...defaultQuery, ...query4 }; } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValueAfterFinish4(this.names); - if (typeof checkpoint !== "undefined") { - const [seen, finished] = checkpoint; - empty.seen = new Set(seen); - empty.finished = finished; - } - return empty; + if (typeof query4 === "object" && query4 && !Array.isArray(query4)) { + url3.search = this.stringifyQuery(query4); } - update(values2) { - let updated = false; - for (const nodeName of values2) - if (this.names.has(nodeName) && !this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } else if (!this.names.has(nodeName)) - throw new InvalidUpdateError2(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; + return url3.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 10 * 60; + const expectedTimeout = 60 * 60 * maxTokens / 128000; + if (expectedTimeout > defaultTimeout) { + throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. " + "See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details"); } - get() { - if (!this.finished || !areSetsEqual2(this.names, this.seen)) - throw new EmptyChannelError2; + return defaultTimeout * 1000; + } + async prepareOptions(options) {} + async prepareRequest(request, { url: url3, options }) { + if (this._authState.tokenCache && this.apiKey == null) { + const headers = request.headers instanceof Headers ? request.headers : new Headers(request.headers); + for (const [k, v] of Object.entries(this._authState.extraHeaders)) { + if (!headers.has(k)) + headers.set(k, v); + } + const existing = headers.get("anthropic-beta")?.split(",").map((s) => s.trim()); + if (!existing?.includes(OAUTH_API_BETA_HEADER)) { + headers.append("anthropic-beta", OAUTH_API_BETA_HEADER); + } + request.headers = headers; } - checkpoint() { - return [[...this.seen], this.finished]; + } + get(path4, opts) { + return this.methodRequest("get", path4, opts); + } + post(path4, opts) { + return this.methodRequest("post", path4, opts); + } + patch(path4, opts) { + return this.methodRequest("patch", path4, opts); + } + put(path4, opts) { + return this.methodRequest("put", path4, opts); + } + delete(path4, opts) { + return this.methodRequest("delete", path4, opts); + } + methodRequest(method, path4, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path4, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + this._requestAuthFlags.delete(options); } - consume() { - if (this.finished && this.seen && this.names && areSetsEqual2(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set; - this.finished = false; - return true; + await this.prepareOptions(options); + const { req, url: url3, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url: url3, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url: url3, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError; + } + const controller = new AbortController; + const response = await this.fetchWithTimeout(url3, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError; } - return false; + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: url3, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url: url3, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError; + } + throw new APIConnectionError({ cause: response }); } - finish() { - if (!this.finished && !!this.names && areSetsEqual2(this.names, this.seen)) { - this.finished = true; - return true; + const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join(""); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url3} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response, options); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); } - return false; + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; } - isAvailable() { - return this.finished && !!this.names && areSetsEqual2(this.names, this.seen); + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path4, Page2, opts) { + return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts }); + } + requestAPIList(Page2, options) { + const request = this.makeRequest(options, null, undefined); + return new PagePromise(this, request, Page2); + } + async fetchWithTimeout(url3, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/any_value.js -var init_any_value2 = __esm(() => { - init_errors10(); - init_base17(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js -var init_dynamic_barrier_value2 = __esm(() => { - init_errors10(); - init_base17(); - init_named_barrier_value2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/channels/index.js -var init_channels2 = __esm(() => { - init_base17(); - init_binop2(); - init_last_value2(); - init_topic2(); - init_ephemeral_value2(); - init_named_barrier_value2(); - init_any_value2(); - init_dynamic_barrier_value2(); - init_untracked_value2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/schema.js -var STATE_SCHEMA_SYMBOL2, StateSchema2; -var init_schema2 = __esm(() => { - init_binop2(); - init_last_value2(); - init_types14(); - init_adapter2(); - init_untracked_value2(); - init_channels2(); - init_reduced2(); - init_untracked2(); - STATE_SCHEMA_SYMBOL2 = Symbol.for("langgraph.state.state_schema"); - StateSchema2 = class { - [STATE_SCHEMA_SYMBOL2] = true; - constructor(fields) { - this.fields = fields; + try { + return await this.fetch.call(undefined, url3, fetchOptions); + } finally { + clearTimeout(timeout); } - getChannels() { - const channels = {}; - for (const [key, value] of Object.entries(this.fields)) - if (ReducedValue2.isInstance(value)) { - const defaultGetter = getSchemaDefaultGetter2(value.valueSchema); - channels[key] = new BinaryOperatorAggregate3(value.reducer, defaultGetter); - } else if (UntrackedValue2.isInstance(value)) { - const defaultGetter = value.schema ? getSchemaDefaultGetter2(value.schema) : undefined; - channels[key] = new UntrackedValueChannel3({ - guard: value.guard, - initialValueFactory: defaultGetter - }); - } else if (isStandardSchema3(value)) - channels[key] = new LastValue3(getSchemaDefaultGetter2(value)); - else - throw new Error(`Invalid state field "${key}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`); - return channels; + } + async shouldRetry(response, options) { + const flags = this._authFlags(options); + if (response.status === 401 && this._authState.tokenCache && flags.usedTokenCache && !flags.didRefreshFor401) { + flags.didRefreshFor401 = true; + this._authState.tokenCache.invalidate(); + return true; } - getJsonSchema() { - const properties = {}; - const required3 = []; - for (const [key, value] of Object.entries(this.fields)) { - let fieldSchema; - if (ReducedValue2.isInstance(value)) { - fieldSchema = getJsonSchemaFromSchema2(value.valueSchema); - if (value.jsonSchemaExtra) - fieldSchema = { - ...fieldSchema ?? {}, - ...value.jsonSchemaExtra - }; - } else if (UntrackedValue2.isInstance(value)) - fieldSchema = value.schema ? getJsonSchemaFromSchema2(value.schema) : undefined; - else if (isStandardSchema3(value)) - fieldSchema = getJsonSchemaFromSchema2(value); - if (fieldSchema) { - properties[key] = fieldSchema; - let hasDefault = false; - if (ReducedValue2.isInstance(value)) - hasDefault = getSchemaDefaultGetter2(value.valueSchema) !== undefined; - else if (UntrackedValue2.isInstance(value)) - hasDefault = value.schema ? getSchemaDefaultGetter2(value.schema) !== undefined : false; - else - hasDefault = getSchemaDefaultGetter2(value) !== undefined; - if (!hasDefault) - required3.push(key); - } + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; } - return { - type: "object", - properties, - required: required3.length > 0 ? required3 : undefined - }; } - getInputJsonSchema() { - const properties = {}; - for (const [key, value] of Object.entries(this.fields)) { - let fieldSchema; - if (ReducedValue2.isInstance(value)) { - fieldSchema = getJsonSchemaFromSchema2(value.inputSchema); - if (value.jsonSchemaExtra) - fieldSchema = { - ...fieldSchema ?? {}, - ...value.jsonSchemaExtra - }; - } else if (UntrackedValue2.isInstance(value)) - fieldSchema = value.schema ? getJsonSchemaFromSchema2(value.schema) : undefined; - else if (isStandardSchema3(value)) - fieldSchema = getJsonSchemaFromSchema2(value); - if (fieldSchema) - properties[key] = fieldSchema; + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } - return { - type: "object", - properties - }; } - getChannelKeys() { - return Object.entries(this.fields).map(([key]) => key); - } - getAllKeys() { - return Object.keys(this.fields); + if (timeoutMillis === undefined) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } - async validateInput(data) { - if (data == null || typeof data !== "object") - return data; - const result = {}; - for (const [key, value] of Object.entries(data)) { - const fieldDef = this.fields[key]; - if (fieldDef === undefined) { - result[key] = value; - continue; - } - let schema; - if (ReducedValue2.isInstance(fieldDef)) - schema = fieldDef.inputSchema; - else if (UntrackedValue2.isInstance(fieldDef)) - schema = fieldDef.schema; - else if (isStandardSchema3(fieldDef)) - schema = fieldDef; - if (schema) { - const validationResult = await schema["~standard"].validate(value); - if (validationResult.issues) - throw new Error(`Validation failed for field "${key}": ${JSON.stringify(validationResult.issues)}`); - result[key] = validationResult.value; - } else - result[key] = value; - } - return result; + await sleep2(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1000; + const defaultTime = 60 * 10 * 1000; + const expectedTime = maxTime * maxTokens / 128000; + if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) { + throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details"); } - static isInstance(value) { - return typeof value === "object" && value !== null && STATE_SCHEMA_SYMBOL2 in value && value[STATE_SCHEMA_SYMBOL2] === true; + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path4, query: query4, defaultBaseURL } = options; + if (this._authState.resolution) { + await this._authState.resolution; } - }; -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/messages_reducer.js -function messagesStateReducer2(left, right) { - const leftArray = Array.isArray(left) ? left : [left]; - const rightArray = Array.isArray(right) ? right : [right]; - const leftMessages = leftArray.map(coerceMessageLikeToMessage); - const rightMessages = rightArray.map(coerceMessageLikeToMessage); - for (const m of leftMessages) - if (m.id === null || m.id === undefined) { - m.id = v43(); - m.lc_kwargs.id = m.id; + if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) { + this.baseURL = this._authState.baseURL; } - let removeAllIdx; - for (let i = 0;i < rightMessages.length; i += 1) { - const m = rightMessages[i]; - if (m.id === null || m.id === undefined) { - m.id = v43(); - m.lc_kwargs.id = m.id; + const url3 = this.buildURL(path4, query4, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url: url3, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; } - if (RemoveMessage.isInstance(m) && m.id === "__remove_all__") - removeAllIdx = i; + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1000)) } : {}, + ...getPlatformHeaders(), + ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : undefined, + "anthropic-version": "2023-06-01" + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; } - if (removeAllIdx != null) - return rightMessages.slice(removeAllIdx + 1); - const merged = [...leftMessages]; - const mergedById = new Map(merged.map((m, i) => [m.id, i])); - const idsToRemove = /* @__PURE__ */ new Set; - for (const m of rightMessages) { - const existingIdx = mergedById.get(m.id); - if (existingIdx !== undefined) - if (RemoveMessage.isInstance(m)) - idsToRemove.add(m.id); - else { - idsToRemove.delete(m.id); - merged[existingIdx] = m; - } - else { - if (RemoveMessage.isInstance(m)) - throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); - mergedById.set(m.id, merged.length); - merged.push(m); + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = buildHeaders([rawHeaders]); + if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) { + return { bodyHeaders: undefined, body }; + } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) { + return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); } } - return merged.filter((m) => !idsToRemove.has(m.id)); } -var REMOVE_ALL_MESSAGES2 = "__remove_all__"; -var init_messages_reducer2 = __esm(() => { - init_wrapper(); - init_messages(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/prebuilt/messages.js -var MessagesValue2; -var init_messages12 = __esm(() => { - init_reduced2(); - init_messages_reducer2(); - init_v44(); - MessagesValue2 = new ReducedValue2(exports_external3.custom().default(() => []), { - inputSchema: exports_external3.custom(), - reducer: messagesStateReducer2, - jsonSchemaExtra: { - langgraph_type: "messages", - description: "A list of chat messages" - } - }); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/prebuilt/index.js -var init_prebuilt2 = __esm(() => { +var _BaseAnthropic_instances, _a3, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden, HUMAN_PROMPT = "\\n\\nHuman:", AI_PROMPT = "\\n\\nAssistant:", Anthropic; +var init_client5 = __esm(() => { + init_tslib(); + init_values6(); + init_detect_platform(); + init_query(); + init_error5(); + init_types16(); + init_token_cache(); + init_credential_chain(); + init_pagination(); + init_uploads2(); + init_resources2(); + init_api_promise(); + init_completions(); + init_models2(); + init_beta(); init_messages12(); + init_detect_platform(); + init_headers(); + init_log(); + init_values6(); + _a3 = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap, _BaseAnthropic_instances = new WeakSet, _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() { + return this.baseURL !== "https://api.anthropic.com"; + }; + BaseAnthropic.Anthropic = _a3; + BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; + BaseAnthropic.AI_PROMPT = AI_PROMPT; + BaseAnthropic.DEFAULT_TIMEOUT = 600000; + BaseAnthropic.AnthropicError = AnthropicError; + BaseAnthropic.APIError = APIError; + BaseAnthropic.APIConnectionError = APIConnectionError; + BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; + BaseAnthropic.APIUserAbortError = APIUserAbortError; + BaseAnthropic.NotFoundError = NotFoundError; + BaseAnthropic.ConflictError = ConflictError; + BaseAnthropic.RateLimitError = RateLimitError; + BaseAnthropic.BadRequestError = BadRequestError; + BaseAnthropic.AuthenticationError = AuthenticationError; + BaseAnthropic.InternalServerError = InternalServerError; + BaseAnthropic.PermissionDeniedError = PermissionDeniedError; + BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; + BaseAnthropic.toFile = toFile; + Anthropic = class Anthropic extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new Completions(this); + this.messages = new Messages2(this); + this.models = new Models2(this); + this.beta = new Beta(this); + } + }; + Anthropic.Completions = Completions; + Anthropic.Messages = Messages2; + Anthropic.Models = Models2; + Anthropic.Beta = Beta; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/values/index.js -var init_values6 = __esm(() => { - init_reduced2(); - init_untracked2(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/state/index.js -var init_state3 = __esm(() => { - init_types14(); - init_adapter2(); - init_reduced2(); - init_untracked2(); - init_schema2(); - init_messages12(); - init_prebuilt2(); - init_values6(); +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/index.mjs +var init_sdk = __esm(() => { + init_client5(); + init_uploads2(); + init_api_promise(); + init_client5(); + init_pagination(); + init_error5(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/zod/meta.js -function withLangGraph2(schema, meta3) { - if (meta3.reducer && !meta3.default) { - const defaultValueGetter = getInteropZodDefaultGetter(schema); - if (defaultValueGetter != null) - meta3.default = defaultValueGetter; - } - if (meta3.reducer) { - const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta3.reducer?.schema ?? schema }); - schemaMetaRegistry2.extend(schemaWithReducer, () => meta3); - return schemaWithReducer; - } else { - schemaMetaRegistry2.extend(schema, () => meta3); - return schema; - } +// ../../node_modules/.pnpm/@anthropic-ai+sdk@0.95.2_zod@3.25.76/node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs +function deepClone2(obj) { + return JSON.parse(JSON.stringify(obj)); } -var SchemaMetaRegistry2 = class { - _map = /* @__PURE__ */ new Map; - _extensionCache = /* @__PURE__ */ new Map; - get(schema) { - return this._map.get(schema); +function transformJSONSchema(jsonSchema) { + const workingCopy = deepClone2(jsonSchema); + return _transformJSONSchema(workingCopy); +} +function _transformJSONSchema(jsonSchema) { + const strictSchema = {}; + const ref = pop(jsonSchema, "$ref"); + if (ref !== undefined) { + strictSchema["$ref"] = ref; + return strictSchema; } - extend(schema, predicate) { - const existingMeta = this.get(schema); - this._map.set(schema, predicate(existingMeta)); + const defs = pop(jsonSchema, "$defs"); + if (defs !== undefined) { + const strictDefs = {}; + strictSchema["$defs"] = strictDefs; + for (const [name, defSchema] of Object.entries(defs)) { + strictDefs[name] = _transformJSONSchema(defSchema); + } } - remove(schema) { - this._map.delete(schema); - return this; + const type = pop(jsonSchema, "type"); + const anyOf = pop(jsonSchema, "anyOf"); + const oneOf = pop(jsonSchema, "oneOf"); + const allOf = pop(jsonSchema, "allOf"); + if (Array.isArray(anyOf)) { + strictSchema["anyOf"] = anyOf.map((variant) => _transformJSONSchema(variant)); + } else if (Array.isArray(oneOf)) { + strictSchema["anyOf"] = oneOf.map((variant) => _transformJSONSchema(variant)); + } else if (Array.isArray(allOf)) { + strictSchema["allOf"] = allOf.map((entry) => _transformJSONSchema(entry)); + } else { + if (type === undefined) { + throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used"); + } + strictSchema["type"] = type; } - has(schema) { - return this._map.has(schema); + const description = pop(jsonSchema, "description"); + if (description !== undefined) { + strictSchema["description"] = description; } - getChannelsForSchema(schema) { - const channels = {}; - const shape = getInteropZodObjectShape(schema); - for (const [key, channelSchema] of Object.entries(shape)) { - const meta3 = this.get(channelSchema); - if (meta3?.reducer) - channels[key] = new BinaryOperatorAggregate3(meta3.reducer.fn, meta3.default); - else - channels[key] = new LastValue3(meta3?.default); - } - return channels; + const title = pop(jsonSchema, "title"); + if (title !== undefined) { + strictSchema["title"] = title; } - getExtendedChannelSchemas(schema, effects) { - if (Object.keys(effects).length === 0) - return schema; - const cacheKey2 = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); - const cache2 = this._extensionCache.get(cacheKey2) ?? /* @__PURE__ */ new Map; - if (cache2.has(schema)) - return cache2.get(schema); - let modifiedSchema = schema; - if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { - const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema2]) => { - const meta3 = this.get(schema2); - let outputSchema = effects.withReducerSchema ? meta3?.reducer?.schema ?? schema2 : schema2; - if (effects.withJsonSchemaExtrasAsDescription && meta3?.jsonSchemaExtra) { - const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema2); - const strExtras = JSON.stringify({ - ...meta3.jsonSchemaExtra, - description - }); - outputSchema = outputSchema.describe(`lg:${strExtras}`); - } - return [key, outputSchema]; - }); - modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); - if (isZodSchemaV3(modifiedSchema)) - modifiedSchema._def.unknownKeys = "strip"; + if (type === "object") { + const properties = pop(jsonSchema, "properties") || {}; + strictSchema["properties"] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ + key, + _transformJSONSchema(propSchema) + ])); + pop(jsonSchema, "additionalProperties"); + strictSchema["additionalProperties"] = false; + const required3 = pop(jsonSchema, "required"); + if (required3 !== undefined) { + strictSchema["required"] = required3; + } + } else if (type === "string") { + const format3 = pop(jsonSchema, "format"); + if (format3 !== undefined && SUPPORTED_STRING_FORMATS.has(format3)) { + strictSchema["format"] = format3; + } else if (format3 !== undefined) { + jsonSchema["format"] = format3; + } + } else if (type === "array") { + const items = pop(jsonSchema, "items"); + if (items !== undefined) { + strictSchema["items"] = _transformJSONSchema(items); + } + const minItems = pop(jsonSchema, "minItems"); + if (minItems !== undefined && (minItems === 0 || minItems === 1)) { + strictSchema["minItems"] = minItems; + } else if (minItems !== undefined) { + jsonSchema["minItems"] = minItems; } - if (effects.asPartial) - modifiedSchema = interopZodObjectPartial(modifiedSchema); - cache2.set(schema, modifiedSchema); - this._extensionCache.set(cacheKey2, cache2); - return modifiedSchema; } -}, schemaMetaRegistry2; -var init_meta2 = __esm(() => { - init_binop2(); - init_last_value2(); - init_types3(); - schemaMetaRegistry2 = new SchemaMetaRegistry2; -}); + if (Object.keys(jsonSchema).length > 0) { + const existingDescription = strictSchema["description"]; + strictSchema["description"] = (existingDescription ? existingDescription + ` -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/types.js -function isStateDefinitionInit2(value) { - if (value == null) - return false; - if (StateSchema2.isInstance(value)) - return true; - if (isInteropZodObject(value)) - return true; - if (typeof value === "object" && "lc_graph_name" in value && value.lc_graph_name === "AnnotationRoot") - return true; - if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.values(value).every((v) => typeof v === "function" || isBaseChannel2(v))) - return true; - return false; -} -function isStateGraphInit2(value) { - if (typeof value !== "object" || value == null) - return false; - const obj = value; - const hasState = "state" in obj && isStateDefinitionInit2(obj.state); - const hasStateSchema = "stateSchema" in obj && isStateDefinitionInit2(obj.stateSchema); - const hasInput = "input" in obj && isStateDefinitionInit2(obj.input); - if (!hasState && !hasStateSchema && !hasInput) - return false; - if ("input" in obj && obj.input != null && !isStateDefinitionInit2(obj.input)) - return false; - if ("output" in obj && obj.output != null && !isStateDefinitionInit2(obj.output)) - return false; - return true; +` : "") + "{" + Object.entries(jsonSchema).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ") + "}"; + } + return strictSchema; } -var init_types15 = __esm(() => { - init_constants8(); - init_base17(); - init_schema2(); - init_types3(); +var SUPPORTED_STRING_FORMATS; +var init_transform_json_schema = __esm(() => { + init_utils19(); + SUPPORTED_STRING_FORMATS = new Set([ + "date-time", + "time", + "date", + "duration", + "email", + "hostname", + "uri", + "ipv4", + "ipv6", + "uuid" + ]); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/state.js -function _getChannels2(schema) { - const channels = {}; - for (const [name, val] of Object.entries(schema)) - if (name === ROOT3) - channels[name] = getChannel2(val); - else - channels[name] = getChannel2(val); - return channels; +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/chat_models.js +function defaultMaxOutputTokensForModel(model) { + if (!model) + return FALLBACK_MAX_OUTPUT_TOKENS; + return Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1] ?? FALLBACK_MAX_OUTPUT_TOKENS; } -function isStateGraphArgs2(obj) { - return typeof obj === "object" && obj !== null && obj.channels !== undefined; +function _toolsInParams(params) { + return !!(params.tools && params.tools.length > 0); } -function _controlBranch2(value) { - if (_isSend2(value)) - return [value]; - const commands = []; - if (isCommand2(value)) - commands.push(value); - else if (Array.isArray(value)) - commands.push(...value.filter(isCommand2)); - const destinations = []; - for (const command of commands) { - if (command.graph === Command2.PARENT) - throw new ParentCommand2(command); - if (_isSend2(command.goto)) - destinations.push(command.goto); - else if (typeof command.goto === "string") - destinations.push(command.goto); - else if (Array.isArray(command.goto)) - destinations.push(...command.goto); +function _documentsInParams(params) { + for (const message of params.messages ?? []) { + if (typeof message.content === "string") + continue; + for (const block of message.content ?? []) + if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) + return true; } - return destinations; + return false; } -function _getControlBranch2() { - return new Branch2({ path: new RunnableCallable3({ - func: _controlBranch2, - tags: [TAG_HIDDEN2], - trace: false, - recurse: false, - name: "" - }) }); +function _thinkingInParams(params) { + return !!(params.thinking && (params.thinking.type === "enabled" || params.thinking.type === "adaptive")); } -var ROOT3 = "__root__", PartialStateSchema2, StateGraph2, CompiledStateGraph2; -var init_state4 = __esm(() => { - init_constants8(); - init_errors10(); - init_last_value2(); - init_annotation3(); - init_utils17(); - init_write2(); - init_read2(); - init_subgraph2(); - init_ephemeral_value2(); - init_graph4(); - init_named_barrier_value2(); - init_schema2(); - init_state3(); - init_meta2(); - init_types15(); - init_runnables(); +function _compactionInParams(params) { + return !!params.context_management?.edits?.some((e) => e.type === "compact_20260112"); +} +function isAnthropicTool(tool2) { + return "input_schema" in tool2; +} +function isBuiltinTool(tool2) { + return typeof tool2 === "object" && tool2 !== null && "type" in tool2 && (("name" in tool2) || ("mcp_server_name" in tool2)) && typeof tool2.type === "string" && [ + "text_editor_", + "computer_", + "bash_", + "web_search_", + "web_fetch_", + "str_replace_editor_", + "str_replace_based_edit_tool_", + "code_execution_", + "memory_", + "tool_search_", + "mcp_toolset" + ].some((prefix) => typeof tool2.type === "string" && tool2.type.startsWith(prefix)); +} +function _combineBetas(a, b, ...rest) { + return Array.from(new Set([ + ...a ?? [], + ...b ?? [], + ...rest.flatMap((x) => Array.from(x)) + ])); +} +function extractToken(chunk) { + if (typeof chunk.content === "string") + return chunk.content; + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) + return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") + return chunk.content[0].text; +} +var MODEL_DEFAULT_MAX_OUTPUT_TOKENS, FALLBACK_MAX_OUTPUT_TOKENS = 4096, ChatAnthropicMessages, ChatAnthropic; +var init_chat_models3 = __esm(() => { + init_output_parsers3(); + init_tools5(); + init_message_inputs(); + init_params(); + init_message_outputs(); + init_errors13(); + init_profiles2(); + init_stream_events(); + init_sdk(); + init_transform_json_schema(); + init_messages(); + init_outputs(); + init_env(); + init_chat_models(); + init_base5(); + init_json_schema3(); init_types3(); - PartialStateSchema2 = Symbol.for("langgraph.state.partial"); - StateGraph2 = class extends Graph$12 { - channels = {}; - waitingEdges = /* @__PURE__ */ new Set; - _schemaDefinition; - _schemaRuntimeDefinition; - _inputDefinition; - _inputRuntimeDefinition; - _outputDefinition; - _outputRuntimeDefinition; - _schemaDefinitions = /* @__PURE__ */ new Map; - _metaRegistry = schemaMetaRegistry2; - _configSchema; - _configRuntimeSchema; - _interrupt; - _writer; - constructor(stateOrInit, options) { - super(); - const init = this._normalizeToStateGraphInit(stateOrInit, options); - const stateSchema4 = init.state ?? init.stateSchema ?? init.input; - if (!stateSchema4) - throw new StateGraphInputError2; - const stateChannelDef = this._getChannelsFromSchema(stateSchema4); - this._schemaDefinition = stateChannelDef; - if (StateSchema2.isInstance(stateSchema4)) - this._schemaRuntimeDefinition = stateSchema4; - else if (isInteropZodObject(stateSchema4)) - this._schemaRuntimeDefinition = stateSchema4; - if (init.input) - if (StateSchema2.isInstance(init.input)) - this._inputRuntimeDefinition = init.input; - else if (isInteropZodObject(init.input)) - this._inputRuntimeDefinition = init.input; - else - this._inputRuntimeDefinition = PartialStateSchema2; - else - this._inputRuntimeDefinition = PartialStateSchema2; - if (init.output) - if (StateSchema2.isInstance(init.output)) - this._outputRuntimeDefinition = init.output; - else if (isInteropZodObject(init.output)) - this._outputRuntimeDefinition = init.output; - else - this._outputRuntimeDefinition = this._schemaRuntimeDefinition; - else - this._outputRuntimeDefinition = this._schemaRuntimeDefinition; - const inputChannelDef = init.input ? this._getChannelsFromSchema(init.input) : stateChannelDef; - const outputChannelDef = init.output ? this._getChannelsFromSchema(init.output) : stateChannelDef; - this._inputDefinition = inputChannelDef; - this._outputDefinition = outputChannelDef; - this._addSchema(this._schemaDefinition); - this._addSchema(this._inputDefinition); - this._addSchema(this._outputDefinition); - if (init.context) { - if (isInteropZodObject(init.context)) - this._configRuntimeSchema = init.context; - } - this._interrupt = init.interrupt; - this._writer = init.writer; + init_function_calling(); + init_standard_schema(); + init_structured_output(); + MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { + "claude-opus-4-7": 16384, + "claude-opus-4-6": 16384, + "claude-sonnet-4-6": 16384, + "claude-opus-4-5": 16384, + "claude-sonnet-4-5": 16384, + "claude-haiku-4-5": 16384, + "claude-opus-4-1": 16384, + "claude-sonnet-4": 16384, + "claude-opus-4": 16384, + "claude-3-7-sonnet": 8192, + "claude-3-5-sonnet": 8192, + "claude-3-5-haiku": 8192, + "claude-3-opus": 4096, + "claude-3-sonnet": 4096, + "claude-3-haiku": 4096 + }; + ChatAnthropicMessages = class extends BaseChatModel { + static lc_name() { + return "ChatAnthropic"; } - _normalizeToStateGraphInit(stateOrInit, options) { - if (isStateGraphInit2(stateOrInit)) { - if (isInteropZodObject(options) || AnnotationRoot2.isInstance(options)) + get lc_secrets() { + return { + anthropicApiKey: "ANTHROPIC_API_KEY", + apiKey: "ANTHROPIC_API_KEY" + }; + } + get lc_aliases() { + return { modelName: "model" }; + } + lc_serializable = true; + anthropicApiKey; + apiKey; + apiUrl; + temperature; + topK; + topP; + maxTokens; + modelName = "claude-sonnet-4-5-20250929"; + model = "claude-sonnet-4-5-20250929"; + invocationKwargs; + stopSequences; + streaming = false; + clientOptions; + thinking = { type: "disabled" }; + contextManagement; + outputConfig; + inferenceGeo; + batchClient; + streamingClient; + streamUsage = true; + betas; + createClient; + constructor(modelOrFields, fieldsArg) { + const fields = typeof modelOrFields === "string" ? { + ...fieldsArg ?? {}, + model: modelOrFields + } : modelOrFields ?? {}; + super(fields ?? {}); + this._addVersion("@langchain/anthropic", "1.4.0"); + this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); + if (!this.anthropicApiKey && !fields?.createClient) + throw new Error("Anthropic API key not found"); + this.clientOptions = fields?.clientOptions ?? {}; + this.apiKey = this.anthropicApiKey; + this.apiUrl = fields?.anthropicApiUrl; + this.modelName = fields?.model ?? fields?.modelName ?? this.model; + this.model = this.modelName; + this.invocationKwargs = fields?.invocationKwargs ?? {}; + this.topP = fields?.topP ?? this.topP; + this.temperature = fields?.temperature ?? this.temperature; + this.topK = fields?.topK ?? this.topK; + this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); + this.stopSequences = fields?.stopSequences ?? this.stopSequences; + this.streaming = fields?.streaming ?? false; + this.streamUsage = fields?.streamUsage ?? this.streamUsage; + this.thinking = fields?.thinking ?? this.thinking; + this.contextManagement = fields?.contextManagement ?? this.contextManagement; + this.outputConfig = fields?.outputConfig ?? this.outputConfig; + this.inferenceGeo = fields?.inferenceGeo ?? this.inferenceGeo; + this.betas = fields?.betas ?? this.betas; + this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "anthropic", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.temperature ?? undefined, + ls_max_tokens: params.max_tokens ?? undefined, + ls_stop: options.stop + }; + } + formatStructuredToolToAnthropic(tools, fields) { + if (!tools) + return; + return tools.map((tool2) => { + if (isLangChainTool(tool2) && tool2.extras?.providerToolDefinition) + return tool2.extras.providerToolDefinition; + if (isBuiltinTool(tool2)) + return tool2; + if (isAnthropicTool(tool2)) { + if (fields?.strict !== undefined) + return { + ...tool2, + strict: fields.strict + }; + return tool2; + } + if (isOpenAITool(tool2)) { + const functionStrict = "strict" in tool2.function && typeof tool2.function.strict === "boolean" ? tool2.function.strict : undefined; + const strict = fields?.strict ?? functionStrict; return { - ...stateOrInit, - context: options + name: tool2.function.name, + description: tool2.function.description, + input_schema: tool2.function.parameters, + ...strict !== undefined ? { strict } : {} }; - const opts = options; - return { - ...stateOrInit, - input: stateOrInit.input ?? opts?.input, - output: stateOrInit.output ?? opts?.output, - context: stateOrInit.context ?? opts?.context, - interrupt: stateOrInit.interrupt ?? opts?.interrupt, - writer: stateOrInit.writer ?? opts?.writer, - nodes: stateOrInit.nodes ?? opts?.nodes - }; - } - if (isStateDefinitionInit2(stateOrInit)) { - if (isInteropZodObject(options) || AnnotationRoot2.isInstance(options)) + } + if (isLangChainTool(tool2)) { + const { strict: extrasStrict, ...restExtras } = tool2.extras ? AnthropicToolExtrasSchema.parse(tool2.extras) : {}; + const strict = fields?.strict ?? extrasStrict; return { - state: stateOrInit, - context: options + name: tool2.name, + description: tool2.description, + input_schema: isInteropZodSchema(tool2.schema) ? toJsonSchema(tool2.schema) : tool2.schema, + ...restExtras, + ...strict !== undefined ? { strict } : {} }; - const opts = options; - return { - state: stateOrInit, - input: opts?.input, - output: opts?.output, - context: opts?.context, - interrupt: opts?.interrupt, - writer: opts?.writer, - nodes: opts?.nodes - }; - } - if (isStateGraphArgs2(stateOrInit)) - return { state: _getChannels2(stateOrInit.channels) }; - throw new StateGraphInputError2; - } - _getChannelsFromSchema(schema) { - if (StateSchema2.isInstance(schema)) - return schema.getChannels(); - if (isInteropZodObject(schema)) - return this._metaRegistry.getChannelsForSchema(schema); - if (typeof schema === "object" && "lc_graph_name" in schema && schema.lc_graph_name === "AnnotationRoot") - return schema.spec; - if (typeof schema === "object" && !Array.isArray(schema) && Object.keys(schema).length > 0) - return schema; - throw new StateGraphInputError2("Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition."); - } - get allEdges() { - return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); + } + throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool2, null, 2)}`); + }); } - _addSchema(stateDefinition) { - if (this._schemaDefinitions.has(stateDefinition)) - return; - this._schemaDefinitions.set(stateDefinition, stateDefinition); - for (const [key, val] of Object.entries(stateDefinition)) { - let channel; - if (typeof val === "function") - channel = val(); - else - channel = val; - if (this.channels[key] !== undefined) { - if (!this.channels[key].equals(channel)) { - if (channel.lc_graph_name !== "LastValue") - throw new Error(`Channel "${key}" already exists with a different type.`); - } - } else - this.channels[key] = channel; - } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: this.formatStructuredToolToAnthropic(tools, { strict: kwargs?.strict }), + ...kwargs + }); } - addNode(...args) { - function isMultipleNodes(args2) { - return args2.length >= 1 && typeof args2[0] !== "string"; - } - const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) - throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - if (key in this.channels) - throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); - for (const reservedChar of ["|", ":"]) - if (key.includes(reservedChar)) - throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) - throw new Error(`Node \`${key}\` already present.`); - if (key === "__end__" || key === "__start__") - throw new Error(`Node \`${key}\` is reserved.`); - let inputSpec = this._schemaDefinition; - if (options?.input !== undefined) - inputSpec = this._getChannelsFromSchema(options.input); - this._addSchema(inputSpec); - let runnable; - if (Runnable.isRunnable(action)) - runnable = action; - else if (typeof action === "function") - runnable = new RunnableCallable3({ - func: action, - name: key, - trace: false - }); - else - runnable = _coerceToRunnable(action); - let cachePolicy = options?.cachePolicy; - if (typeof cachePolicy === "boolean") - cachePolicy = cachePolicy ? {} : undefined; - const nodeSpec = { - runnable, - retryPolicy: options?.retryPolicy, - cachePolicy, - metadata: options?.metadata, - input: inputSpec ?? this._schemaDefinition, - subgraphs: isPregelLike2(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends, - defer: options?.defer + invocationParams(options) { + const tool_choice = handleToolChoice(options?.tool_choice); + const toolBetas = options?.tools?.reduce((acc, tool2) => { + if (typeof tool2 === "object" && "type" in tool2 && tool2.type in ANTHROPIC_TOOL_BETAS) { + const beta = ANTHROPIC_TOOL_BETAS[tool2.type]; + if (!acc.includes(beta)) + return [...acc, beta]; + } + return acc; + }, []); + const mergedOutputConfig = (() => { + const base = { + ...this.outputConfig, + ...options?.outputConfig }; - this.nodes[key] = nodeSpec; - } - return this; + if (options?.outputFormat && !base.format) + base.format = options.outputFormat; + return Object.keys(base).length > 0 ? base : undefined; + })(); + const compactionBetas = this.contextManagement?.edits?.some((e) => e.type === "compact_20260112") ? ["compact-2026-01-12"] : []; + const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig); + const output = { + model: this.model, + stop_sequences: options?.stop ?? this.stopSequences, + stream: this.streaming, + max_tokens: this.maxTokens, + tools: this.formatStructuredToolToAnthropic(options?.tools, { strict: options?.strict }), + tool_choice, + thinking: this.thinking, + context_management: this.contextManagement, + ...this.invocationKwargs, + container: options?.container, + betas: _combineBetas(this.betas, options?.betas, toolBetas ?? [], compactionBetas, taskBudgetBetas), + output_config: mergedOutputConfig, + inference_geo: options?.inferenceGeo ?? this.inferenceGeo, + mcp_servers: options?.mcp_servers, + cache_control: options?.cache_control + }; + validateInvocationParamCompatibility({ + model: this.model, + thinking: this.thinking, + topK: this.topK, + topP: this.topP, + temperature: this.temperature + }); + Object.assign(output, getSamplingParams({ + model: this.model, + thinking: this.thinking, + topK: this.topK, + topP: this.topP, + temperature: this.temperature + })); + return output; } - addEdge(startKey, endKey) { - if (typeof startKey === "string") - return super.addEdge(startKey, endKey); - if (this.compiled) - console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - for (const start of startKey) { - if (start === "__end__") - throw new Error("END cannot be a start node"); - if (!Object.keys(this.nodes).some((node) => node === start)) - throw new Error(`Need to add a node named "${start}" first`); - } - if (endKey === "__end__") - throw new Error("END cannot be an end node"); - if (!Object.keys(this.nodes).some((node) => node === endKey)) - throw new Error(`Need to add a node named "${endKey}" first`); - this.waitingEdges.add([startKey, endKey]); - return this; + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; } - addSequence(nodes) { - const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); - if (parsedNodes.length === 0) - throw new Error("Sequence requires at least one node."); - let previousNode; - for (const [key, action, options] of parsedNodes) { - if (key in this.nodes) - throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); - const validKey = key; - this.addNode(validKey, action, options); - if (previousNode != null) - this.addEdge(previousNode, validKey); - previousNode = validKey; - } - return this; + identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; } - compile({ checkpointer, store, cache: cache2, interruptBefore, interruptAfter, name, description, transformers } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); - const outputChannels = outputKeys.length === 1 && outputKeys[0] === ROOT3 ? ROOT3 : outputKeys; - const streamKeys = Object.keys(this.channels); - const streamChannels = streamKeys.length === 1 && streamKeys[0] === ROOT3 ? ROOT3 : streamKeys; - const userInterrupt = this._interrupt; - const compiled = new CompiledStateGraph2({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - ...this.channels, - [START2]: new EphemeralValue3 - }, - inputChannels: START2, - outputChannels, - streamChannels, - streamMode: "updates", - store, - cache: cache2, - name, - description, - userInterrupt, - streamTransformers: transformers + async* _streamResponseChunks(messages, options, runManager) { + const params = this.invocationParams(options); + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const payload = { + ...params, + ...formattedMessages, + stream: true + }; + const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload) && !_compactionInParams(payload); + const stream2 = await this.createStreamWithRetry(payload, { + headers: options.headers, + signal: options.signal }); - compiled.attachNode(START2); - for (const [key, node] of Object.entries(this.nodes)) - compiled.attachNode(key, node); - compiled.attachBranch(START2, SELF2, _getControlBranch2(), { withReader: false }); - for (const [key] of Object.entries(this.nodes)) - compiled.attachBranch(key, SELF2, _getControlBranch2(), { withReader: false }); - for (const [start, end] of this.edges) - compiled.attachEdge(start, end); - for (const [starts, end] of this.waitingEdges) - compiled.attachEdge(starts, end); - for (const [start, branches] of Object.entries(this.branches)) - for (const [name2, branch] of Object.entries(branches)) - compiled.attachBranch(start, name2, branch); - return compiled.validate(); - } - }; - CompiledStateGraph2 = class extends CompiledGraph2 { - description; - _metaRegistry = schemaMetaRegistry2; - constructor({ description, ...rest }) { - super(rest); - this.description = description; - } - attachNode(key, node) { - let outputKeys; - if (key === "__start__") - outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); - else - outputKeys = Object.keys(this.builder.channels); - function _getRoot(input) { - if (isCommand2(input)) { - if (input.graph === Command2.PARENT) - return null; - return input._updateAsTuples(); - } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand2(i))) { - const updates = []; - for (const i of input) - if (isCommand2(i)) { - if (i.graph === Command2.PARENT) - continue; - updates.push(...i._updateAsTuples()); - } else - updates.push([ROOT3, i]); - return updates; - } else if (input != null) - return [[ROOT3, input]]; - return null; - } - const nodeKey = key; - function _getUpdates(input) { - if (!input) - return null; - else if (isCommand2(input)) { - if (input.graph === Command2.PARENT) - return null; - return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); - } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand2)) { - const updates = []; - for (const item of input) - if (isCommand2(item)) { - if (item.graph === Command2.PARENT) - continue; - updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); - } else { - const itemUpdates = _getUpdates(item); - if (itemUpdates) - updates.push(...itemUpdates ?? []); - } - return updates; - } else if (typeof input === "object" && !Array.isArray(input)) - return Object.entries(input).filter(([k]) => outputKeys.includes(k)); - else { - const typeofInput = Array.isArray(input) ? "array" : typeof input; - throw new InvalidUpdateError2(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); + for await (const data of stream2) { + if (options.signal?.aborted) { + stream2.controller.abort(); + return; } - } - const stateWriteEntries = [{ - value: PASSTHROUGH2, - mapper: new RunnableCallable3({ - func: outputKeys.length && outputKeys[0] === ROOT3 ? _getRoot : _getUpdates, - trace: false, - recurse: false - }) - }]; - if (key === "__start__") - this.nodes[key] = new PregelNode3({ - tags: [TAG_HIDDEN2], - triggers: [START2], - channels: [START2], - writers: [new ChannelWrite3(stateWriteEntries, [TAG_HIDDEN2])] + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const result = _makeMessageChunkFromAnthropicEvent(data, { + streamUsage: shouldStreamUsage, + coerceContentToString }); - else { - const inputDefinition = node?.input ?? this.builder._schemaDefinition; - const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); - const isSingleInput = Object.keys(inputValues).length === 1 && ROOT3 in inputValues; - const branchChannel = `branch:to:${key}`; - this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish3 : new EphemeralValue3(false); - this.nodes[key] = new PregelNode3({ - triggers: [branchChannel], - channels: isSingleInput ? Object.keys(inputValues) : inputValues, - writers: [new ChannelWrite3(stateWriteEntries, [TAG_HIDDEN2])], - mapper: isSingleInput ? undefined : (input) => { - return Object.fromEntries(Object.entries(input).filter(([k]) => (k in inputValues))); - }, - bound: node?.runnable, - metadata: node?.metadata, - retryPolicy: node?.retryPolicy, - cachePolicy: node?.cachePolicy, - subgraphs: node?.subgraphs, - ends: node?.ends + if (!result) + continue; + const { chunk } = result; + const token = extractToken(chunk); + const generationChunk = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: chunk.content, + additional_kwargs: chunk.additional_kwargs, + tool_call_chunks: chunk.tool_call_chunks, + usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined, + response_metadata: chunk.response_metadata, + id: chunk.id + }), + text: token ?? "" }); + yield generationChunk; + await runManager?.handleLLMNewToken(token ?? "", undefined, undefined, undefined, undefined, { chunk: generationChunk }); } } - attachEdge(starts, end) { - if (end === "__end__") - return; - if (typeof starts === "string") - this.nodes[starts].writers.push(new ChannelWrite3([{ - channel: `branch:to:${end}`, - value: null - }], [TAG_HIDDEN2])); - else if (Array.isArray(starts)) { - const channelName = `join:${starts.join("+")}:${end}`; - this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish3(new Set(starts)) : new NamedBarrierValue3(new Set(starts)); - this.nodes[end].triggers.push(channelName); - for (const start of starts) - this.nodes[start].writers.push(new ChannelWrite3([{ - channel: channelName, - value: start - }], [TAG_HIDDEN2])); - } + async* _streamChatModelEvents(messages, options, _runManager) { + const params = this.invocationParams(options); + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const payload = { + ...params, + ...formattedMessages, + stream: true + }; + const stream2 = await this.createStreamWithRetry(payload, { + headers: options.headers, + signal: options.signal + }); + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const abortableStream = async function* (source, signal) { + for await (const data of source) { + if (signal?.aborted) { + source.controller?.abort(); + return; + } + yield data; + } + }; + yield* convertAnthropicStream(abortableStream(stream2, options.signal), { streamUsage: shouldStreamUsage ?? true }); } - attachBranch(start, _, branch, options = { withReader: true }) { - const branchWriter = async (packets, config3) => { - const filteredPackets = packets.filter((p) => p !== END2); - if (!filteredPackets.length) - return; - const writes = filteredPackets.map((p) => { - if (_isSend2(p)) - return p; - return { - channel: p === "__end__" ? p : `branch:to:${p}`, - value: start - }; - }); - await ChannelWrite3.doWrite({ - ...config3, - tags: (config3.tags ?? []).concat([TAG_HIDDEN2]) - }, writes); + async _generateNonStreaming(messages, params, requestOptions) { + const formattedMessages = _convertMessagesToAnthropicPayload(messages); + const { content, ...additionalKwargs } = await this.completionWithRetry({ + ...params, + stream: false, + ...formattedMessages + }, requestOptions); + const generations = anthropicResponseToChatMessages(content, additionalKwargs); + const { role: _role, type: _type, ...rest } = additionalKwargs; + return { + generations, + llmOutput: rest }; - this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config3) => ChannelRead3.doRead(config3, this.streamChannels ?? this.outputChannels, true) : undefined)); } - async _validateInput(input) { - if (input == null) - return input; - const inputDef = this.builder._inputRuntimeDefinition; - const schemaDef = this.builder._schemaRuntimeDefinition; - if (StateSchema2.isInstance(inputDef)) { - if (isCommand2(input)) { - const parsedInput = input; - if (input.update) - parsedInput.update = await inputDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); - return parsedInput; - } - return await inputDef.validateInput(input); + async _generate(messages, options, runManager) { + options.signal?.throwIfAborted(); + if (this.stopSequences && options.stop) + throw new Error(`"stopSequence" parameter found in input and default params`); + const params = this.invocationParams(options); + if (params.stream) { + let finalChunk; + const stream2 = this._streamResponseChunks(messages, options, runManager); + for await (const chunk of stream2) + if (finalChunk === undefined) + finalChunk = chunk; + else + finalChunk = finalChunk.concat(chunk); + if (finalChunk === undefined) + throw new Error("No chunks returned from Anthropic API."); + return { generations: [{ + text: finalChunk.text, + message: finalChunk.message + }] }; + } else + return this._generateNonStreaming(messages, params, { + signal: options.signal, + headers: options.headers + }); + } + async createStreamWithRetry(request, options) { + if (!this.streamingClient) { + const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined; + this.streamingClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options_, + apiKey: this.apiKey, + maxRetries: 0 + }); } - if (inputDef === PartialStateSchema2 && StateSchema2.isInstance(schemaDef)) { - if (isCommand2(input)) { - const parsedInput = input; - if (input.update) - parsedInput.update = await schemaDef.validateInput(Array.isArray(input.update) ? Object.fromEntries(input.update) : input.update); - return parsedInput; + const { betas, ...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) + return await this.streamingClient.beta.messages.create({ + ...rest, + betas, + ...this.invocationKwargs, + stream: true + }, options); + return await this.streamingClient.messages.create({ + ...rest, + ...this.invocationKwargs, + stream: true + }, options); + } catch (e) { + throw wrapAnthropicClientError(e); } - return await schemaDef.validateInput(input); + }; + return this.caller.call(makeCompletionRequest); + } + async completionWithRetry(request, options) { + if (!this.batchClient) { + const options2 = this.apiUrl ? { baseURL: this.apiUrl } : undefined; + this.batchClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options2, + apiKey: this.apiKey, + maxRetries: 0 + }); } - const schema = (() => { - const apply = (schema2) => { - if (schema2 == null) - return; - return this._metaRegistry.getExtendedChannelSchemas(schema2, { withReducerSchema: true }); - }; - if (isInteropZodObject(inputDef)) - return apply(inputDef); - if (inputDef === PartialStateSchema2) { - if (isInteropZodObject(schemaDef)) - return interopZodObjectPartial(apply(schemaDef)); - return; + const { betas, ...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) + return await this.batchClient.beta.messages.create({ + ...rest, + ...this.invocationKwargs, + betas + }, options); + return await this.batchClient.messages.create({ + ...rest, + ...this.invocationKwargs + }, options); + } catch (e) { + throw wrapAnthropicClientError(e); } - })(); - if (isCommand2(input)) { - const parsedInput = input; - if (input.update && schema != null) - parsedInput.update = interopParse(schema, input.update); - return parsedInput; - } - if (schema != null) - return interopParse(schema, input); - return input; + }; + return this.caller.callWithOptions({ signal: options.signal ?? undefined }, makeCompletionRequest); } - isInterrupted(input) { - return isInterrupted2(input); + _llmType() { + return "anthropic"; } - async _validateContext(config3) { - const configSchema = this.builder._configRuntimeSchema; - if (isInteropZodObject(configSchema)) - interopParse(configSchema, config3); - return config3; + get profile() { + return PROFILES[this.model] ?? {}; + } + withStructuredOutput(outputSchema, config3) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config3, + schema: outputSchema + }; + let method = config3?.method ?? "functionCalling"; + if (config3?.strict !== undefined && method !== "functionCalling") + throw new Error(`Argument \`strict\` is only supported for \`method\` = "functionCalling" on Anthropic models. Got method = "${method}".`); + if (method === "jsonMode") { + console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`); + method = "jsonSchema"; + } + if (method === "jsonSchema") { + outputParser = createContentParser(schema); + const jsonSchema = transformJSONSchema(toJsonSchema(schema)); + llm = this.withConfig({ + outputVersion: "v0", + outputConfig: { format: { + type: "json_schema", + schema: jsonSchema + } }, + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: jsonSchema + } + }); + } else if (method === "functionCalling") { + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema) || isSerializableSchema(schema)) { + const jsonSchema = toJsonSchema(schema); + tools = [{ + name: functionName, + description: jsonSchema.description ?? "A function available to call.", + input_schema: jsonSchema + }]; + } else if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { + tools = [schema]; + functionName = schema.name; + } else + tools = [{ + name: functionName, + description: schema.description ?? "", + input_schema: schema + }]; + outputParser = createFunctionCallingParser(schema, functionName, AnthropicToolsOutputParser); + if (this.thinking?.type === "enabled" || this.thinking?.type === "adaptive") { + const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; + console.warn(thinkingAdmonition); + llm = this.withConfig({ + outputVersion: "v0", + tools, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + }, + ...config3?.strict !== undefined ? { strict: config3.strict } : {} + }); + const raiseIfNoToolCalls = (message) => { + if (!message.tool_calls || message.tool_calls.length === 0) + throw new Error(thinkingAdmonition); + return message; + }; + llm = llm.pipe(raiseIfNoToolCalls); + } else + llm = this.withConfig({ + outputVersion: "v0", + tools, + tool_choice: { + type: "tool", + name: functionName + }, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + }, + ...config3?.strict !== undefined ? { strict: config3.strict } : {} + }); + } else + throw new TypeError(`Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`); + return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatAnthropicStructuredOutput"); } }; + ChatAnthropic = class extends ChatAnthropicMessages { + }; }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/message.js -function pushMessage2(message, options) { - const { stateKey: userStateKey, ...userConfig } = options ?? {}; - const config3 = ensureLangGraphConfig2(userConfig); - let stateKey = userStateKey ?? "messages"; - if (userStateKey === null) - stateKey = undefined; - const validMessage = coerceMessageLikeToMessage(message); - if (!validMessage.id) - throw new Error("Message ID is required."); - const messagesHandler = (() => { - if (Array.isArray(config3.callbacks)) - return config3.callbacks; - if (typeof config3.callbacks !== "undefined") - return config3.callbacks.handlers; - return []; - })().find((cb) => ("name" in cb) && cb.name === "StreamMessagesHandler"); - if (messagesHandler) { - const metadata = config3.metadata ?? {}; - const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); - messagesHandler._emit([namespace, metadata], validMessage, undefined, false); - } - if (stateKey) - config3.configurable?.__pregel_send?.([[stateKey, validMessage]]); - return validMessage; +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/utils/prompts.js +function convertPromptToAnthropic(formattedPrompt) { + const anthropicBody = _convertMessagesToAnthropicPayload(formattedPrompt.toChatMessages()); + if (anthropicBody.messages === undefined) + anthropicBody.messages = []; + return anthropicBody; } -var MessageGraph2; -var init_message3 = __esm(() => { - init_config3(); - init_messages_reducer2(); - init_state4(); - init_messages(); - MessageGraph2 = class extends StateGraph2 { - constructor() { - super({ channels: { __root__: { - reducer: messagesStateReducer2, - default: () => [] - } } }); +var init_prompts3 = __esm(() => { + init_message_inputs(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/types.js +var Memory20250818ViewCommandSchema, Memory20250818CreateCommandSchema, Memory20250818StrReplaceCommandSchema, Memory20250818InsertCommandSchema, Memory20250818DeleteCommandSchema, Memory20250818RenameCommandSchema, Memory20250818CommandSchema, TextEditor20250728ViewCommandSchema, TextEditor20250728StrReplaceCommandSchema, TextEditor20250728CreateCommandSchema, TextEditor20250728InsertCommandSchema, TextEditor20250728CommandSchema, coordinateSchema, ComputerScreenshotActionSchema, ComputerLeftClickActionSchema, ComputerRightClickActionSchema, ComputerMiddleClickActionSchema, ComputerDoubleClickActionSchema, ComputerTripleClickActionSchema, ComputerLeftClickDragActionSchema, ComputerLeftMouseDownActionSchema, ComputerLeftMouseUpActionSchema, ComputerScrollActionSchema, ComputerTypeActionSchema, ComputerKeyActionSchema, ComputerMouseMoveActionSchema, ComputerHoldKeyActionSchema, ComputerWaitActionSchema, ComputerZoomActionSchema, Computer20250124ActionSchema, Computer20251124ActionSchema, Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema, Bash20250124CommandSchema; +var init_types17 = __esm(() => { + init_v43(); + Memory20250818ViewCommandSchema = exports_external3.object({ + command: exports_external3.literal("view"), + path: exports_external3.string() + }); + Memory20250818CreateCommandSchema = exports_external3.object({ + command: exports_external3.literal("create"), + path: exports_external3.string(), + file_text: exports_external3.string() + }); + Memory20250818StrReplaceCommandSchema = exports_external3.object({ + command: exports_external3.literal("str_replace"), + path: exports_external3.string(), + old_str: exports_external3.string(), + new_str: exports_external3.string() + }); + Memory20250818InsertCommandSchema = exports_external3.object({ + command: exports_external3.literal("insert"), + path: exports_external3.string(), + insert_line: exports_external3.number(), + insert_text: exports_external3.string() + }); + Memory20250818DeleteCommandSchema = exports_external3.object({ + command: exports_external3.literal("delete"), + path: exports_external3.string() + }); + Memory20250818RenameCommandSchema = exports_external3.object({ + command: exports_external3.literal("rename"), + old_path: exports_external3.string(), + new_path: exports_external3.string() + }); + Memory20250818CommandSchema = exports_external3.discriminatedUnion("command", [ + Memory20250818ViewCommandSchema, + Memory20250818CreateCommandSchema, + Memory20250818StrReplaceCommandSchema, + Memory20250818InsertCommandSchema, + Memory20250818DeleteCommandSchema, + Memory20250818RenameCommandSchema + ]); + TextEditor20250728ViewCommandSchema = exports_external3.object({ + command: exports_external3.literal("view"), + path: exports_external3.string(), + view_range: exports_external3.tuple([exports_external3.number(), exports_external3.number()]).optional() + }); + TextEditor20250728StrReplaceCommandSchema = exports_external3.object({ + command: exports_external3.literal("str_replace"), + path: exports_external3.string(), + old_str: exports_external3.string(), + new_str: exports_external3.string() + }); + TextEditor20250728CreateCommandSchema = exports_external3.object({ + command: exports_external3.literal("create"), + path: exports_external3.string(), + file_text: exports_external3.string() + }); + TextEditor20250728InsertCommandSchema = exports_external3.object({ + command: exports_external3.literal("insert"), + path: exports_external3.string(), + insert_line: exports_external3.number(), + new_str: exports_external3.string() + }); + TextEditor20250728CommandSchema = exports_external3.discriminatedUnion("command", [ + TextEditor20250728ViewCommandSchema, + TextEditor20250728StrReplaceCommandSchema, + TextEditor20250728CreateCommandSchema, + TextEditor20250728InsertCommandSchema + ]); + coordinateSchema = exports_external3.tuple([exports_external3.number(), exports_external3.number()]); + ComputerScreenshotActionSchema = exports_external3.object({ action: exports_external3.literal("screenshot") }); + ComputerLeftClickActionSchema = exports_external3.object({ + action: exports_external3.literal("left_click"), + coordinate: coordinateSchema + }); + ComputerRightClickActionSchema = exports_external3.object({ + action: exports_external3.literal("right_click"), + coordinate: coordinateSchema + }); + ComputerMiddleClickActionSchema = exports_external3.object({ + action: exports_external3.literal("middle_click"), + coordinate: coordinateSchema + }); + ComputerDoubleClickActionSchema = exports_external3.object({ + action: exports_external3.literal("double_click"), + coordinate: coordinateSchema + }); + ComputerTripleClickActionSchema = exports_external3.object({ + action: exports_external3.literal("triple_click"), + coordinate: coordinateSchema + }); + ComputerLeftClickDragActionSchema = exports_external3.object({ + action: exports_external3.literal("left_click_drag"), + start_coordinate: coordinateSchema, + end_coordinate: coordinateSchema + }); + ComputerLeftMouseDownActionSchema = exports_external3.object({ + action: exports_external3.literal("left_mouse_down"), + coordinate: coordinateSchema + }); + ComputerLeftMouseUpActionSchema = exports_external3.object({ + action: exports_external3.literal("left_mouse_up"), + coordinate: coordinateSchema + }); + ComputerScrollActionSchema = exports_external3.object({ + action: exports_external3.literal("scroll"), + coordinate: coordinateSchema, + scroll_direction: exports_external3.enum([ + "up", + "down", + "left", + "right" + ]), + scroll_amount: exports_external3.number() + }); + ComputerTypeActionSchema = exports_external3.object({ + action: exports_external3.literal("type"), + text: exports_external3.string() + }); + ComputerKeyActionSchema = exports_external3.object({ + action: exports_external3.literal("key"), + key: exports_external3.string() + }); + ComputerMouseMoveActionSchema = exports_external3.object({ + action: exports_external3.literal("mouse_move"), + coordinate: coordinateSchema + }); + ComputerHoldKeyActionSchema = exports_external3.object({ + action: exports_external3.literal("hold_key"), + key: exports_external3.string() + }); + ComputerWaitActionSchema = exports_external3.object({ + action: exports_external3.literal("wait"), + duration: exports_external3.number().optional() + }); + ComputerZoomActionSchema = exports_external3.object({ + action: exports_external3.literal("zoom"), + region: exports_external3.tuple([ + exports_external3.number(), + exports_external3.number(), + exports_external3.number(), + exports_external3.number() + ]) + }); + Computer20250124ActionSchema = exports_external3.discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema + ]); + Computer20251124ActionSchema = exports_external3.discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema, + ComputerZoomActionSchema + ]); + Bash20250124ExecuteCommandSchema = exports_external3.object({ command: exports_external3.string().describe("The bash command to run") }); + Bash20250124RestartCommandSchema = exports_external3.object({ restart: exports_external3.literal(true).describe("Set to true to restart the bash session") }); + Bash20250124CommandSchema = exports_external3.union([Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema]); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/memory.js +function memory_20250818(options) { + const memoryTool = tool(options?.execute, { + name: "memory", + schema: Memory20250818CommandSchema + }); + memoryTool.extras = { + ...memoryTool.extras ?? {}, + providerToolDefinition: { + type: "memory_20250818", + name: "memory" } }; + return memoryTool; +} +var init_memory5 = __esm(() => { + init_types17(); + init_tools2(); }); -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/func/index.js -function task2(optionsOrName, func) { - const options = typeof optionsOrName === "string" ? { - name: optionsOrName, - retry: undefined, - cachePolicy: undefined - } : optionsOrName; - const { name, retry } = options; - if (isAsyncGeneratorFunction2(func) || isGeneratorFunction2(func)) - throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); - const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : undefined); - let cache2; - if (typeof cachePolicy === "boolean") - cache2 = cachePolicy ? {} : undefined; - else - cache2 = cachePolicy; - return (...args) => { - return call3({ - func, +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/webSearch.js +function webSearch_20250305(options) { + return { + type: "web_search_20250305", + name: "web_search", + max_uses: options?.maxUses, + allowed_domains: options?.allowedDomains, + blocked_domains: options?.blockedDomains, + cache_control: options?.cacheControl, + defer_loading: options?.deferLoading, + strict: options?.strict, + user_location: options?.userLocation + }; +} +var init_webSearch = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/webFetch.js +function webFetch_20250910(options) { + return { + type: "web_fetch_20250910", + name: "web_fetch", + max_uses: options?.maxUses, + allowed_domains: options?.allowedDomains, + blocked_domains: options?.blockedDomains, + cache_control: options?.cacheControl, + citations: options?.citations, + max_content_tokens: options?.maxContentTokens + }; +} +var init_webFetch = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/toolSearch.js +function toolSearchRegex_20251119(options) { + return { + type: "tool_search_tool_regex_20251119", + name: "tool_search_tool_regex", + cache_control: options?.cacheControl + }; +} +function toolSearchBM25_20251119(options) { + return { + type: "tool_search_tool_bm25_20251119", + name: "tool_search_tool_bm25", + cache_control: options?.cacheControl + }; +} +var init_toolSearch = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/textEditor.js +function textEditor_20250728(options) { + const name = "str_replace_based_edit_tool"; + const textEditorTool = tool(options?.execute, { + name, + description: "A tool for editing text files", + schema: TextEditor20250728CommandSchema + }); + textEditorTool.extras = { + ...textEditorTool.extras ?? {}, + providerToolDefinition: { + type: "text_editor_20250728", name, - retry, - cache: cache2 - }, ...args); + ...options?.maxCharacters !== undefined && { max_characters: options.maxCharacters } + } + }; + return textEditorTool; +} +var init_textEditor = __esm(() => { + init_types17(); + init_tools2(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/computer.js +function computer_20251124(options) { + const name = TOOL_NAME; + const computerTool = tool(options.execute, { + name, + schema: Computer20251124ActionSchema + }); + computerTool.extras = { + ...computerTool.extras ?? {}, + providerToolDefinition: { + type: "computer_20251124", + name, + display_width_px: options.displayWidthPx, + display_height_px: options.displayHeightPx, + ...options.displayNumber !== undefined && { display_number: options.displayNumber }, + ...options.enableZoom !== undefined && { enable_zoom: options.enableZoom } + } }; + return computerTool; } -function getPreviousState2() { - return AsyncLocalStorageProviderSingleton2.getRunnableConfig().configurable?.[CONFIG_KEY_PREVIOUS_STATE2]; +function computer_20250124(options) { + const name = TOOL_NAME; + const computerTool = tool(options.execute, { + name, + description: "A tool for interacting with the computer", + schema: Computer20250124ActionSchema + }); + computerTool.extras = { + ...computerTool.extras ?? {}, + providerToolDefinition: { + type: "computer_20250124", + name, + display_width_px: options.displayWidthPx, + display_height_px: options.displayHeightPx, + ...options.displayNumber !== undefined && { display_number: options.displayNumber } + } + }; + return computerTool; } -var entrypoint3 = function entrypoint4(optionsOrName, func) { - const { name, checkpointer, store, cache: cache2 } = typeof optionsOrName === "string" ? { - name: optionsOrName, - checkpointer: undefined, - store: undefined - } : optionsOrName; - if (isAsyncGeneratorFunction2(func) || isGeneratorFunction2(func)) - throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); - const streamMode = "updates"; - const bound = getRunnableForEntrypoint2(name, func); - function isEntrypointFinal(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; +var TOOL_NAME = "computer"; +var init_computer = __esm(() => { + init_types17(); + init_tools2(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/codeExecution.js +function codeExecution_20250825(options) { + return { + type: "code_execution_20250825", + name: "code_execution", + cache_control: options?.cacheControl + }; +} +var init_codeExecution = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/bash.js +function bash_20250124(options) { + const name = "bash"; + const bashTool = tool(options?.execute, { + name, + description: "A tool for executing bash commands", + schema: Bash20250124CommandSchema + }); + bashTool.extras = { + ...bashTool.extras ?? {}, + providerToolDefinition: { + type: "bash_20250124", + name + } + }; + return bashTool; +} +var init_bash = __esm(() => { + init_types17(); + init_tools2(); +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/mcpToolset.js +function mcpToolset_20251120(options) { + const defaultConfig = options.defaultConfig?.enabled !== undefined || options.defaultConfig?.deferLoading !== undefined ? { + enabled: options.defaultConfig?.enabled, + defer_loading: options.defaultConfig?.deferLoading + } : undefined; + const configs = options.configs ? Object.fromEntries(Object.entries(options.configs).map(([toolName, config3]) => [toolName, { + enabled: config3.enabled, + defer_loading: config3.deferLoading + }])) : undefined; + return { + type: "mcp_toolset", + mcp_server_name: options.serverName, + default_config: defaultConfig, + configs, + cache_control: options.cacheControl + }; +} +var init_mcpToolset = () => {}; + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/tools/index.js +var tools; +var init_tools6 = __esm(() => { + init_memory5(); + init_webSearch(); + init_webFetch(); + init_toolSearch(); + init_textEditor(); + init_computer(); + init_codeExecution(); + init_bash(); + init_mcpToolset(); + tools = { + memory_20250818, + webSearch_20250305, + webFetch_20250910, + toolSearchRegex_20251119, + toolSearchBM25_20251119, + textEditor_20250728, + computer_20251124, + computer_20250124, + codeExecution_20250825, + bash_20250124, + mcpToolset_20251120 + }; +}); + +// ../../node_modules/.pnpm/@langchain+anthropic@1.4.0_@langchain+core@1.1.48_@opentelemetry+api@1.9.1_@opentelemetry+sdk_nrim6yfewv2f6yjwoyidqc7grm/node_modules/@langchain/anthropic/dist/index.js +var exports_dist3 = {}; +__export(exports_dist3, { + tools: () => tools, + convertPromptToAnthropic: () => convertPromptToAnthropic, + ChatAnthropicMessages: () => ChatAnthropicMessages, + ChatAnthropic: () => ChatAnthropic +}); +var init_dist10 = __esm(() => { + init_chat_models3(); + init_prompts3(); + init_tools6(); +}); + +// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js +var require_ms = __commonJS((exports, module) => { + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse16(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); + }; + function parse16(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); + if (!match2) { + return; + } + var n4 = parseFloat(match2[1]); + var type = (match2[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n4 * y; + case "weeks": + case "week": + case "w": + return n4 * w; + case "days": + case "day": + case "d": + return n4 * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n4 * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n4 * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n4 * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n4; + default: + return; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; } - const pluckReturnValue = new RunnableCallable3({ - name: "pluckReturnValue", - func: (value) => { - return isEntrypointFinal(value) ? value.value : value; + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); } - }); - const pluckSaveValue = new RunnableCallable3({ - name: "pluckSaveValue", - func: (value) => { - return isEntrypointFinal(value) ? value.save : value; + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); } - }); - const entrypointNode = new PregelNode3({ - bound, - triggers: [START2], - channels: [START2], - writers: [new ChannelWrite3([{ - channel: END2, - value: PASSTHROUGH2, - mapper: pluckReturnValue - }, { - channel: PREVIOUS2, - value: PASSTHROUGH2, - mapper: pluckSaveValue - }], [TAG_HIDDEN2])] - }); - return new Pregel2({ - name, - checkpointer, - nodes: { [name]: entrypointNode }, - channels: { - [START2]: new EphemeralValue3, - [END2]: new LastValue3, - [PREVIOUS2]: new LastValue3 - }, - inputChannels: START2, - outputChannels: END2, - streamChannels: END2, - streamMode, - store, - cache: cache2 - }); -}; -var init_func2 = __esm(() => { - init_constants8(); - init_last_value2(); - init_utils17(); - init_write2(); - init_read2(); - init_call2(); - init_pregel2(); - init_ephemeral_value2(); - init_singletons(); - entrypoint3.final = function final2({ value, save }) { - return { - value, - save, - __lg_type: "__pregel_final" - }; - }; + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n4, name) { + var isPlural = msAbs >= n4 * 1.5; + return Math.round(ms / n4) + " " + name + (isPlural ? "s" : ""); + } }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js -var util3, objectUtil2, ZodParsedType2, getParsedType4 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType2.undefined; - case "string": - return ZodParsedType2.string; - case "number": - return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; - case "boolean": - return ZodParsedType2.boolean; - case "function": - return ZodParsedType2.function; - case "bigint": - return ZodParsedType2.bigint; - case "symbol": - return ZodParsedType2.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType2.array; - } - if (data === null) { - return ZodParsedType2.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType2.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType2.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType2.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType2.date; +// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js +var require_common3 = __commonJS((exports, module) => { + function setup(env2) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce3; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env2).forEach((key) => { + createDebug[key] = env2[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0;i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; } - return ZodParsedType2.object; - default: - return ZodParsedType2.unknown; - } -}; -var init_util4 = __esm(() => { - (function(util4) { - util4.assertEqual = (_) => {}; - function assertIs3(_arg) {} - util4.assertIs = assertIs3; - function assertNever3(_x) { - throw new Error; + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; } - util4.assertNever = assertNever3; - util4.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util4.getValidEnumValues = (obj) => { - const validKeys = util4.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util4.objectValues(filtered); - }; - util4.objectValues = (obj) => { - return util4.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { - const keys = []; - for (const key in object3) { - if (Object.prototype.hasOwnProperty.call(object3, key)) { - keys.push(key); + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(new Date); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); } + let index2 = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format3) => { + if (match2 === "%%") { + return "%"; + } + index2++; + const formatter = createDebug.formatters[format3]; + if (typeof formatter === "function") { + const val = args[index2]; + match2 = formatter.call(self2, val); + args.splice(index2, 1); + index2--; + } + return match2; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); } - return keys; - }; - util4.find = (arr3, checker) => { - for (const item of arr3) { - if (checker(item)) - return item; + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend3; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); } - return; - }; - util4.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues3(array3, separator = " | ") { - return array3.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + return debug; } - util4.joinValues = joinValues3; - util4.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; - })(util3 || (util3 = {})); - (function(objectUtil3) { - objectUtil3.mergeShapes = (first, second) => { - return { - ...first, - ...second - }; - }; - })(objectUtil2 || (objectUtil2 = {})); - ZodParsedType2 = util3.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" - ]); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js -var ZodIssueCode4, quotelessJson2 = (obj) => { - const json3 = JSON.stringify(obj, null, 2); - return json3.replace(/"([^"]+)":/g, "$1:"); -}, ZodError5; -var init_ZodError2 = __esm(() => { - init_util4(); - ZodIssueCode4 = util3.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" - ]); - ZodError5 = class ZodError5 extends Error { - get errors() { - return this.issues; + function extend3(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns3 of split) { + if (ns3[0] === "-") { + createDebug.skips.push(ns3.slice(1)); + } else { + createDebug.names.push(ns3); + } } - this.name = "ZodError"; - this.issues = issues; } - format(_mapper) { - const mapper = _mapper || function(issue3) { - return issue3.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error91) => { - for (const issue3 of error91.issues) { - if (issue3.code === "invalid_union") { - issue3.unionErrors.map(processError); - } else if (issue3.code === "invalid_return_type") { - processError(issue3.returnTypeError); - } else if (issue3.code === "invalid_arguments") { - processError(issue3.argumentsError); - } else if (issue3.path.length === 0) { - fieldErrors._errors.push(mapper(issue3)); + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; } else { - let curr = fieldErrors; - let i = 0; - while (i < issue3.path.length) { - const el = issue3.path[i]; - const terminal = i === issue3.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue3)); - } - curr = curr[el]; - i++; - } + searchIndex++; + templateIndex++; } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError5)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util3.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue3) => issue3.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - formErrors.push(mapper(sub)); + return false; } } - return { formErrors, fieldErrors }; + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; } - get formErrors() { - return this.flatten(); + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; } - }; - ZodError5.create = (issues) => { - const error91 = new ZodError5(issues); - return error91; - }; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js -var errorMap2 = (issue3, _ctx) => { - let message; - switch (issue3.code) { - case ZodIssueCode4.invalid_type: - if (issue3.received === ZodParsedType2.undefined) { - message = "Required"; - } else { - message = `Expected ${issue3.expected}, received ${issue3.received}`; + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } } - break; - case ZodIssueCode4.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue3.expected, util3.jsonStringifyReplacer)}`; - break; - case ZodIssueCode4.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util3.joinValues(issue3.keys, ", ")}`; - break; - case ZodIssueCode4.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode4.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util3.joinValues(issue3.options)}`; - break; - case ZodIssueCode4.invalid_enum_value: - message = `Invalid enum value. Expected ${util3.joinValues(issue3.options)}, received '${issue3.received}'`; - break; - case ZodIssueCode4.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode4.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode4.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode4.invalid_string: - if (typeof issue3.validation === "object") { - if ("includes" in issue3.validation) { - message = `Invalid input: must include "${issue3.validation.includes}"`; - if (typeof issue3.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue3.validation.position}`; - } - } else if ("startsWith" in issue3.validation) { - message = `Invalid input: must start with "${issue3.validation.startsWith}"`; - } else if ("endsWith" in issue3.validation) { - message = `Invalid input: must end with "${issue3.validation.endsWith}"`; - } else { - util3.assertNever(issue3.validation); + for (const ns3 of createDebug.names) { + if (matchesTemplate(name, ns3)) { + return true; } - } else if (issue3.validation !== "regex") { - message = `Invalid ${issue3.validation}`; - } else { - message = "Invalid"; } - break; - case ZodIssueCode4.too_small: - if (issue3.type === "array") - message = `Array must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `more than`} ${issue3.minimum} element(s)`; - else if (issue3.type === "string") - message = `String must contain ${issue3.exact ? "exactly" : issue3.inclusive ? `at least` : `over`} ${issue3.minimum} character(s)`; - else if (issue3.type === "number") - message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; - else if (issue3.type === "bigint") - message = `Number must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${issue3.minimum}`; - else if (issue3.type === "date") - message = `Date must be ${issue3.exact ? `exactly equal to ` : issue3.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue3.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode4.too_big: - if (issue3.type === "array") - message = `Array must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `less than`} ${issue3.maximum} element(s)`; - else if (issue3.type === "string") - message = `String must contain ${issue3.exact ? `exactly` : issue3.inclusive ? `at most` : `under`} ${issue3.maximum} character(s)`; - else if (issue3.type === "number") - message = `Number must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; - else if (issue3.type === "bigint") - message = `BigInt must be ${issue3.exact ? `exactly` : issue3.inclusive ? `less than or equal to` : `less than`} ${issue3.maximum}`; - else if (issue3.type === "date") - message = `Date must be ${issue3.exact ? `exactly` : issue3.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue3.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode4.custom: - message = `Invalid input`; - break; - case ZodIssueCode4.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode4.not_multiple_of: - message = `Number must be a multiple of ${issue3.multipleOf}`; - break; - case ZodIssueCode4.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util3.assertNever(issue3); + return false; + } + function coerce3(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; } - return { message }; -}, en_default4; -var init_en4 = __esm(() => { - init_ZodError2(); - init_util4(); - en_default4 = errorMap2; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js -function setErrorMap4(map3) { - overrideErrorMap2 = map3; -} -function getErrorMap4() { - return overrideErrorMap2; -} -var overrideErrorMap2; -var init_errors13 = __esm(() => { - init_en4(); - overrideErrorMap2 = en_default4; + module.exports = setup; }); -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js -function addIssueToContext2(ctx, issueData) { - const overrideMap = getErrorMap4(); - const issue3 = makeIssue2({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_default4 ? undefined : en_default4 - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue3); -} - -class ParseStatus2 { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID2; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); +// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js +var require_browser = __commonJS((exports, module) => { + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load2; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; } - return ParseStatus2.mergeObjectSync(status, syncPairs); + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID2; - if (value.status === "aborted") - return INVALID2; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; } - return { status: status.value, value: finalObject }; - } -} -var makeIssue2 = (params) => { - const { data, path: path4, errorMaps, issueData } = params; - const fullPath = [...path4, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map3 of maps) { - errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}, EMPTY_PATH2, INVALID2, DIRTY2 = (value) => ({ status: "dirty", value }), OK2 = (value) => ({ status: "valid", value }), isAborted2 = (x) => x.status === "aborted", isDirty2 = (x) => x.status === "dirty", isValid2 = (x) => x.status === "valid", isAsync2 = (x) => typeof Promise !== "undefined" && x instanceof Promise; -var init_parseUtil2 = __esm(() => { - init_errors13(); - init_en4(); - EMPTY_PATH2 = []; - INVALID2 = Object.freeze({ - status: "aborted" - }); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js -var init_typeAliases2 = () => {}; - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js -var errorUtil2; -var init_errorUtil2 = __esm(() => { - (function(errorUtil3) { - errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; - })(errorUtil2 || (errorUtil2 = {})); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js -class ParseInputLazyPath2 { - constructor(parent, value, path4, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path4; - this._key = key; + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index2 = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match2) => { + if (match2 === "%%") { + return; + } + index2++; + if (match2 === "%c") { + lastC = index2; + } + }); + args.splice(lastC, 0, c); } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); + exports.log = console.debug || console.log || (() => {}); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); } else { - this._cachedPath.push(...this._path, this._key); + exports.storage.removeItem("debug"); } + } catch (error91) {} + } + function load2() { + let r; + try { + r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error91) {} + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; } - return this._cachedPath; + return r; } -} -function processCreateParams2(params) { - if (!params) - return {}; - const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; - if (errorMap3 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + function localstorage() { + try { + return localStorage; + } catch (error91) {} } - if (errorMap3) - return { errorMap: errorMap3, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; + module.exports = require_common3()(exports); + var { formatters: formatters2 } = module.exports; + formatters2.j = function(v) { + try { + return JSON.stringify(v); + } catch (error91) { + return "[UnexpectedJSONParseError]: " + error91.message; } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; - return { errorMap: customMap, description }; -} +}); -class ZodType4 { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType4(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType4(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; +// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js +var require_node = __commonJS((exports, module) => { + var tty = __require("tty"); + var util5 = __require("util"); + exports.init = init; + exports.log = log2; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load2; + exports.useColors = useColors; + exports.destroy = util5.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + exports.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = (()=>{throw new Error("Cannot require module "+"supports-color");})(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error91) {} + exports.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); } - _processInputParams(input) { - return { - status: new ParseStatus2, - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType4(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split(` +`).join(` +` + prefix); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } } - _parseSync(input) { - const result = this._parse(input); - if (isAsync2(result)) { - throw new Error("Synchronous parse encountered promise."); + function getDate() { + if (exports.inspectOpts.hideDate) { + return ""; } - return result; + return new Date().toISOString() + " "; } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + function log2(...args) { + return process.stderr.write(util5.formatWithOptions(exports.inspectOpts, ...args) + ` +`); } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult2(ctx, result); + function load2() { + return process.env.DEBUG; } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0;i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType4(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult2(ctx, result); + module.exports = require_common3()(exports); + var { formatters: formatters2 } = module.exports; + formatters2.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util5.inspect(v, this.inspectOpts).split(` +`).map((str) => str.trim()).join(" "); + }; + formatters2.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util5.inspect(v, this.inspectOpts); + }; +}); + +// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js +var require_src = __commonJS((exports, module) => { + if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) { + module.exports = require_browser(); + } else { + module.exports = require_node(); } - refine(check3, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check3(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode4.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); +}); + +// ../../node_modules/.pnpm/@kwsites+file-exists@1.1.1/node_modules/@kwsites/file-exists/dist/src/index.js +var require_src2 = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + var fs_1 = __require("fs"); + var debug_1 = __importDefault(require_src()); + var log2 = debug_1.default("@kwsites/file-exists"); + function check3(path4, isFile, isDirectory) { + log2(`checking %s`, path4); + try { + const stat4 = fs_1.statSync(path4); + if (stat4.isFile() && isFile) { + log2(`[OK] path represents a file`); + return true; } - if (!result) { - setError(); - return false; - } else { + if (stat4.isDirectory() && isDirectory) { + log2(`[OK] path represents a directory`); return true; } - }); - } - refinement(check3, refinementData) { - return this._refinement((val, ctx) => { - if (!check3(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + log2(`[FAIL] path represents something other than a file or directory`); + return false; + } catch (e) { + if (e.code === "ENOENT") { + log2(`[FAIL] path is not accessible: %o`, e); return false; - } else { - return true; } - }); + log2(`[FATAL] %o`, e); + throw e; + } } - _refinement(refinement) { - return new ZodEffects2({ - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "refinement", refinement } - }); + function exists(path4, type = exports.READABLE) { + return check3(path4, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0); } - superRefine(refinement) { - return this._refinement(refinement); + exports.exists = exists; + exports.FILE = 1; + exports.FOLDER = 2; + exports.READABLE = exports.FILE + exports.FOLDER; +}); + +// ../../node_modules/.pnpm/@kwsites+file-exists@1.1.1/node_modules/@kwsites/file-exists/dist/index.js +var require_dist5 = __commonJS((exports) => { + function __export2(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) + Object.defineProperty(exports, "__esModule", { value: true }); + __export2(require_src2()); +}); + +// ../../node_modules/.pnpm/@kwsites+promise-deferred@1.1.1/node_modules/@kwsites/promise-deferred/dist/index.js +var require_dist6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDeferred = exports.deferred = undefined; + function deferred() { + let done; + let fail; + let status = "pending"; + const promise3 = new Promise((_done, _fail) => { + done = _done; + fail = _fail; + }); + return { + promise: promise3, + done(result) { + if (status === "pending") { + status = "resolved"; + done(result); + } + }, + fail(error91) { + if (status === "pending") { + status = "rejected"; + fail(error91); + } + }, + get fulfilled() { + return status !== "pending"; + }, + get status() { + return status; + } }; } - optional() { - return ZodOptional4.create(this, this._def); - } - nullable() { - return ZodNullable4.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray4.create(this); - } - promise() { - return ZodPromise4.create(this, this._def); + exports.deferred = deferred; + exports.createDeferred = deferred; + exports.default = deferred; +}); + +// ../../node_modules/.pnpm/bson@6.10.4/node_modules/bson/lib/bson.cjs +var require_bson = __commonJS((exports) => { + var TypedArrayPrototypeGetSymbolToStringTag = (() => { + const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get; + return (value) => g.call(value); + })(); + function isUint8Array(value) { + return TypedArrayPrototypeGetSymbolToStringTag(value) === "Uint8Array"; } - or(option) { - return ZodUnion4.create([this, option], this._def); + function isAnyArrayBuffer(value) { + return typeof value === "object" && value != null && Symbol.toStringTag in value && (value[Symbol.toStringTag] === "ArrayBuffer" || value[Symbol.toStringTag] === "SharedArrayBuffer"); } - and(incoming) { - return ZodIntersection4.create(this, incoming, this._def); + function isRegExp(regexp2) { + return regexp2 instanceof RegExp || Object.prototype.toString.call(regexp2) === "[object RegExp]"; } - transform(transform3) { - return new ZodEffects2({ - ...processCreateParams2(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect: { type: "transform", transform: transform3 } - }); + function isMap(value) { + return typeof value === "object" && value != null && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Map"; } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault4({ - ...processCreateParams2(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodDefault - }); + function isDate(date10) { + return date10 instanceof Date || Object.prototype.toString.call(date10) === "[object Date]"; } - brand() { - return new ZodBranded2({ - typeName: ZodFirstPartyTypeKind3.ZodBranded, - type: this, - ...processCreateParams2(this._def) + function defaultInspect(x2, _options) { + return JSON.stringify(x2, (k2, v) => { + if (typeof v === "bigint") { + return { $numberLong: `${v}` }; + } else if (isMap(v)) { + return Object.fromEntries(v); + } + return v; }); } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch4({ - ...processCreateParams2(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind3.ZodCatch - }); + function getStylizeFunction(options) { + const stylizeExists = options != null && typeof options === "object" && "stylize" in options && typeof options.stylize === "function"; + if (stylizeExists) { + return options.stylize; + } } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); + var BSON_MAJOR_VERSION = 6; + var BSON_VERSION_SYMBOL = Symbol.for("@@mdb.bson.version"); + var BSON_INT32_MAX = 2147483647; + var BSON_INT32_MIN = -2147483648; + var BSON_INT64_MAX = Math.pow(2, 63) - 1; + var BSON_INT64_MIN = -Math.pow(2, 63); + var JS_INT_MAX = Math.pow(2, 53); + var JS_INT_MIN = -Math.pow(2, 53); + var BSON_DATA_NUMBER = 1; + var BSON_DATA_STRING = 2; + var BSON_DATA_OBJECT = 3; + var BSON_DATA_ARRAY = 4; + var BSON_DATA_BINARY = 5; + var BSON_DATA_UNDEFINED = 6; + var BSON_DATA_OID = 7; + var BSON_DATA_BOOLEAN = 8; + var BSON_DATA_DATE = 9; + var BSON_DATA_NULL = 10; + var BSON_DATA_REGEXP = 11; + var BSON_DATA_DBPOINTER = 12; + var BSON_DATA_CODE = 13; + var BSON_DATA_SYMBOL = 14; + var BSON_DATA_CODE_W_SCOPE = 15; + var BSON_DATA_INT = 16; + var BSON_DATA_TIMESTAMP = 17; + var BSON_DATA_LONG = 18; + var BSON_DATA_DECIMAL128 = 19; + var BSON_DATA_MIN_KEY = 255; + var BSON_DATA_MAX_KEY = 127; + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + var BSON_BINARY_SUBTYPE_UUID_NEW = 4; + var BSONType = Object.freeze({ + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: -1, + maxKey: 127 + }); + + class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return "BSONError"; + } + constructor(message, options) { + super(message, options); + } + static isBSONError(value) { + return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value; + } } - pipe(target) { - return ZodPipeline2.create(this, target); + + class BSONVersionError extends BSONError { + get name() { + return "BSONVersionError"; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } } - readonly() { - return ZodReadonly4.create(this); + + class BSONRuntimeError extends BSONError { + get name() { + return "BSONRuntimeError"; + } + constructor(message) { + super(message); + } } - isOptional() { - return this.safeParse(undefined).success; + + class BSONOffsetError extends BSONError { + get name() { + return "BSONOffsetError"; + } + constructor(message, offset, options) { + super(`${message}. offset: ${offset}`, options); + this.offset = offset; + } } - isNullable() { - return this.safeParse(null).success; + var TextDecoderFatal; + var TextDecoderNonFatal; + function parseUtf8(buffer2, start, end, fatal) { + if (fatal) { + TextDecoderFatal ??= new TextDecoder("utf8", { fatal: true }); + try { + return TextDecoderFatal.decode(buffer2.subarray(start, end)); + } catch (cause) { + throw new BSONError("Invalid UTF-8 string in BSON document", { cause }); + } + } + TextDecoderNonFatal ??= new TextDecoder("utf8", { fatal: false }); + return TextDecoderNonFatal.decode(buffer2.subarray(start, end)); } -} -function timeRegexSource2(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + function tryReadBasicLatin(uint8array, start, end) { + if (uint8array.length === 0) { + return ""; + } + const stringByteLength = end - start; + if (stringByteLength === 0) { + return ""; + } + if (stringByteLength > 20) { + return null; + } + if (stringByteLength === 1 && uint8array[start] < 128) { + return String.fromCharCode(uint8array[start]); + } + if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + if (stringByteLength === 3 && uint8array[start] < 128 && uint8array[start + 1] < 128 && uint8array[start + 2] < 128) { + return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]) + String.fromCharCode(uint8array[start + 2]); + } + const latinBytes = []; + for (let i2 = start;i2 < end; i2++) { + const byte = uint8array[i2]; + if (byte > 127) { + return null; + } + latinBytes.push(byte); + } + return String.fromCharCode(...latinBytes); } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex2(args) { - return new RegExp(`^${timeRegexSource2(args)}$`); -} -function datetimeRegex2(args) { - let regex2 = `${dateRegexSource2}T${timeRegexSource2(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex2 = `${regex2}(${opts.join("|")})`; - return new RegExp(`^${regex2}$`); -} -function isValidIP2(ip, version5) { - if ((version5 === "v4" || !version5) && ipv4Regex2.test(ip)) { - return true; + function tryWriteBasicLatin(destination, source, offset) { + if (source.length === 0) + return 0; + if (source.length > 25) + return null; + if (destination.length - offset < source.length) + return null; + for (let charOffset = 0, destinationOffset = offset;charOffset < source.length; charOffset++, destinationOffset++) { + const char = source.charCodeAt(charOffset); + if (char > 127) + return null; + destination[destinationOffset] = char; + } + return source.length; } - if ((version5 === "v6" || !version5) && ipv6Regex2.test(ip)) { - return true; + function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); } - return false; -} -function isValidJWT4(jwt3, alg) { - if (!jwtRegex2.test(jwt3)) - return false; - try { - const [header] = jwt3.split("."); - if (!header) - return false; - const base647 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base647)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; + var nodejsRandomBytes = (() => { + try { + return __require("crypto").randomBytes; + } catch { + return nodejsMathRandomBytes; + } + })(); + var nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + allocateUnsafe(size) { + return Buffer.allocUnsafe(size); + }, + equals(a, b2) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b2); + }, + fromNumberArray(array3) { + return Buffer.from(array3); + }, + fromBase64(base647) { + return Buffer.from(base647, "base64"); + }, + toBase64(buffer2) { + return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64"); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, "binary"); + }, + toISO88591(buffer2) { + return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary"); + }, + fromHex(hex3) { + return Buffer.from(hex3, "hex"); + }, + toHex(buffer2) { + return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex"); + }, + toUTF8(buffer2, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + const string7 = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end); + if (fatal) { + for (let i2 = 0;i2 < string7.length; i2++) { + if (string7.charCodeAt(i2) === 65533) { + parseUtf8(buffer2, start, end, true); + break; + } + } + } + return string7; + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, "utf8"); + }, + encodeUTF8Into(buffer2, source, byteOffset) { + const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset); + if (latinBytesWritten != null) { + return latinBytesWritten; + } + return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, undefined, "utf8"); + }, + randomBytes: nodejsRandomBytes, + swap32(buffer2) { + return nodeJsByteUtils.toLocalBufferType(buffer2).swap32(); + } + }; + function isReactNative() { + const { navigator: navigator2 } = globalThis; + return typeof navigator2 === "object" && navigator2.product === "ReactNative"; } -} -function isValidCidr2(ip, version5) { - if ((version5 === "v4" || !version5) && ipv4CidrRegex2.test(ip)) { - return true; + function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); } - if ((version5 === "v6" || !version5) && ipv6CidrRegex2.test(ip)) { - return true; + var webRandomBytes = (() => { + const { crypto: crypto3 } = globalThis; + if (crypto3 != null && typeof crypto3.getRandomValues === "function") { + return (byteLength) => { + return crypto3.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } else { + if (isReactNative()) { + const { console: console2 } = globalThis; + console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values."); + } + return webMathRandomBytes; + } + })(); + var HEX_DIGIT = /(\d|[a-f])/i; + var webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array); + if (stringTag === "Uint8Array") { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`); + }, + allocate(size) { + if (typeof size !== "number") { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + allocateUnsafe(size) { + return webByteUtils.allocate(size); + }, + equals(a, b2) { + if (a.byteLength !== b2.byteLength) { + return false; + } + for (let i2 = 0;i2 < a.byteLength; i2++) { + if (a[i2] !== b2[i2]) { + return false; + } + } + return true; + }, + fromNumberArray(array3) { + return Uint8Array.from(array3); + }, + fromBase64(base647) { + return Uint8Array.from(atob(base647), (c3) => c3.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, (c3) => c3.charCodeAt(0) & 255); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), (b2) => String.fromCharCode(b2)).join(""); + }, + fromHex(hex3) { + const evenLengthHex = hex3.length % 2 === 0 ? hex3 : hex3.slice(0, hex3.length - 1); + const buffer2 = []; + for (let i2 = 0;i2 < evenLengthHex.length; i2 += 2) { + const firstDigit = evenLengthHex[i2]; + const secondDigit = evenLengthHex[i2 + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer2.push(hexDigit); + } + return Uint8Array.from(buffer2); + }, + toHex(uint8array) { + return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join(""); + }, + toUTF8(uint8array, start, end, fatal) { + const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; + if (basicLatin != null) { + return basicLatin; + } + return parseUtf8(uint8array, start, end, fatal); + }, + utf8ByteLength(input) { + return new TextEncoder().encode(input).byteLength; + }, + encodeUTF8Into(uint8array, source, byteOffset) { + const bytes = new TextEncoder().encode(source); + uint8array.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes, + swap32(buffer2) { + if (buffer2.length % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i2 = 0;i2 < buffer2.length; i2 += 4) { + const byte0 = buffer2[i2]; + const byte1 = buffer2[i2 + 1]; + const byte2 = buffer2[i2 + 2]; + const byte3 = buffer2[i2 + 3]; + buffer2[i2] = byte3; + buffer2[i2 + 1] = byte2; + buffer2[i2 + 2] = byte1; + buffer2[i2 + 3] = byte0; + } + return buffer2; + } + }; + var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true; + var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + + class BSONValue { + get [BSON_VERSION_SYMBOL]() { + return BSON_MAJOR_VERSION; + } + [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) { + return this.inspect(depth, options, inspect); + } } - return false; -} -function floatSafeRemainder4(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function deepPartialify2(schema) { - if (schema instanceof ZodObject4) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional4.create(deepPartialify2(fieldSchema)); + var FLOAT = new Float64Array(1); + var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); + FLOAT[0] = -1; + var isBigEndian = FLOAT_BYTES[7] === 0; + var NumberUtils = { + isBigEndian, + getNonnegativeInt32LE(source, offset) { + if (source[offset + 3] > 127) { + throw new RangeError(`Size cannot be negative at offset: ${offset}`); + } + return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24; + }, + getInt32LE(source, offset) { + return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24; + }, + getUint32LE(source, offset) { + return source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216; + }, + getUint32BE(source, offset) { + return source[offset + 3] + source[offset + 2] * 256 + source[offset + 1] * 65536 + source[offset] * 16777216; + }, + getBigInt64LE(source, offset) { + const hi = BigInt(source[offset + 4] + source[offset + 5] * 256 + source[offset + 6] * 65536 + (source[offset + 7] << 24)); + const lo = BigInt(source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216); + return (hi << BigInt(32)) + lo; + }, + getFloat64LE: isBigEndian ? (source, offset) => { + FLOAT_BYTES[7] = source[offset]; + FLOAT_BYTES[6] = source[offset + 1]; + FLOAT_BYTES[5] = source[offset + 2]; + FLOAT_BYTES[4] = source[offset + 3]; + FLOAT_BYTES[3] = source[offset + 4]; + FLOAT_BYTES[2] = source[offset + 5]; + FLOAT_BYTES[1] = source[offset + 6]; + FLOAT_BYTES[0] = source[offset + 7]; + return FLOAT[0]; + } : (source, offset) => { + FLOAT_BYTES[0] = source[offset]; + FLOAT_BYTES[1] = source[offset + 1]; + FLOAT_BYTES[2] = source[offset + 2]; + FLOAT_BYTES[3] = source[offset + 3]; + FLOAT_BYTES[4] = source[offset + 4]; + FLOAT_BYTES[5] = source[offset + 5]; + FLOAT_BYTES[6] = source[offset + 6]; + FLOAT_BYTES[7] = source[offset + 7]; + return FLOAT[0]; + }, + setInt32BE(destination, offset, value) { + destination[offset + 3] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset] = value; + return 4; + }, + setInt32LE(destination, offset, value) { + destination[offset] = value; + value >>>= 8; + destination[offset + 1] = value; + value >>>= 8; + destination[offset + 2] = value; + value >>>= 8; + destination[offset + 3] = value; + return 4; + }, + setBigInt64LE(destination, offset, value) { + const mask32bits = BigInt(4294967295); + let lo = Number(value & mask32bits); + destination[offset] = lo; + lo >>= 8; + destination[offset + 1] = lo; + lo >>= 8; + destination[offset + 2] = lo; + lo >>= 8; + destination[offset + 3] = lo; + let hi = Number(value >> BigInt(32) & mask32bits); + destination[offset + 4] = hi; + hi >>= 8; + destination[offset + 5] = hi; + hi >>= 8; + destination[offset + 6] = hi; + hi >>= 8; + destination[offset + 7] = hi; + return 8; + }, + setFloat64LE: isBigEndian ? (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[7]; + destination[offset + 1] = FLOAT_BYTES[6]; + destination[offset + 2] = FLOAT_BYTES[5]; + destination[offset + 3] = FLOAT_BYTES[4]; + destination[offset + 4] = FLOAT_BYTES[3]; + destination[offset + 5] = FLOAT_BYTES[2]; + destination[offset + 6] = FLOAT_BYTES[1]; + destination[offset + 7] = FLOAT_BYTES[0]; + return 8; + } : (destination, offset, value) => { + FLOAT[0] = value; + destination[offset] = FLOAT_BYTES[0]; + destination[offset + 1] = FLOAT_BYTES[1]; + destination[offset + 2] = FLOAT_BYTES[2]; + destination[offset + 3] = FLOAT_BYTES[3]; + destination[offset + 4] = FLOAT_BYTES[4]; + destination[offset + 5] = FLOAT_BYTES[5]; + destination[offset + 6] = FLOAT_BYTES[6]; + destination[offset + 7] = FLOAT_BYTES[7]; + return 8; + } + }; + + class Binary extends BSONValue { + get _bsontype() { + return "Binary"; + } + constructor(buffer2, subType) { + super(); + if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) { + throw new BSONError("Binary can only be constructed from Uint8Array or number[]"); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer2 == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } else { + this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2); + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === "string" && byteValue.length !== 1) { + throw new BSONError("only accepts single character String"); + } else if (typeof byteValue !== "number" && byteValue.length !== 1) + throw new BSONError("only accepts single character Uint8Array or Array"); + let decodedByte; + if (typeof byteValue === "string") { + decodedByte = byteValue.charCodeAt(0); + } else if (typeof byteValue === "number") { + decodedByte = byteValue; + } else { + decodedByte = byteValue[0]; + } + if (decodedByte < 0 || decodedByte > 255) { + throw new BSONError("only accepts number in a valid unsigned byte range 0-255"); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === "number" ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === "string") { + throw new BSONError("input cannot be string"); + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + const end = position + length; + return this.buffer.subarray(position, end > this.position ? this.position : end); + } + value() { + return this.buffer.length === this.position ? this.buffer : this.buffer.subarray(0, this.position); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + } + toString(encoding) { + if (encoding === "hex") + return ByteUtils.toHex(this.buffer.subarray(0, this.position)); + if (encoding === "base64") + return ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + if (encoding === "utf8" || encoding === "utf-8") + return ByteUtils.toUTF8(this.buffer, 0, this.position, false); + return ByteUtils.toUTF8(this.buffer, 0, this.position, false); + } + toExtendedJSON(options) { + options = options || {}; + if (this.sub_type === Binary.SUBTYPE_VECTOR) { + validateBinaryVector(this); + } + const base64String = ByteUtils.toBase64(this.buffer); + const subType = Number(this.sub_type).toString(16); + if (options.legacy) { + return { + $binary: base64String, + $type: subType.length === 1 ? "0" + subType : subType + }; + } + return { + $binary: { + base64: base64String, + subType: subType.length === 1 ? "0" + subType : subType + } + }; + } + toUUID() { + if (this.sub_type === Binary.SUBTYPE_UUID) { + return new UUID2(this.buffer.subarray(0, this.position)); + } + throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); } - return new ZodObject4({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray4) { - return new ZodArray4({ - ...schema._def, - type: deepPartialify2(schema.element) - }); - } else if (schema instanceof ZodOptional4) { - return ZodOptional4.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodNullable4) { - return ZodNullable4.create(deepPartialify2(schema.unwrap())); - } else if (schema instanceof ZodTuple4) { - return ZodTuple4.create(schema.items.map((item) => deepPartialify2(item))); - } else { - return schema; - } -} -function mergeValues4(a, b) { - const aType = getParsedType4(a); - const bType = getParsedType4(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { - const bKeys = util3.objectKeys(b); - const sharedKeys = util3.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues4(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; + static createFromHexString(hex3, subType) { + return new Binary(ByteUtils.fromHex(hex3), subType); + } + static createFromBase64(base647, subType) { + return new Binary(ByteUtils.fromBase64(base647), subType); + } + static fromExtendedJSON(doc3, options) { + options = options || {}; + let data; + let type; + if ("$binary" in doc3) { + if (options.legacy && typeof doc3.$binary === "string" && "$type" in doc3) { + type = doc3.$type ? parseInt(doc3.$type, 16) : 0; + data = ByteUtils.fromBase64(doc3.$binary); + } else { + if (typeof doc3.$binary !== "string") { + type = doc3.$binary.subType ? parseInt(doc3.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc3.$binary.base64); + } + } + } else if ("$uuid" in doc3) { + type = 4; + data = UUID2.bytesFromString(doc3.$uuid); } - newObj[key] = sharedValue.data; + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc3)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID2(data) : new Binary(data, type); } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { - if (a.length !== b.length) { - return { valid: false }; + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const base647 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + const base64Arg = inspect(base647, options); + const subTypeArg = inspect(this.sub_type, options); + return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; } - const newArray = []; - for (let index2 = 0;index2 < a.length; index2++) { - const itemA = a[index2]; - const itemB = b[index2]; - const sharedValue = mergeValues4(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; + toInt8Array() { + if (this.sub_type !== Binary.SUBTYPE_VECTOR) { + throw new BSONError("Binary sub_type is not Vector"); } - newArray.push(sharedValue.data); + if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) { + throw new BSONError("Binary datatype field is not Int8"); + } + validateBinaryVector(this); + return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -function createZodEnum2(values2, params) { - return new ZodEnum4({ - values: values2, - typeName: ZodFirstPartyTypeKind3.ZodEnum, - ...processCreateParams2(params) - }); -} -function cleanParams2(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom4(check3, _params = {}, fatal) { - if (check3) - return ZodAny4.create().superRefine((data, ctx) => { - const r = check3(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); + toFloat32Array() { + if (this.sub_type !== Binary.SUBTYPE_VECTOR) { + throw new BSONError("Binary sub_type is not Vector"); } - if (!r) { - const params = cleanParams2(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) { + throw new BSONError("Binary datatype field is not Float32"); } - return; - }); - return ZodAny4.create(); -} -var handleResult2 = (ctx, result) => { - if (isValid2(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); + validateBinaryVector(this); + const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); + if (NumberUtils.isBigEndian) + ByteUtils.swap32(floatBytes); + return new Float32Array(floatBytes.buffer); } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error91 = new ZodError5(ctx.common.issues); - this._error = error91; - return this._error; + toPackedBits() { + if (this.sub_type !== Binary.SUBTYPE_VECTOR) { + throw new BSONError("Binary sub_type is not Vector"); } - }; - } -}, cuidRegex2, cuid2Regex2, ulidRegex2, uuidRegex2, nanoidRegex2, jwtRegex2, durationRegex2, emailRegex2, _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`, emojiRegex3, ipv4Regex2, ipv4CidrRegex2, ipv6Regex2, ipv6CidrRegex2, base64Regex2, base64urlRegex2, dateRegexSource2 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`, dateRegex2, ZodString4, ZodNumber4, ZodBigInt4, ZodBoolean4, ZodDate4, ZodSymbol4, ZodUndefined4, ZodNull4, ZodAny4, ZodUnknown4, ZodNever4, ZodVoid4, ZodArray4, ZodObject4, ZodUnion4, getDiscriminator2 = (type) => { - if (type instanceof ZodLazy4) { - return getDiscriminator2(type.schema); - } else if (type instanceof ZodEffects2) { - return getDiscriminator2(type.innerType()); - } else if (type instanceof ZodLiteral4) { - return [type.value]; - } else if (type instanceof ZodEnum4) { - return type.options; - } else if (type instanceof ZodNativeEnum2) { - return util3.objectValues(type.enum); - } else if (type instanceof ZodDefault4) { - return getDiscriminator2(type._def.innerType); - } else if (type instanceof ZodUndefined4) { - return [undefined]; - } else if (type instanceof ZodNull4) { - return [null]; - } else if (type instanceof ZodOptional4) { - return [undefined, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodNullable4) { - return [null, ...getDiscriminator2(type.unwrap())]; - } else if (type instanceof ZodBranded2) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodReadonly4) { - return getDiscriminator2(type.unwrap()); - } else if (type instanceof ZodCatch4) { - return getDiscriminator2(type._def.innerType); - } else { - return []; - } -}, ZodDiscriminatedUnion4, ZodIntersection4, ZodTuple4, ZodRecord4, ZodMap4, ZodSet4, ZodFunction3, ZodLazy4, ZodLiteral4, ZodEnum4, ZodNativeEnum2, ZodPromise4, ZodEffects2, ZodOptional4, ZodNullable4, ZodDefault4, ZodCatch4, ZodNaN4, BRAND2, ZodBranded2, ZodPipeline2, ZodReadonly4, late2, ZodFirstPartyTypeKind3, instanceOfType2 = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom4((data) => data instanceof cls, params), stringType2, numberType2, nanType2, bigIntType2, booleanType2, dateType2, symbolType2, undefinedType2, nullType2, anyType2, unknownType2, neverType2, voidType2, arrayType2, objectType2, strictObjectType2, unionType2, discriminatedUnionType2, intersectionType2, tupleType2, recordType2, mapType2, setType2, functionType2, lazyType2, literalType2, enumType2, nativeEnumType2, promiseType2, effectsType2, optionalType2, nullableType2, preprocessType2, pipelineType2, ostring2 = () => stringType2().optional(), onumber2 = () => numberType2().optional(), oboolean2 = () => booleanType2().optional(), coerce2, NEVER4; -var init_types16 = __esm(() => { - init_ZodError2(); - init_errors13(); - init_errorUtil2(); - init_parseUtil2(); - init_util4(); - cuidRegex2 = /^c[^\s-]{8,}$/i; - cuid2Regex2 = /^[0-9a-z]+$/; - ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; - uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; - nanoidRegex2 = /^[a-z0-9_-]{21}$/i; - jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; - durationRegex2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; - ipv4Regex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv4CidrRegex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; - ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; - ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; - dateRegex2 = new RegExp(`^${dateRegexSource2}$`); - ZodString4 = class ZodString4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); + if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) { + throw new BSONError("Binary datatype field is not packed bit"); } - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.string, - received: ctx2.parsedType - }); - return INVALID2; + validateBinaryVector(this); + return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); + } + toBits() { + if (this.sub_type !== Binary.SUBTYPE_VECTOR) { + throw new BSONError("Binary sub_type is not Vector"); } - const status = new ParseStatus2; - let ctx = undefined; - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - if (input.data.length < check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: check3.value, - type: "string", - inclusive: true, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - if (input.data.length > check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: check3.value, - type: "string", - inclusive: true, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "length") { - const tooBig = input.data.length > check3.value; - const tooSmall = input.data.length < check3.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: check3.value, - type: "string", - inclusive: true, - exact: true, - message: check3.message - }); - } else if (tooSmall) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: check3.value, - type: "string", - inclusive: true, - exact: true, - message: check3.message - }); - } - status.dirty(); - } - } else if (check3.kind === "email") { - if (!emailRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "email", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "emoji") { - if (!emojiRegex3) { - emojiRegex3 = new RegExp(_emojiRegex2, "u"); - } - if (!emojiRegex3.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "emoji", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "uuid") { - if (!uuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "uuid", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "nanoid") { - if (!nanoidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "nanoid", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cuid") { - if (!cuidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cuid2") { - if (!cuid2Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cuid2", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "ulid") { - if (!ulidRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ulid", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "url", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "regex") { - check3.regex.lastIndex = 0; - const testResult = check3.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "regex", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "trim") { - input.data = input.data.trim(); - } else if (check3.kind === "includes") { - if (!input.data.includes(check3.value, check3.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { includes: check3.value, position: check3.position }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check3.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check3.kind === "startsWith") { - if (!input.data.startsWith(check3.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { startsWith: check3.value }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "endsWith") { - if (!input.data.endsWith(check3.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: { endsWith: check3.value }, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "datetime") { - const regex2 = datetimeRegex2(check3); - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "datetime", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "date") { - const regex2 = dateRegex2; - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "date", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "time") { - const regex2 = timeRegex2(check3); - if (!regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_string, - validation: "time", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "duration") { - if (!durationRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "duration", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "ip") { - if (!isValidIP2(input.data, check3.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "ip", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "jwt") { - if (!isValidJWT4(input.data, check3.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "jwt", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "cidr") { - if (!isValidCidr2(input.data, check3.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "cidr", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "base64") { - if (!base64Regex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "base64url") { - if (!base64urlRegex2.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - validation: "base64url", - code: ZodIssueCode4.invalid_string, - message: check3.message - }); - status.dirty(); - } - } else { - util3.assertNever(check3); + if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) { + throw new BSONError("Binary datatype field is not packed bit"); + } + validateBinaryVector(this); + const byteCount = this.length() - 2; + const bitCount = byteCount * 8 - this.buffer[1]; + const bits = new Int8Array(bitCount); + for (let bitOffset = 0;bitOffset < bits.length; bitOffset++) { + const byteOffset = bitOffset / 8 | 0; + const byte = this.buffer[byteOffset + 2]; + const shift = 7 - bitOffset % 8; + const bit = byte >> shift & 1; + bits[bitOffset] = bit; + } + return bits; + } + static fromInt8Array(array3) { + const buffer2 = ByteUtils.allocate(array3.byteLength + 2); + buffer2[0] = Binary.VECTOR_TYPE.Int8; + buffer2[1] = 0; + const intBytes = new Uint8Array(array3.buffer, array3.byteOffset, array3.byteLength); + buffer2.set(intBytes, 2); + const bin = new this(buffer2, this.SUBTYPE_VECTOR); + validateBinaryVector(bin); + return bin; + } + static fromFloat32Array(array3) { + const binaryBytes = ByteUtils.allocate(array3.byteLength + 2); + binaryBytes[0] = Binary.VECTOR_TYPE.Float32; + binaryBytes[1] = 0; + const floatBytes = new Uint8Array(array3.buffer, array3.byteOffset, array3.byteLength); + binaryBytes.set(floatBytes, 2); + if (NumberUtils.isBigEndian) + ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2)); + const bin = new this(binaryBytes, this.SUBTYPE_VECTOR); + validateBinaryVector(bin); + return bin; + } + static fromPackedBits(array3, padding = 0) { + const buffer2 = ByteUtils.allocate(array3.byteLength + 2); + buffer2[0] = Binary.VECTOR_TYPE.PackedBit; + buffer2[1] = padding; + buffer2.set(array3, 2); + const bin = new this(buffer2, this.SUBTYPE_VECTOR); + validateBinaryVector(bin); + return bin; + } + static fromBits(bits) { + const byteLength = bits.length + 7 >>> 3; + const bytes = new Uint8Array(byteLength + 2); + bytes[0] = Binary.VECTOR_TYPE.PackedBit; + const remainder = bits.length % 8; + bytes[1] = remainder === 0 ? 0 : 8 - remainder; + for (let bitOffset = 0;bitOffset < bits.length; bitOffset++) { + const byteOffset = bitOffset >>> 3; + const bit = bits[bitOffset]; + if (bit !== 0 && bit !== 1) { + throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`); } + if (bit === 0) + continue; + const shift = 7 - bitOffset % 8; + bytes[byteOffset + 2] |= bit << shift; } - return { status: status.value, value: input.data }; + return new this(bytes, Binary.SUBTYPE_VECTOR); } - _regex(regex2, validation, message) { - return this.refinement((data) => regex2.test(data), { - validation, - code: ZodIssueCode4.invalid_string, - ...errorUtil2.errToObj(message) - }); + } + Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; + Binary.BUFFER_SIZE = 256; + Binary.SUBTYPE_DEFAULT = 0; + Binary.SUBTYPE_FUNCTION = 1; + Binary.SUBTYPE_BYTE_ARRAY = 2; + Binary.SUBTYPE_UUID_OLD = 3; + Binary.SUBTYPE_UUID = 4; + Binary.SUBTYPE_MD5 = 5; + Binary.SUBTYPE_ENCRYPTED = 6; + Binary.SUBTYPE_COLUMN = 7; + Binary.SUBTYPE_SENSITIVE = 8; + Binary.SUBTYPE_VECTOR = 9; + Binary.SUBTYPE_USER_DEFINED = 128; + Binary.VECTOR_TYPE = Object.freeze({ + Int8: 3, + Float32: 39, + PackedBit: 16 + }); + function validateBinaryVector(vector) { + if (vector.sub_type !== Binary.SUBTYPE_VECTOR) + return; + const size = vector.position; + const datatype = vector.buffer[0]; + const padding = vector.buffer[1]; + if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) && padding !== 0) { + throw new BSONError("Invalid Vector: padding must be zero for int8 and float32 vectors"); } - _addCheck(check3) { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, check3] - }); + if (datatype === Binary.VECTOR_TYPE.Float32) { + if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) { + throw new BSONError("Invalid Vector: Float32 vector must contain a multiple of 4 bytes"); + } } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); + if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) { + throw new BSONError("Invalid Vector: padding must be zero for packed bit vectors that are empty"); } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); + if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) { + throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`); } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); + } + var UUID_BYTE_LENGTH = 16; + var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; + var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; + + class UUID2 extends Binary { + constructor(input) { + let bytes; + if (input == null) { + bytes = UUID2.generate(); + } else if (input instanceof UUID2) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } else if (typeof input === "string") { + bytes = UUID2.bytesFromString(input); + } else { + throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); + get id() { + return this.buffer; } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); + set id(value) { + this.buffer = value; } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); + toHexString(includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(this.buffer.subarray(0, 4)), + ByteUtils.toHex(this.buffer.subarray(4, 6)), + ByteUtils.toHex(this.buffer.subarray(6, 8)), + ByteUtils.toHex(this.buffer.subarray(8, 10)), + ByteUtils.toHex(this.buffer.subarray(10, 16)) + ].join("-"); + } + return ByteUtils.toHex(this.buffer); } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); + toString(encoding) { + if (encoding === "hex") + return ByteUtils.toHex(this.id); + if (encoding === "base64") + return ByteUtils.toBase64(this.id); + return this.toHexString(); } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); + toJSON() { + return this.toHexString(); } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID2) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID2(otherId).id, this.id); + } catch { + return false; + } } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil2.errToObj(message) - }); + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + return bytes; } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); + static isValid(input) { + if (!input) { + return false; + } + if (typeof input === "string") { + return UUID2.isValidUUIDString(input); + } + if (isUint8Array(input)) { + return input.byteLength === UUID_BYTE_LENGTH; + } + return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16; } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); + static createFromHexString(hexString) { + const buffer2 = UUID2.bytesFromString(hexString); + return new UUID2(buffer2); } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); + static createFromBase64(base647) { + return new UUID2(ByteUtils.fromBase64(base647)); + } + static bytesFromString(representation) { + if (!UUID2.isValidUUIDString(representation)) { + throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation"); } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil2.errToObj(options?.message) - }); + return ByteUtils.fromHex(representation.replace(/-/g, "")); } - date(message) { - return this._addCheck({ kind: "date", message }); + static isValidUUIDString(representation) { + return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new UUID(${inspect(this.toHexString(), options)})`; + } + } + + class Code extends BSONValue { + get _bsontype() { + return "Code"; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil2.errToObj(options?.message) - }); + return { code: this.code }; } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; } - regex(regex2, message) { - return this._addCheck({ - kind: "regex", - regex: regex2, - ...errorUtil2.errToObj(message) - }); + static fromExtendedJSON(doc3) { + return new Code(doc3.$code, doc3.$scope); } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil2.errToObj(options?.message) - }); + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + let parametersString = inspect(this.code, options); + const multiLineFn = parametersString.includes(` +`); + if (this.scope != null) { + parametersString += `,${multiLineFn ? ` +` : " "}${inspect(this.scope, options)}`; + } + const endingNewline = multiLineFn && this.scope === null; + return `new Code(${multiLineFn ? ` +` : ""}${parametersString}${endingNewline ? ` +` : ""})`; } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil2.errToObj(message) - }); + } + function isDBRefLike(value) { + return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || ("$db" in value) && typeof value.$db === "string"); + } + + class DBRef extends BSONValue { + get _bsontype() { + return "DBRef"; } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil2.errToObj(message) - }); + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split("."); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil2.errToObj(message) - }); + get namespace() { + return this.collection; } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil2.errToObj(message) - }); + set namespace(value) { + this.collection = value; } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil2.errToObj(message) - }); + toJSON() { + const o2 = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o2.$db = this.db; + return o2; } - nonempty(message) { - return this.min(1, errorUtil2.errToObj(message)); + toExtendedJSON(options) { + options = options || {}; + let o2 = { + $ref: this.collection, + $id: this.oid + }; + if (options.legacy) { + return o2; + } + if (this.db) + o2.$db = this.db; + o2 = Object.assign(o2, this.fields); + return o2; } - trim() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); + static fromExtendedJSON(doc3) { + const copy = Object.assign({}, doc3); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc3.$ref, doc3.$id, doc3.$db, copy); } - toLowerCase() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const args = [ + inspect(this.namespace, options), + inspect(this.oid, options), + ...this.db ? [inspect(this.db, options)] : [], + ...Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [] + ]; + args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; + return `new DBRef(${args.join(", ")})`; } - toUpperCase() { - return new ZodString4({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); + } + function removeLeadingZerosAndExplicitPlus(str) { + if (str === "") { + return str; } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); + let startIndex = 0; + const isNegative = str[startIndex] === "-"; + const isExplicitlyPositive = str[startIndex] === "+"; + if (isExplicitlyPositive || isNegative) { + startIndex += 1; } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); + let foundInsignificantZero = false; + for (;startIndex < str.length && str[startIndex] === "0"; ++startIndex) { + foundInsignificantZero = true; } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); + if (!foundInsignificantZero) { + return isExplicitlyPositive ? str.slice(1) : str; + } + return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`; + } + function validateStringCharacters(str, radix) { + radix = radix ?? 10; + const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix); + const regex2 = new RegExp(`[^-+${validCharacters}]`, "i"); + return regex2.test(str) ? false : str; + } + var wasm = undefined; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; + } catch {} + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + var INT_CACHE = {}; + var UINT_CACHE = {}; + var MAX_INT64_STRING_LENGTH = 20; + var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; + + class Long extends BSONValue { + get _bsontype() { + return "Long"; + } + get __isLong__() { + return true; + } + constructor(lowOrValue = 0, highOrUnsigned, unsigned) { + super(); + const unsignedBool = typeof highOrUnsigned === "boolean" ? highOrUnsigned : Boolean(unsigned); + const high = typeof highOrUnsigned === "number" ? highOrUnsigned : 0; + const res = typeof lowOrValue === "string" ? Long.fromString(lowOrValue, unsignedBool) : typeof lowOrValue === "bigint" ? Long.fromBigInt(lowOrValue, unsignedBool) : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool }; + this.low = res.low; + this.high = res.high; + this.unsigned = res.unsigned; + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + let obj, cachedObj, cache2; + if (unsigned) { + value >>>= 0; + if (cache2 = 0 <= value && value < 256) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); + if (cache2) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache2 = -128 <= value && value < 128) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = Long.fromBits(value, value < 0 ? -1 : 0, false); + if (cache2) + INT_CACHE[value] = obj; + return obj; + } + } + static fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? Long.UZERO : Long.ZERO; + if (unsigned) { + if (value < 0) + return Long.UZERO; + if (value >= TWO_PWR_64_DBL) + return Long.MAX_UNSIGNED_VALUE; + } else { + if (value <= -9223372036854776000) + return Long.MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return Long.MAX_VALUE; + } + if (value < 0) + return Long.fromNumber(-value, unsigned).neg(); + return Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); + static fromBigInt(value, unsigned) { + const FROM_BIGINT_BIT_MASK = BigInt(4294967295); + const FROM_BIGINT_BIT_SHIFT = BigInt(32); + return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number(value >> FROM_BIGINT_BIT_SHIFT & FROM_BIGINT_BIT_MASK), unsigned); } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); + static _fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError("empty string"); + if (radix < 2 || 36 < radix) + throw new BSONError("radix"); + let p2; + if ((p2 = str.indexOf("-")) > 0) + throw new BSONError("interior hyphen"); + else if (p2 === 0) { + return Long._fromString(str.substring(1), unsigned, radix).neg(); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 8)); + let result = Long.ZERO; + for (let i2 = 0;i2 < str.length; i2 += 8) { + const size = Math.min(8, str.length - i2), value = parseInt(str.substring(i2, i2 + size), radix); + if (size < 8) { + const power = Long.fromNumber(Math.pow(radix, size)); + result = result.mul(power).add(Long.fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); + static fromStringStrict(str, unsignedOrRadix, radix) { + let unsigned = false; + if (typeof unsignedOrRadix === "number") { + radix = unsignedOrRadix, unsignedOrRadix = false; + } else { + unsigned = !!unsignedOrRadix; + } + radix ??= 10; + if (str.trim() !== str) { + throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`); + } + if (!validateStringCharacters(str, radix)) { + throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`); + } + const cleanedStr = removeLeadingZerosAndExplicitPlus(str); + const result = Long._fromString(cleanedStr, unsigned, radix); + if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) { + throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`); + } + return result; } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); + static fromString(str, unsignedOrRadix, radix) { + let unsigned = false; + if (typeof unsignedOrRadix === "number") { + radix = unsignedOrRadix, unsignedOrRadix = false; + } else { + unsigned = !!unsignedOrRadix; + } + radix ??= 10; + if (str === "NaN" && radix < 24) { + return Long.ZERO; + } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) { + return Long.ZERO; + } + return Long._fromString(str, unsigned, radix); } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + static fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); + static fromBytesBE(bytes, unsigned) { + return new Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + static isLong(value) { + return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true; } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); + static fromValue(val, unsigned) { + if (typeof val === "number") + return Long.fromNumber(val, unsigned); + if (typeof val === "string") + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + const a48 = this.high >>> 16; + const a32 = this.high & 65535; + const a16 = this.low >>> 16; + const a00 = this.low & 65535; + const b48 = addend.high >>> 16; + const b32 = addend.high & 65535; + const b16 = addend.low >>> 16; + const b00 = addend.low & 65535; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 + b48; + c48 &= 65535; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); + compare(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.eq(other)) + return 0; + const thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); + comp(other) { + return this.compare(other); } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError("division by zero"); + if (wasm) { + if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { + return this; } + const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + if (this.isZero()) + return this.unsigned ? Long.UZERO : Long.ZERO; + let approx, rem, res; + if (!this.unsigned) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + const halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(Long.ZERO)) { + return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(Long.MIN_VALUE)) + return this.unsigned ? Long.UZERO : Long.ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = Long.ZERO; + } else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + let approxRes = Long.fromNumber(approx); + let approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); } - return max; + return res; } - }; - ZodString4.create = (params) => { - return new ZodString4({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); - }; - ZodNumber4 = class ZodNumber4 extends ZodType4 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; + div(divisor) { + return this.divide(divisor); } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.number, - received: ctx2.parsedType - }); - return INVALID2; - } - let ctx = undefined; - const status = new ParseStatus2; - for (const check3 of this._def.checks) { - if (check3.kind === "int") { - if (!util3.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: "integer", - received: "float", - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "min") { - const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: check3.value, - type: "number", - inclusive: check3.inclusive, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: check3.value, - type: "number", - inclusive: check3.inclusive, - exact: false, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "multipleOf") { - if (floatSafeRemainder4(input.data, check3.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.not_multiple_of, - multipleOf: check3.value, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.not_finite, - message: check3.message - }); - status.dirty(); - } - } else { - util3.assertNever(check3); - } - } - return { status: status.value, value: input.data }; + equals(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); + eq(other) { + return this.equals(other); } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); + getHighBits() { + return this.high; } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); + getHighBitsUnsigned() { + return this.high >>> 0; } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); + getLowBits() { + return this.low; } - setLimit(kind, value, inclusive, message) { - return new ZodNumber4({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); + getLowBitsUnsigned() { + return this.low >>> 0; } - _addCheck(check3) { - return new ZodNumber4({ - ...this._def, - checks: [...this._def.checks, check3] - }); + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31;bit > 0; bit--) + if ((val & 1 << bit) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil2.toString(message) - }); + greaterThan(other) { + return this.comp(other) > 0; } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); + gt(other) { + return this.greaterThan(other); } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil2.toString(message) - }); + greaterThanOrEqual(other) { + return this.comp(other) >= 0; } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); + gte(other) { + return this.greaterThanOrEqual(other); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil2.toString(message) - }); + ge(other) { + return this.greaterThanOrEqual(other); } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); + isEven() { + return (this.low & 1) === 0; } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil2.toString(message) - }); + isNegative() { + return !this.unsigned && this.high < 0; } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil2.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil2.toString(message) - }); + isOdd() { + return (this.low & 1) === 1; } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; + isPositive() { + return this.unsigned || this.high >= 0; } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + isZero() { + return this.high === 0 && this.low === 0; } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util3.isInteger(ch.value)); + lessThan(other) { + return this.comp(other) < 0; } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); + lt(other) { + return this.lessThan(other); } - }; - ZodNumber4.create = (params) => { - return new ZodNumber4({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); - }; - ZodBigInt4 = class ZodBigInt4 extends ZodType4 { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; + lessThanOrEqual(other) { + return this.comp(other) <= 0; } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.bigint) { - return this._getInvalidInput(input); + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); } - let ctx = undefined; - const status = new ParseStatus2; - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - const tooSmall = check3.inclusive ? input.data < check3.value : input.data <= check3.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - type: "bigint", - minimum: check3.value, - inclusive: check3.inclusive, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "max") { - const tooBig = check3.inclusive ? input.data > check3.value : input.data >= check3.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - type: "bigint", - maximum: check3.value, - inclusive: check3.inclusive, - message: check3.message - }); - status.dirty(); - } - } else if (check3.kind === "multipleOf") { - if (input.data % check3.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.not_multiple_of, - multipleOf: check3.value, - message: check3.message - }); - status.dirty(); - } - } else { - util3.assertNever(check3); - } + return this.sub(this.div(divisor).mul(divisor)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + if (wasm) { + const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); + return Long.fromBits(low, wasm.get_high(), this.unsigned); } - return { status: status.value, value: input.data }; + if (multiplier.isZero()) + return Long.ZERO; + if (this.eq(Long.MIN_VALUE)) + return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (multiplier.eq(Long.MIN_VALUE)) + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + const a48 = this.high >>> 16; + const a32 = this.high & 65535; + const a16 = this.low >>> 16; + const a00 = this.low & 65535; + const b48 = multiplier.high >>> 16; + const b32 = multiplier.high & 65535; + const b16 = multiplier.low >>> 16; + const b00 = multiplier.low & 65535; + let c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 65535; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 65535; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.bigint, - received: ctx.parsedType - }); - return INVALID2; + mul(multiplier) { + return this.multiply(multiplier); } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil2.toString(message)); + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil2.toString(message)); + neg() { + return this.negate(); } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil2.toString(message)); + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil2.toString(message)); + notEquals(other) { + return !this.equals(other); } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt4({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil2.toString(message) - } - ] - }); + neq(other) { + return this.notEquals(other); } - _addCheck(check3) { - return new ZodBigInt4({ - ...this._def, - checks: [...this._def.checks, check3] - }); + ne(other) { + return this.notEquals(other); } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil2.toString(message) - }); + shiftLeft(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); + else + return Long.fromBits(0, this.low << numBits - 32, this.unsigned); } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); + shl(numBits) { + return this.shiftLeft(numBits); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil2.toString(message) - }); + shiftRight(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); + else + return Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil2.toString(message) - }); + shr(numBits) { + return this.shiftRight(numBits); } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + shiftRightUnsigned(numBits) { + if (Long.isLong(numBits)) + numBits = numBits.toInt(); + numBits &= 63; + if (numBits === 0) + return this; + else { + const high = this.high; + if (numBits < 32) { + const low = this.low; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); + } else if (numBits === 32) + return Long.fromBits(high, 0, this.unsigned); + else + return Long.fromBits(high >>> numBits - 32, 0, this.unsigned); } - return min; } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); } - }; - ZodBigInt4.create = (params) => { - return new ZodBigInt4({ - checks: [], - typeName: ZodFirstPartyTypeKind3.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams2(params) - }); - }; - ZodBoolean4 = class ZodBoolean4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.boolean, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); + shru(numBits) { + return this.shiftRightUnsigned(numBits); } - }; - ZodBoolean4.create = (params) => { - return new ZodBoolean4({ - typeName: ZodFirstPartyTypeKind3.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams2(params) - }); - }; - ZodDate4 = class ZodDate4 extends ZodType4 { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.date, - received: ctx2.parsedType - }); - return INVALID2; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode4.invalid_date - }); - return INVALID2; - } - const status = new ParseStatus2; - let ctx = undefined; - for (const check3 of this._def.checks) { - if (check3.kind === "min") { - if (input.data.getTime() < check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - message: check3.message, - inclusive: true, - exact: false, - minimum: check3.value, - type: "date" - }); - status.dirty(); - } - } else if (check3.kind === "max") { - if (input.data.getTime() > check3.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - message: check3.message, - inclusive: true, - exact: false, - maximum: check3.value, - type: "date" - }); - status.dirty(); - } - } else { - util3.assertNever(check3); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); } - _addCheck(check3) { - return new ZodDate4({ - ...this._def, - checks: [...this._def.checks, check3] - }); + sub(subtrahend) { + return this.subtract(subtrahend); } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil2.toString(message) - }); + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil2.toString(message) - }); + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; + toBigInt() { + return BigInt(this.toString()); } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); } - }; - ZodDate4.create = (params) => { - return new ZodDate4({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind3.ZodDate, - ...processCreateParams2(params) - }); - }; - ZodSymbol4 = class ZodSymbol4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.symbol, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); + toBytesLE() { + const hi = this.high, lo = this.low; + return [ + lo & 255, + lo >>> 8 & 255, + lo >>> 16 & 255, + lo >>> 24, + hi & 255, + hi >>> 8 & 255, + hi >>> 16 & 255, + hi >>> 24 + ]; } - }; - ZodSymbol4.create = (params) => { - return new ZodSymbol4({ - typeName: ZodFirstPartyTypeKind3.ZodSymbol, - ...processCreateParams2(params) - }); - }; - ZodUndefined4 = class ZodUndefined4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.undefined, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); + toBytesBE() { + const hi = this.high, lo = this.low; + return [ + hi >>> 24, + hi >>> 16 & 255, + hi >>> 8 & 255, + hi & 255, + lo >>> 24, + lo >>> 16 & 255, + lo >>> 8 & 255, + lo & 255 + ]; } - }; - ZodUndefined4.create = (params) => { - return new ZodUndefined4({ - typeName: ZodFirstPartyTypeKind3.ZodUndefined, - ...processCreateParams2(params) - }); - }; - ZodNull4 = class ZodNull4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.null, - received: ctx.parsedType - }); - return INVALID2; + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError("radix"); + if (this.isZero()) + return "0"; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else + return "-" + this.neg().toString(radix); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ""; + while (true) { + const remDiv = rem.div(radixToPower); + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; + let digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) + digits = "0" + digits; + result = "" + digits + result; + } } - return OK2(input.data); - } - }; - ZodNull4.create = (params) => { - return new ZodNull4({ - typeName: ZodFirstPartyTypeKind3.ZodNull, - ...processCreateParams2(params) - }); - }; - ZodAny4 = class ZodAny4 extends ZodType4 { - constructor() { - super(...arguments); - this._any = true; } - _parse(input) { - return OK2(input.data); + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); } - }; - ZodAny4.create = (params) => { - return new ZodAny4({ - typeName: ZodFirstPartyTypeKind3.ZodAny, - ...processCreateParams2(params) - }); - }; - ZodUnknown4 = class ZodUnknown4 extends ZodType4 { - constructor() { - super(...arguments); - this._unknown = true; + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); } - _parse(input) { - return OK2(input.data); + eqz() { + return this.isZero(); } - }; - ZodUnknown4.create = (params) => { - return new ZodUnknown4({ - typeName: ZodFirstPartyTypeKind3.ZodUnknown, - ...processCreateParams2(params) - }); - }; - ZodNever4 = class ZodNever4 extends ZodType4 { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.never, - received: ctx.parsedType - }); - return INVALID2; + le(other) { + return this.lessThanOrEqual(other); } - }; - ZodNever4.create = (params) => { - return new ZodNever4({ - typeName: ZodFirstPartyTypeKind3.ZodNever, - ...processCreateParams2(params) - }); - }; - ZodVoid4 = class ZodVoid4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.void, - received: ctx.parsedType - }); - return INVALID2; - } - return OK2(input.data); + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; } - }; - ZodVoid4.create = (params) => { - return new ZodVoid4({ - typeName: ZodFirstPartyTypeKind3.ZodVoid, - ...processCreateParams2(params) - }); - }; - ZodArray4 = class ZodArray4 extends ZodType4 { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext2(ctx, { - code: tooBig ? ZodIssueCode4.too_big : ZodIssueCode4.too_small, - minimum: tooSmall ? def.exactLength.value : undefined, - maximum: tooBig ? def.exactLength.value : undefined, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } + static fromExtendedJSON(doc3, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc3.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError("$numberLong string is too long"); } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } + if (!DECIMAL_REG_EX.test(doc3.$numberLong)) { + throw new BSONError(`$numberLong string "${doc3.$numberLong}" is in an invalid format`); } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } + if (useBigInt64) { + const bigIntResult = BigInt(doc3.$numberLong); + return BigInt.asIntN(64, bigIntResult); } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - })).then((result2) => { - return ParseStatus2.mergeArray(status, result2); - }); + const longResult = Long.fromString(doc3.$numberLong); + if (relaxed) { + return longResult.toNumber(); } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i)); - }); - return ParseStatus2.mergeArray(status, result); + return longResult; } - get element() { - return this._def.type; + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const longVal = inspect(this.toString(), options); + const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ""; + return `new Long(${longVal}${unsignedVal})`; } - min(minLength, message) { - return new ZodArray4({ - ...this._def, - minLength: { value: minLength, message: errorUtil2.toString(message) } - }); + } + Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); + Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 0, true); + Long.ZERO = Long.fromInt(0); + Long.UZERO = Long.fromInt(0, true); + Long.ONE = Long.fromInt(1); + Long.UONE = Long.fromInt(1, true); + Long.NEG_ONE = Long.fromInt(-1); + Long.MAX_VALUE = Long.fromBits(4294967295 | 0, 2147483647 | 0, false); + Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false); + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + var NAN_BUFFER = ByteUtils.fromNumberArray([ + 124, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ].reverse()); + var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 248, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ].reverse()); + var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 120, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ].reverse()); + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + var COMBINATION_MASK = 31; + var EXPONENT_MASK = 16383; + var COMBINATION_INFINITY = 30; + var COMBINATION_NAN = 31; + function isDigit(value) { + return !isNaN(parseInt(value, 10)); + } + function divideu128(value) { + const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + let _rem = Long.fromNumber(0); + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; } - max(maxLength, message) { - return new ZodArray4({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil2.toString(message) } - }); + for (let i2 = 0;i2 <= 3; i2++) { + _rem = _rem.shiftLeft(32); + _rem = _rem.add(new Long(value.parts[i2], 0)); + value.parts[i2] = _rem.div(DIVISOR).low; + _rem = _rem.modulo(DIVISOR); } - length(len, message) { - return new ZodArray4({ - ...this._def, - exactLength: { value: len, message: errorUtil2.toString(message) } - }); + return { quotient: value, rem: _rem }; + } + function multiply64x2(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } - nonempty(message) { - return this.min(1, message); + const leftHigh = left.shiftRightUnsigned(32); + const leftLow = new Long(left.getLowBits(), 0); + const rightHigh = right.shiftRightUnsigned(32); + const rightLow = new Long(right.getLowBits(), 0); + let productHigh = leftHigh.multiply(rightHigh); + let productMid = leftHigh.multiply(rightLow); + const productMid2 = leftLow.multiply(rightHigh); + let productLow = leftLow.multiply(rightLow); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + return { high: productHigh, low: productLow }; + } + function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + const ulleft = left.low >>> 0; + const ulright = right.low >>> 0; + if (ulleft < ulright) + return true; } - }; - ZodArray4.create = (schema, params) => { - return new ZodArray4({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind3.ZodArray, - ...processCreateParams2(params) - }); - }; - ZodObject4 = class ZodObject4 extends ZodType4 { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; + return false; + } + function invalidErr(string7, message) { + throw new BSONError(`"${string7}" is not a valid Decimal128 string - ${message}`); + } + + class Decimal128 extends BSONValue { + get _bsontype() { + return "Decimal128"; } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util3.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; + constructor(bytes) { + super(); + if (typeof bytes === "string") { + this.bytes = Decimal128.fromString(bytes).bytes; + } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError("Decimal128 must take a Buffer of 16 bytes"); + } + this.bytes = bytes; + } else { + throw new BSONError("Decimal128 must take a Buffer or string"); + } } - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext2(ctx2, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.object, - received: ctx2.parsedType - }); - return INVALID2; + static fromString(representation) { + return Decimal128._fromString(representation, { allowRounding: false }); + } + static fromStringWithRounding(representation) { + return Decimal128._fromString(representation, { allowRounding: true }); + } + static _fromString(representation, options) { + let isNegative = false; + let sawSign = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let lastDigit = 0; + let exponent = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index2 = 0; + if (representation.length >= 7000) { + throw new BSONError("" + representation + " not a valid Decimal128 string"); } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever4 && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) { + throw new BSONError("" + representation + " not a valid Decimal128 string"); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, "missing exponent power"); + if (e && unsignedNumber === undefined) + invalidErr(representation, "missing exponent base"); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, "missing e before exponent"); } } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); + if (representation[index2] === "+" || representation[index2] === "-") { + sawSign = true; + isNegative = representation[index2++] === "-"; } - if (this._def.catchall instanceof ZodNever4) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); + if (!isDigit(representation[index2]) && representation[index2] !== ".") { + if (representation[index2] === "i" || representation[index2] === "I") { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } else if (representation[index2] === "N") { + return new Decimal128(NAN_BUFFER); + } + } + while (isDigit(representation[index2]) || representation[index2] === ".") { + if (representation[index2] === ".") { + if (sawRadix) + invalidErr(representation, "contains multiple periods"); + sawRadix = true; + index2 = index2 + 1; + continue; + } + if (nDigitsStored < MAX_DIGITS) { + if (representation[index2] !== "0" || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + foundNonZero = true; + digits[digitsInsert++] = parseInt(representation[index2], 10); + nDigitsStored = nDigitsStored + 1; } - } else if (unknownKeys === "strip") {} else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } + if (foundNonZero) + nDigits = nDigits + 1; + if (sawRadix) + radixPosition = radixPosition + 1; + nDigitsRead = nDigitsRead + 1; + index2 = index2 + 1; + } + if (sawRadix && !nDigitsRead) + throw new BSONError("" + representation + " not a valid Decimal128 string"); + if (representation[index2] === "e" || representation[index2] === "E") { + const match2 = representation.substr(++index2).match(EXPONENT_REGEX); + if (!match2 || !match2[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match2[0], 10); + index2 = index2 + match2[0].length; + } + if (representation[index2]) + return new Decimal128(NAN_BUFFER); + if (!nDigitsStored) { + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + if (significantDigits !== 1) { + while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") { + significantDigits = significantDigits - 1; + } } } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus2.mergeObjectSync(status, syncPairs); - }); + if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { + exponent = EXPONENT_MIN; } else { - return ParseStatus2.mergeObjectSync(status, pairs); + exponent = exponent - radixPosition; } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil2.errToObj; - return new ZodObject4({ - ...this._def, - unknownKeys: "strict", - ...message !== undefined ? { - errorMap: (issue3, ctx) => { - const defaultError = this._def.errorMap?.(issue3, ctx).message ?? ctx.defaultError; - if (issue3.code === "unrecognized_keys") - return { - message: errorUtil2.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit >= MAX_DIGITS) { + if (significantDigits === 0) { + exponent = EXPONENT_MAX; + break; } - } : {} - }); - } - strip() { - return new ZodObject4({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new ZodObject4({ - ...this._def, - unknownKeys: "passthrough" - }); - } - extend(augmentation) { - return new ZodObject4({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - merge(merging) { - const merged = new ZodObject4({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind3.ZodObject - }); - return merged; - } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - catchall(index2) { - return new ZodObject4({ - ...this._def, - catchall: index2 - }); - } - pick(mask) { - const shape = {}; - for (const key of util3.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; + invalidErr(representation, "overflow"); } + exponent = exponent - 1; } - return new ZodObject4({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; + if (options.allowRounding) { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + const digitsString = digits.join(""); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, "overflow"); + } + } + if (lastDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + let roundBit = 0; + if (roundDigit >= 5) { + roundBit = 1; + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; + for (let i2 = firstNonZero + lastDigit + 2;i2 < endOfString; i2++) { + if (parseInt(representation[i2], 10)) { + roundBit = 1; + break; + } + } + } + } + if (roundBit) { + let dIdx = lastDigit; + for (;dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } else { + break; + } + } + } + } + } else { + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0) { + if (significantDigits === 0) { + exponent = EXPONENT_MIN; + break; + } + invalidErr(representation, "exponent underflow"); + } + if (nDigitsStored < nDigits) { + if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) { + invalidErr(representation, "inexact rounding"); + } + nDigits = nDigits - 1; + } else { + if (digits[lastDigit] !== 0) { + invalidErr(representation, "inexact rounding"); + } + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + invalidErr(representation, "overflow"); + } + } + if (lastDigit + 1 < significantDigits) { + if (sawRadix) { + firstNonZero = firstNonZero + 1; + } + if (sawSign) { + firstNonZero = firstNonZero + 1; + } + const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); + if (roundDigit !== 0) { + invalidErr(representation, "inexact rounding"); + } } } - return new ZodObject4({ - ...this._def, - shape: () => shape - }); - } - deepPartial() { - return deepPartialify2(this); - } - partial(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit < 17) { + let dIdx = 0; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + for (;dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + let dIdx = 0; + significandHigh = Long.fromNumber(digits[dIdx++]); + for (;dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + significandLow = Long.fromNumber(digits[dIdx++]); + for (;dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); } } - return new ZodObject4({ - ...this._def, - shape: () => newShape - }); + const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); + significand.low = significand.low.add(significandLow); + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311))); + } + dec.low = significand.low; + if (isNegative) { + dec.high = dec.high.or(Long.fromString("9223372036854775808")); + } + const buffer2 = ByteUtils.allocateUnsafe(16); + index2 = 0; + buffer2[index2++] = dec.low.low & 255; + buffer2[index2++] = dec.low.low >> 8 & 255; + buffer2[index2++] = dec.low.low >> 16 & 255; + buffer2[index2++] = dec.low.low >> 24 & 255; + buffer2[index2++] = dec.low.high & 255; + buffer2[index2++] = dec.low.high >> 8 & 255; + buffer2[index2++] = dec.low.high >> 16 & 255; + buffer2[index2++] = dec.low.high >> 24 & 255; + buffer2[index2++] = dec.high.low & 255; + buffer2[index2++] = dec.high.low >> 8 & 255; + buffer2[index2++] = dec.high.low >> 16 & 255; + buffer2[index2++] = dec.high.low >> 24 & 255; + buffer2[index2++] = dec.high.high & 255; + buffer2[index2++] = dec.high.high >> 8 & 255; + buffer2[index2++] = dec.high.high >> 16 & 255; + buffer2[index2++] = dec.high.high >> 24 & 255; + return new Decimal128(buffer2); } - required(mask) { - const newShape = {}; - for (const key of util3.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i2 = 0;i2 < significand.length; i2++) + significand[i2] = 0; + let index2 = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j2, k2; + const string7 = []; + index2 = 0; + const buffer2 = this.bytes; + const low = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; + const midl = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; + const midh = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; + const high = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; + index2 = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string7.push("-"); + } + const combination = high >> 26 & COMBINATION_MASK; + if (combination >> 3 === 3) { + if (combination === COMBINATION_INFINITY) { + return string7.join("") + "Infinity"; + } else if (combination === COMBINATION_NAN) { + return "NaN"; } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional4) { - newField = newField._def.innerType; - } - newShape[key] = newField; + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 8 + (high >> 14 & 1); } + } else { + significand_msb = high >> 14 & 7; + biased_exponent = high >> 17 & EXPONENT_MASK; } - return new ZodObject4({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum2(util3.objectKeys(this.shape)); - } - }; - ZodObject4.create = (shape, params) => { - return new ZodObject4({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); - }; - ZodObject4.strictCreate = (shape, params) => { - return new ZodObject4({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); - }; - ZodObject4.lazycreate = (shape, params) => { - return new ZodObject4({ - shape, - unknownKeys: "strip", - catchall: ZodNever4.create(), - typeName: ZodFirstPartyTypeKind3.ZodObject, - ...processCreateParams2(params) - }); - }; - ZodUnion4 = class ZodUnion4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; + const exponent = biased_exponent - EXPONENT_BIAS; + significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { + is_zero = true; + } else { + for (k2 = 3;k2 >= 0; k2--) { + let least_digits = 0; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j2 = 8;j2 >= 0; j2--) { + significand[k2 * 9 + j2] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); } } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } + } + if (is_zero) { + significand_digits = 1; + significand[index2] = 0; + } else { + significand_digits = 36; + while (!significand[index2]) { + significand_digits = significand_digits - 1; + index2 = index2 + 1; } - const unionErrors = results.map((result) => new ZodError5(result.ctx.common.issues)); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_union, - unionErrors - }); - return INVALID2; } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + if (significand_digits > 34) { + string7.push(`${0}`); + if (exponent > 0) + string7.push(`E+${exponent}`); + else if (exponent < 0) + string7.push(`E${exponent}`); + return string7.join(""); + } + string7.push(`${significand[index2++]}`); + significand_digits = significand_digits - 1; + if (significand_digits) { + string7.push("."); + } + for (let i2 = 0;i2 < significand_digits; i2++) { + string7.push(`${significand[index2++]}`); + } + string7.push("E"); + if (scientific_exponent > 0) { + string7.push(`+${scientific_exponent}`); + } else { + string7.push(`${scientific_exponent}`); + } } else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; + if (exponent >= 0) { + for (let i2 = 0;i2 < significand_digits; i2++) { + string7.push(`${significand[index2++]}`); } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); + } else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i2 = 0;i2 < radix_position; i2++) { + string7.push(`${significand[index2++]}`); + } + } else { + string7.push("0"); + } + string7.push("."); + while (radix_position++ < 0) { + string7.push("0"); + } + for (let i2 = 0;i2 < significand_digits - Math.max(radix_position - 1, 0); i2++) { + string7.push(`${significand[index2++]}`); } } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError5(issues2)); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_union, - unionErrors - }); - return INVALID2; } + return string7.join(""); } - get options() { - return this._def.options; - } - }; - ZodUnion4.create = (types3, params) => { - return new ZodUnion4({ - options: types3, - typeName: ZodFirstPartyTypeKind3.ZodUnion, - ...processCreateParams2(params) - }); - }; - ZodDiscriminatedUnion4 = class ZodDiscriminatedUnion4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID2; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } + toJSON() { + return { $numberDecimal: this.toString() }; } - get discriminator() { - return this._def.discriminator; + toExtendedJSON() { + return { $numberDecimal: this.toString() }; } - get options() { - return this._def.options; + static fromExtendedJSON(doc3) { + return Decimal128.fromString(doc3.$numberDecimal); } - get optionsMap() { - return this._def.optionsMap; + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const d128string = inspect(this.toString(), options); + return `new Decimal128(${d128string})`; } - static create(discriminator, options, params) { - const optionsMap = new Map; - for (const type of options) { - const discriminatorValues = getDiscriminator2(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion4({ - typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams2(params) - }); + } + + class Double extends BSONValue { + get _bsontype() { + return "Double"; } - }; - ZodIntersection4 = class ZodIntersection4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { - return INVALID2; - } - const merged = mergeValues4(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_intersection_types - }); - return INVALID2; - } - if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); } + this.value = +value; } - }; - ZodIntersection4.create = (left, right, params) => { - return new ZodIntersection4({ - left, - right, - typeName: ZodFirstPartyTypeKind3.ZodIntersection, - ...processCreateParams2(params) - }); - }; - ZodTuple4 = class ZodTuple4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.array) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.array, - received: ctx.parsedType - }); - return INVALID2; + static fromString(value) { + const coercedValue = Number(value); + if (value === "NaN") + return new Double(NaN); + if (value === "Infinity") + return new Double(Infinity); + if (value === "-Infinity") + return new Double(-Infinity); + if (!Number.isFinite(coercedValue)) { + throw new BSONError(`Input: ${value} is not representable as a Double`); } - if (ctx.data.length < this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID2; + if (value.trim() !== value) { + throw new BSONError(`Input: '${value}' contains whitespace`); } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); + if (value === "") { + throw new BSONError(`Input is an empty string`); } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus2.mergeArray(status, results); - }); - } else { - return ParseStatus2.mergeArray(status, items); + if (/[^-0-9.+eE]/.test(value)) { + throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`); } + return new Double(coercedValue); } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple4({ - ...this._def, - rest - }); - } - }; - ZodTuple4.create = (schemas5, params) => { - if (!Array.isArray(schemas5)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + valueOf() { + return this.value; } - return new ZodTuple4({ - items: schemas5, - typeName: ZodFirstPartyTypeKind3.ZodTuple, - rest: null, - ...processCreateParams2(params) - }); - }; - ZodRecord4 = class ZodRecord4 extends ZodType4 { - get keySchema() { - return this._def.keyType; + toJSON() { + return this.value; } - get valueSchema() { - return this._def.valueType; + toString(radix) { + return this.value.toString(radix); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.object) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.object, - received: ctx.parsedType - }); - return INVALID2; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); + toExtendedJSON(options) { + if (options && (options.legacy || options.relaxed && isFinite(this.value))) { + return this.value; } - if (ctx.common.async) { - return ParseStatus2.mergeObjectAsync(status, pairs); - } else { - return ParseStatus2.mergeObjectSync(status, pairs); + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: "-0.0" }; } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType4) { - return new ZodRecord4({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams2(third) - }); - } - return new ZodRecord4({ - keyType: ZodString4.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind3.ZodRecord, - ...processCreateParams2(second) - }); + static fromExtendedJSON(doc3, options) { + const doubleValue = parseFloat(doc3.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); } - }; - ZodMap4 = class ZodMap4 extends ZodType4 { - get keySchema() { - return this._def.keyType; + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Double(${inspect(this.value, options)})`; } - get valueSchema() { - return this._def.valueType; + } + + class Int32 extends BSONValue { + get _bsontype() { + return "Int32"; } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.map) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.map, - received: ctx.parsedType - }); - return INVALID2; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index2) => { - return { - key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index2, "key"])), - value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index2, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = new Map; - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = new Map; - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID2; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); } + this.value = +value | 0; } - }; - ZodMap4.create = (keyType, valueType, params) => { - return new ZodMap4({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind3.ZodMap, - ...processCreateParams2(params) - }); - }; - ZodSet4 = class ZodSet4 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.set) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.set, - received: ctx.parsedType - }); - return INVALID2; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = new Set; - for (const element of elements2) { - if (element.status === "aborted") - return INVALID2; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); + static fromString(value) { + const cleanedValue = removeLeadingZerosAndExplicitPlus(value); + const coercedValue = Number(value); + if (BSON_INT32_MAX < coercedValue) { + throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`); + } else if (BSON_INT32_MIN > coercedValue) { + throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`); + } else if (!Number.isSafeInteger(coercedValue)) { + throw new BSONError(`Input: '${value}' is not a safe integer`); + } else if (coercedValue.toString() !== cleanedValue) { + throw new BSONError(`Input: '${value}' is not a valid Int32 string`); } + return new Int32(coercedValue); } - min(minSize, message) { - return new ZodSet4({ - ...this._def, - minSize: { value: minSize, message: errorUtil2.toString(message) } - }); + valueOf() { + return this.value; } - max(maxSize, message) { - return new ZodSet4({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil2.toString(message) } - }); + toString(radix) { + return this.value.toString(radix); } - size(size, message) { - return this.min(size, message).max(size, message); + toJSON() { + return this.value; } - nonempty(message) { - return this.min(1, message); + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; } - }; - ZodSet4.create = (valueType, params) => { - return new ZodSet4({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind3.ZodSet, - ...processCreateParams2(params) - }); - }; - ZodFunction3 = class ZodFunction3 extends ZodType4 { - constructor() { - super(...arguments); - this.validate = this.implement; + static fromExtendedJSON(doc3, options) { + return options && options.relaxed ? parseInt(doc3.$numberInt, 10) : new Int32(doc3.$numberInt); } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.function) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.function, - received: ctx.parsedType - }); - return INVALID2; - } - function makeArgsIssue(args, error91) { - return makeIssue2({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), - issueData: { - code: ZodIssueCode4.invalid_arguments, - argumentsError: error91 - } - }); - } - function makeReturnsIssue(returns, error91) { - return makeIssue2({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap4(), en_default4].filter((x) => !!x), - issueData: { - code: ZodIssueCode4.invalid_return_type, - returnTypeError: error91 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise4) { - const me = this; - return OK2(async function(...args) { - const error91 = new ZodError5([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error91.addIssue(makeArgsIssue(args, e)); - throw error91; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error91.addIssue(makeReturnsIssue(result, e)); - throw error91; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK2(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError5([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError5([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new Int32(${inspect(this.value, options)})`; } - parameters() { - return this._def.args; + } + + class MaxKey extends BSONValue { + get _bsontype() { + return "MaxKey"; } - returnType() { - return this._def.returns; + toExtendedJSON() { + return { $maxKey: 1 }; } - args(...items) { - return new ZodFunction3({ - ...this._def, - args: ZodTuple4.create(items).rest(ZodUnknown4.create()) - }); + static fromExtendedJSON() { + return new MaxKey; } - returns(returnType) { - return new ZodFunction3({ - ...this._def, - returns: returnType - }); + inspect() { + return "new MaxKey()"; } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + } + + class MinKey extends BSONValue { + get _bsontype() { + return "MinKey"; } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + toExtendedJSON() { + return { $minKey: 1 }; } - static create(args, returns, params) { - return new ZodFunction3({ - args: args ? args : ZodTuple4.create([]).rest(ZodUnknown4.create()), - returns: returns || ZodUnknown4.create(), - typeName: ZodFirstPartyTypeKind3.ZodFunction, - ...processCreateParams2(params) - }); + static fromExtendedJSON() { + return new MinKey; } - }; - ZodLazy4 = class ZodLazy4 extends ZodType4 { - get schema() { - return this._def.getter(); + inspect() { + return "new MinKey()"; } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + var PROCESS_UNIQUE = null; + var __idCache = new WeakMap; + + class ObjectId extends BSONValue { + get _bsontype() { + return "ObjectId"; } - }; - ZodLazy4.create = (getter, params) => { - return new ZodLazy4({ - getter, - typeName: ZodFirstPartyTypeKind3.ZodLazy, - ...processCreateParams2(params) - }); - }; - ZodLiteral4 = class ZodLiteral4 extends ZodType4 { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_literal, - expected: this._def.value - }); - return INVALID2; + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === "object" && inputId && "id" in inputId) { + if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError("Argument passed in must have an id that is of type string or Buffer"); + } + if ("toHexString" in inputId && typeof inputId.toHexString === "function") { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } else { + workingId = inputId.id; + } + } else { + workingId = inputId; + } + if (workingId == null || typeof workingId === "number") { + this.buffer = ObjectId.generate(typeof workingId === "number" ? workingId : undefined); + } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this.buffer = ByteUtils.toLocalBufferType(workingId); + } else if (typeof workingId === "string") { + if (ObjectId.validateHexString(workingId)) { + this.buffer = ByteUtils.fromHex(workingId); + if (ObjectId.cacheHexString) { + __idCache.set(this, workingId); + } + } else { + throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer"); + } + } else { + throw new BSONError("Argument passed in does not match the accepted types"); } - return { status: "valid", value: input.data }; } - get value() { - return this._def.value; + get id() { + return this.buffer; } - }; - ZodLiteral4.create = (value, params) => { - return new ZodLiteral4({ - value, - typeName: ZodFirstPartyTypeKind3.ZodLiteral, - ...processCreateParams2(params) - }); - }; - ZodEnum4 = class ZodEnum4 extends ZodType4 { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode4.invalid_type - }); - return INVALID2; + set id(value) { + this.buffer = value; + if (ObjectId.cacheHexString) { + __idCache.set(this, ByteUtils.toHex(value)); } - if (!this._cache) { - this._cache = new Set(this._def.values); + } + static validateHexString(string7) { + if (string7?.length !== 24) + return false; + for (let i2 = 0;i2 < 24; i2++) { + const char = string7.charCodeAt(i2); + if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) { + continue; + } + return false; } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_enum_value, - options: expectedValues - }); - return INVALID2; + return true; + } + toHexString() { + if (ObjectId.cacheHexString) { + const __id = __idCache.get(this); + if (__id) + return __id; } - return OK2(input.data); + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString) { + __idCache.set(this, hexString); + } + return hexString; } - get options() { - return this._def.values; + static getInc() { + return ObjectId.index = (ObjectId.index + 1) % 16777215; } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + static generate(time6) { + if (typeof time6 !== "number") { + time6 = Math.floor(Date.now() / 1000); } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + const inc = ObjectId.getInc(); + const buffer2 = ByteUtils.allocateUnsafe(12); + NumberUtils.setInt32BE(buffer2, 0, time6); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); } - return enumValues; + buffer2[4] = PROCESS_UNIQUE[0]; + buffer2[5] = PROCESS_UNIQUE[1]; + buffer2[6] = PROCESS_UNIQUE[2]; + buffer2[7] = PROCESS_UNIQUE[3]; + buffer2[8] = PROCESS_UNIQUE[4]; + buffer2[11] = inc & 255; + buffer2[10] = inc >> 8 & 255; + buffer2[9] = inc >> 16 & 255; + return buffer2; } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; + toString(encoding) { + if (encoding === "base64") + return ByteUtils.toBase64(this.id); + if (encoding === "hex") + return this.toHexString(); + return this.toHexString(); } - extract(values2, newDef = this._def) { - return ZodEnum4.create(values2, { - ...this._def, - ...newDef - }); + toJSON() { + return this.toHexString(); } - exclude(values2, newDef = this._def) { - return ZodEnum4.create(this.options.filter((opt) => !values2.includes(opt)), { - ...this._def, - ...newDef - }); + static is(variable) { + return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId"; } - }; - ZodEnum4.create = createZodEnum2; - ZodNativeEnum2 = class ZodNativeEnum2 extends ZodType4 { - _parse(input) { - const nativeEnumValues = util3.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - expected: util3.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode4.invalid_type - }); - return INVALID2; + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; } - if (!this._cache) { - this._cache = new Set(util3.getValidEnumValues(this._def.values)); + if (ObjectId.is(otherId)) { + return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer); } - if (!this._cache.has(input.data)) { - const expectedValues = util3.objectValues(nativeEnumValues); - addIssueToContext2(ctx, { - received: ctx.data, - code: ZodIssueCode4.invalid_enum_value, - options: expectedValues - }); - return INVALID2; + if (typeof otherId === "string") { + return otherId.toLowerCase() === this.toHexString(); } - return OK2(input.data); + if (typeof otherId === "object" && typeof otherId.toHexString === "function") { + const otherIdString = otherId.toHexString(); + const thisIdString = this.toHexString(); + return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString; + } + return false; } - get enum() { - return this._def.values; + getTimestamp() { + const timestamp = new Date; + const time6 = NumberUtils.getUint32BE(this.buffer, 0); + timestamp.setTime(Math.floor(time6) * 1000); + return timestamp; } - }; - ZodNativeEnum2.create = (values2, params) => { - return new ZodNativeEnum2({ - values: values2, - typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, - ...processCreateParams2(params) - }); - }; - ZodPromise4 = class ZodPromise4 extends ZodType4 { - unwrap() { - return this._def.type; + static createPk() { + return new ObjectId; } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.promise, - received: ctx.parsedType - }); - return INVALID2; + serializeInto(uint8array, index2) { + uint8array[index2] = this.buffer[0]; + uint8array[index2 + 1] = this.buffer[1]; + uint8array[index2 + 2] = this.buffer[2]; + uint8array[index2 + 3] = this.buffer[3]; + uint8array[index2 + 4] = this.buffer[4]; + uint8array[index2 + 5] = this.buffer[5]; + uint8array[index2 + 6] = this.buffer[6]; + uint8array[index2 + 7] = this.buffer[7]; + uint8array[index2 + 8] = this.buffer[8]; + uint8array[index2 + 9] = this.buffer[9]; + uint8array[index2 + 10] = this.buffer[10]; + uint8array[index2 + 11] = this.buffer[11]; + return 12; + } + static createFromTime(time6) { + const buffer2 = ByteUtils.allocate(12); + for (let i2 = 11;i2 >= 4; i2--) + buffer2[i2] = 0; + NumberUtils.setInt32BE(buffer2, 0, time6); + return new ObjectId(buffer2); + } + static createFromHexString(hexString) { + if (hexString?.length !== 24) { + throw new BSONError("hex string must be 24 characters"); } - const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); - return OK2(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); + return new ObjectId(ByteUtils.fromHex(hexString)); } - }; - ZodPromise4.create = (schema, params) => { - return new ZodPromise4({ - type: schema, - typeName: ZodFirstPartyTypeKind3.ZodPromise, - ...processCreateParams2(params) - }); - }; - ZodEffects2 = class ZodEffects2 extends ZodType4 { - innerType() { - return this._def.schema; + static createFromBase64(base647) { + if (base647?.length !== 16) { + throw new BSONError("base64 string must be 16 characters"); + } + return new ObjectId(ByteUtils.fromBase64(base647)); } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + static isValid(id) { + if (id == null) + return false; + if (typeof id === "string") + return ObjectId.validateHexString(id); + try { + new ObjectId(id); + return true; + } catch { + return false; + } } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext2(ctx, arg); - if (arg.fatal) { - status.abort(); + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString("hex") }; + } + static fromExtendedJSON(doc3) { + return new ObjectId(doc3.$oid); + } + isCached() { + return ObjectId.cacheHexString && __idCache.has(this); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new ObjectId(${inspect(this.toHexString(), options)})`; + } + } + ObjectId.index = Math.floor(Math.random() * 16777215); + function internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined) { + let totalLength = 4 + 1; + if (Array.isArray(object3)) { + for (let i2 = 0;i2 < object3.length; i2++) { + totalLength += calculateElement(i2.toString(), object3[i2], serializeFunctions, true, ignoreUndefined); + } + } else { + if (typeof object3?.toBSON === "function") { + object3 = object3.toBSON(); + } + for (const key of Object.keys(object3)) { + totalLength += calculateElement(key, object3[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; + } + function calculateElement(name, value, serializeFunctions = false, isArray3 = false, ignoreUndefined = false) { + if (typeof value?.toBSON === "function") { + value = value.toBSON(); + } + switch (typeof value) { + case "string": + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case "number": + if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); } else { - status.dirty(); + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID2; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; - }); } else { - if (status.value === "aborted") - return INVALID2; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID2; - if (result.status === "dirty") - return DIRTY2(result.value); - if (status.value === "dirty") - return DIRTY2(result.value); - return result; + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); + case "undefined": + if (isArray3 || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case "boolean": + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case "object": + if (value != null && typeof value._bsontype === "string" && value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError; + } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } else if (value._bsontype === "ObjectId") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength; + } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if (value._bsontype === "Decimal128") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } else if (value._bsontype === "Code") { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1 + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1; + } + } else if (value._bsontype === "Binary") { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1); } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } else if (value._bsontype === "Symbol") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1; + } else if (value._bsontype === "DBRef") { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values["$db"] = value.db; } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || isRegExp(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value._bsontype === "BSONRegExp") { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1; } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID2; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case "function": + if (serializeFunctions) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1; + } + return 0; + case "bigint": + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + case "symbol": + return 0; + default: + throw new BSONError(`Unrecognized JS type: ${typeof value}`); + } + } + function alphabetize(str) { + return str.split("").sort().join(""); + } + + class BSONRegExp extends BSONValue { + get _bsontype() { + return "BSONRegExp"; + } + constructor(pattern, options) { + super(); + this.pattern = pattern; + this.options = alphabetize(options ?? ""); + if (this.pattern.indexOf("\x00") !== -1) { + throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); + } + if (this.options.indexOf("\x00") !== -1) { + throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); + } + for (let i2 = 0;i2 < this.options.length; i2++) { + if (!(this.options[i2] === "i" || this.options[i2] === "m" || this.options[i2] === "x" || this.options[i2] === "l" || this.options[i2] === "s" || this.options[i2] === "u")) { + throw new BSONError(`The regular expression option [${this.options[i2]}] is not supported`); } } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid2(base)) - return INVALID2; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + static parseOptions(options) { + return options ? options.split("").sort().join("") : ""; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc3) { + if ("$regex" in doc3) { + if (typeof doc3.$regex !== "string") { + if (doc3.$regex._bsontype === "BSONRegExp") { + return doc3; } - return { status: status.value, value: result }; } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid2(base)) - return INVALID2; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); + return new BSONRegExp(doc3.$regex, BSONRegExp.parseOptions(doc3.$options)); } } - util3.assertNever(effect); - } - }; - ZodEffects2.create = (schema, effect, params) => { - return new ZodEffects2({ - schema, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - effect, - ...processCreateParams2(params) - }); - }; - ZodEffects2.createWithPreprocess = (preprocess3, schema, params) => { - return new ZodEffects2({ - schema, - effect: { type: "preprocess", transform: preprocess3 }, - typeName: ZodFirstPartyTypeKind3.ZodEffects, - ...processCreateParams2(params) - }); - }; - ZodOptional4 = class ZodOptional4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 === ZodParsedType2.undefined) { - return OK2(undefined); + if ("$regularExpression" in doc3) { + return new BSONRegExp(doc3.$regularExpression.pattern, BSONRegExp.parseOptions(doc3.$regularExpression.options)); } - return this._def.innerType._parse(input); + throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc3)}`); } - unwrap() { - return this._def.innerType; + inspect(depth, options, inspect) { + const stylize = getStylizeFunction(options) ?? ((v) => v); + inspect ??= defaultInspect; + const pattern = stylize(inspect(this.pattern), "regexp"); + const flags = stylize(inspect(this.options), "regexp"); + return `new BSONRegExp(${pattern}, ${flags})`; } - }; - ZodOptional4.create = (type, params) => { - return new ZodOptional4({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodOptional, - ...processCreateParams2(params) - }); - }; - ZodNullable4 = class ZodNullable4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 === ZodParsedType2.null) { - return OK2(null); - } - return this._def.innerType._parse(input); + } + + class BSONSymbol extends BSONValue { + get _bsontype() { + return "BSONSymbol"; } - unwrap() { - return this._def.innerType; + constructor(value) { + super(); + this.value = value; } - }; - ZodNullable4.create = (type, params) => { - return new ZodNullable4({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodNullable, - ...processCreateParams2(params) - }); - }; - ZodDefault4 = class ZodDefault4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType2.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); + valueOf() { + return this.value; } - removeDefault() { - return this._def.innerType; + toString() { + return this.value; } - }; - ZodDefault4.create = (type, params) => { - return new ZodDefault4({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams2(params) - }); - }; - ZodCatch4 = class ZodCatch4 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc3) { + return new BSONSymbol(doc3.$symbol); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + return `new BSONSymbol(${inspect(this.value, options)})`; + } + } + var LongWithoutOverridesClass = Long; + + class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return "Timestamp"; + } + get i() { + return this.low >>> 0; + } + get t() { + return this.high >>> 0; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } else if (typeof low === "bigint") { + super(low, true); + } else if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (typeof low === "object" && "t" in low && "i" in low) { + if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) { + throw new BSONError("Timestamp constructed from { t, i } must provide t as a number"); } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx + if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) { + throw new BSONError("Timestamp constructed from { t, i } must provide i as a number"); } - }); - if (isAsync2(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError5(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); + const t2 = Number(low.t); + const i2 = Number(low.i); + if (t2 < 0 || Number.isNaN(t2)) { + throw new BSONError("Timestamp constructed from { t, i } must provide a positive t"); + } + if (i2 < 0 || Number.isNaN(i2)) { + throw new BSONError("Timestamp constructed from { t, i } must provide a positive i"); + } + if (t2 > 4294967295) { + throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max"); + } + if (i2 > 4294967295) { + throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max"); + } + super(i2, t2, true); } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError5(newCtx.common.issues); - }, - input: newCtx.data - }) - }; + throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }"); } } - removeCatch() { - return this._def.innerType; + toJSON() { + return { + $timestamp: this.toString() + }; } - }; - ZodCatch4.create = (type, params) => { - return new ZodCatch4({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams2(params) - }); - }; - ZodNaN4 = class ZodNaN4 extends ZodType4 { - _parse(input) { - const parsedType5 = this._getType(input); - if (parsedType5 !== ZodParsedType2.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext2(ctx, { - code: ZodIssueCode4.invalid_type, - expected: ZodParsedType2.nan, - received: ctx.parsedType - }); - return INVALID2; - } - return { status: "valid", value: input.data }; + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); } - }; - ZodNaN4.create = (params) => { - return new ZodNaN4({ - typeName: ZodFirstPartyTypeKind3.ZodNaN, - ...processCreateParams2(params) - }); - }; - BRAND2 = Symbol("zod_brand"); - ZodBranded2 = class ZodBranded2 extends ZodType4 { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.t, i: this.i } }; + } + static fromExtendedJSON(doc3) { + const i2 = Long.isLong(doc3.$timestamp.i) ? doc3.$timestamp.i.getLowBitsUnsigned() : doc3.$timestamp.i; + const t2 = Long.isLong(doc3.$timestamp.t) ? doc3.$timestamp.t.getLowBitsUnsigned() : doc3.$timestamp.t; + return new Timestamp({ t: t2, i: i2 }); + } + inspect(depth, options, inspect) { + inspect ??= defaultInspect; + const t2 = inspect(this.t, options); + const i2 = inspect(this.i, options); + return `new Timestamp({ t: ${t2}, i: ${i2} })`; + } + } + Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); + var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); + function internalDeserialize(buffer2, options, isArray3) { + options = options == null ? {} : options; + const index2 = options && options.index ? options.index : 0; + const size = NumberUtils.getInt32LE(buffer2, index2); + if (size < 5) { + throw new BSONError(`bson size must be >= 5, is ${size}`); + } + if (options.allowObjectSmallerThanBufferSize && buffer2.length < size) { + throw new BSONError(`buffer length ${buffer2.length} must be >= bson size ${size}`); + } + if (!options.allowObjectSmallerThanBufferSize && buffer2.length !== size) { + throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`); + } + if (size + index2 > buffer2.byteLength) { + throw new BSONError(`(bson size ${size} + options.index ${index2} must be <= buffer length ${buffer2.byteLength})`); + } + if (buffer2[index2 + size - 1] !== 0) { + throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + return deserializeObject(buffer2, index2, options, isArray3); + } + var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + function deserializeObject(buffer2, index2, options, isArray3 = false) { + const fieldsAsRaw = options["fieldsAsRaw"] == null ? null : options["fieldsAsRaw"]; + const raw2 = options["raw"] == null ? false : options["raw"]; + const bsonRegExp = typeof options["bsonRegExp"] === "boolean" ? options["bsonRegExp"] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError("Must either request bigint or Long for int64 deserialization"); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError("Must either request bigint or Long for int64 deserialization"); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + let utf8KeysSet; + const utf8ValidatedKeys = validation.utf8; + if (typeof utf8ValidatedKeys === "boolean") { + validationSetting = utf8ValidatedKeys; + } else { + globalUTFValidation = false; + const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function(key) { + return utf8ValidatedKeys[key]; }); + if (utf8ValidationValues.length === 0) { + throw new BSONError("UTF-8 validation setting cannot be empty"); + } + if (typeof utf8ValidationValues[0] !== "boolean") { + throw new BSONError("Invalid UTF-8 validation option, must specify boolean values"); + } + validationSetting = utf8ValidationValues[0]; + if (!utf8ValidationValues.every((item) => item === validationSetting)) { + throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false"); + } } - unwrap() { - return this._def.type; + if (!globalUTFValidation) { + utf8KeysSet = new Set; + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } } - }; - ZodPipeline2 = class ZodPipeline2 extends ZodType4 { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY2(inResult.value); + const startIndex = index2; + if (buffer2.length < 5) + throw new BSONError("corrupt bson message < 5 bytes long"); + const size = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (size < 5 || size > buffer2.length) + throw new BSONError("corrupt bson message"); + const object3 = isArray3 ? [] : {}; + let arrayIndex = 0; + let isPossibleDBRef = isArray3 ? false : null; + while (true) { + const elementType = buffer2[index2++]; + if (elementType === 0) + break; + let i2 = index2; + while (buffer2[i2] !== 0 && i2 < buffer2.length) { + i2++; + } + if (i2 >= buffer2.byteLength) + throw new BSONError("Bad BSON Document: illegal CString"); + const name = isArray3 ? arrayIndex++ : ByteUtils.toUTF8(buffer2, index2, i2, false); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet?.has(name)) { + shouldValidateKey = validationSetting; + } else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === "$") { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index2 = i2 + 1; + if (elementType === BSON_DATA_STRING) { + const stringSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { + throw new BSONError("bad string length in bson"); + } + value = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); + index2 = index2 + stringSize; + } else if (elementType === BSON_DATA_OID) { + const oid = ByteUtils.allocateUnsafe(12); + for (let i3 = 0;i3 < 12; i3++) + oid[i3] = buffer2[index2 + i3]; + value = new ObjectId(oid); + index2 = index2 + 12; + } else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(NumberUtils.getInt32LE(buffer2, index2)); + index2 += 4; + } else if (elementType === BSON_DATA_INT) { + value = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + } else if (elementType === BSON_DATA_NUMBER) { + value = NumberUtils.getFloat64LE(buffer2, index2); + index2 += 8; + if (promoteValues === false) + value = new Double(value); + } else if (elementType === BSON_DATA_DATE) { + const lowBits = NumberUtils.getInt32LE(buffer2, index2); + const highBits = NumberUtils.getInt32LE(buffer2, index2 + 4); + index2 += 8; + value = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON_DATA_BOOLEAN) { + if (buffer2[index2] !== 0 && buffer2[index2] !== 1) + throw new BSONError("illegal boolean type value"); + value = buffer2[index2++] === 1; + } else if (elementType === BSON_DATA_OBJECT) { + const _index = index2; + const objectSize = NumberUtils.getInt32LE(buffer2, index2); + if (objectSize <= 0 || objectSize > buffer2.length - index2) + throw new BSONError("bad embedded document length in bson"); + if (raw2) { + value = buffer2.subarray(index2, index2 + objectSize); + } else { + let objectOptions = options; + if (!globalUTFValidation) { + objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer2, _index, objectOptions, false); + } + index2 = index2 + objectSize; + } else if (elementType === BSON_DATA_ARRAY) { + const _index = index2; + const objectSize = NumberUtils.getInt32LE(buffer2, index2); + let arrayOptions = options; + const stopIndex = index2 + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, raw: true }; + } + if (!globalUTFValidation) { + arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; + } + value = deserializeObject(buffer2, _index, arrayOptions, true); + index2 = index2 + objectSize; + if (buffer2[index2 - 1] !== 0) + throw new BSONError("invalid array terminator byte"); + if (index2 !== stopIndex) + throw new BSONError("corrupted array bson"); + } else if (elementType === BSON_DATA_UNDEFINED) { + value = undefined; + } else if (elementType === BSON_DATA_NULL) { + value = null; + } else if (elementType === BSON_DATA_LONG) { + if (useBigInt64) { + value = NumberUtils.getBigInt64LE(buffer2, index2); + index2 += 8; + } else { + const lowBits = NumberUtils.getInt32LE(buffer2, index2); + const highBits = NumberUtils.getInt32LE(buffer2, index2 + 4); + index2 += 8; + const long = new Long(lowBits, highBits); + if (promoteLongs && promoteValues === true) { + value = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); + value = long; } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID2; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; + } + } else if (elementType === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocateUnsafe(16); + for (let i3 = 0;i3 < 16; i3++) + bytes[i3] = buffer2[index2 + i3]; + index2 = index2 + 16; + value = new Decimal128(bytes); + } else if (elementType === BSON_DATA_BINARY) { + let binarySize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + const totalBinarySize = binarySize; + const subType = buffer2[index2++]; + if (binarySize < 0) + throw new BSONError("Negative binary type element size found"); + if (binarySize > buffer2.byteLength) + throw new BSONError("Binary type size larger than document size"); + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (binarySize < 0) + throw new BSONError("Negative binary type element size found for subtype 0x02"); + if (binarySize > totalBinarySize - 4) + throw new BSONError("Binary type with subtype 0x02 contains too long binary size"); + if (binarySize < totalBinarySize - 4) + throw new BSONError("Binary type with subtype 0x02 contains too short binary size"); + } + if (promoteBuffers && promoteValues) { + value = ByteUtils.toLocalBufferType(buffer2.subarray(index2, index2 + binarySize)); } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); + value = new Binary(buffer2.subarray(index2, index2 + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID2.isValid(value)) { + value = value.toUUID(); + } } - } - } - static create(a, b) { - return new ZodPipeline2({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind3.ZodPipeline - }); - } - }; - ZodReadonly4 = class ZodReadonly4 extends ZodType4 { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid2(data)) { - data.value = Object.freeze(data.value); + index2 = index2 + binarySize; + } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i2 = index2; + while (buffer2[i2] !== 0 && i2 < buffer2.length) { + i2++; } - return data; - }; - return isAsync2(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } - }; - ZodReadonly4.create = (type, params) => { - return new ZodReadonly4({ - innerType: type, - typeName: ZodFirstPartyTypeKind3.ZodReadonly, - ...processCreateParams2(params) - }); - }; - late2 = { - object: ZodObject4.lazycreate - }; - (function(ZodFirstPartyTypeKind4) { - ZodFirstPartyTypeKind4["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind4["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind4["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind4["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind4["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind4["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind4["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind4["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind4["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind4["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind4["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind4["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind4["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind4["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind4["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind4["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind4["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind4["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind4["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind4["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind4["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind4["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind4["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind4["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind4["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind4["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind4["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind4["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind4["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind4["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind4["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind4["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind4["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind4["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind4["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind4["ZodReadonly"] = "ZodReadonly"; - })(ZodFirstPartyTypeKind3 || (ZodFirstPartyTypeKind3 = {})); - stringType2 = ZodString4.create; - numberType2 = ZodNumber4.create; - nanType2 = ZodNaN4.create; - bigIntType2 = ZodBigInt4.create; - booleanType2 = ZodBoolean4.create; - dateType2 = ZodDate4.create; - symbolType2 = ZodSymbol4.create; - undefinedType2 = ZodUndefined4.create; - nullType2 = ZodNull4.create; - anyType2 = ZodAny4.create; - unknownType2 = ZodUnknown4.create; - neverType2 = ZodNever4.create; - voidType2 = ZodVoid4.create; - arrayType2 = ZodArray4.create; - objectType2 = ZodObject4.create; - strictObjectType2 = ZodObject4.strictCreate; - unionType2 = ZodUnion4.create; - discriminatedUnionType2 = ZodDiscriminatedUnion4.create; - intersectionType2 = ZodIntersection4.create; - tupleType2 = ZodTuple4.create; - recordType2 = ZodRecord4.create; - mapType2 = ZodMap4.create; - setType2 = ZodSet4.create; - functionType2 = ZodFunction3.create; - lazyType2 = ZodLazy4.create; - literalType2 = ZodLiteral4.create; - enumType2 = ZodEnum4.create; - nativeEnumType2 = ZodNativeEnum2.create; - promiseType2 = ZodPromise4.create; - effectsType2 = ZodEffects2.create; - optionalType2 = ZodOptional4.create; - nullableType2 = ZodNullable4.create; - preprocessType2 = ZodEffects2.createWithPreprocess; - pipelineType2 = ZodPipeline2.create; - coerce2 = { - string: (arg) => ZodString4.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber4.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean4.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt4.create({ ...arg, coerce: true }), - date: (arg) => ZodDate4.create({ ...arg, coerce: true }) - }; - NEVER4 = INVALID2; -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js -var exports_external4 = {}; -__export(exports_external4, { - void: () => voidType2, - util: () => util3, - unknown: () => unknownType2, - union: () => unionType2, - undefined: () => undefinedType2, - tuple: () => tupleType2, - transformer: () => effectsType2, - symbol: () => symbolType2, - string: () => stringType2, - strictObject: () => strictObjectType2, - setErrorMap: () => setErrorMap4, - set: () => setType2, - record: () => recordType2, - quotelessJson: () => quotelessJson2, - promise: () => promiseType2, - preprocess: () => preprocessType2, - pipeline: () => pipelineType2, - ostring: () => ostring2, - optional: () => optionalType2, - onumber: () => onumber2, - oboolean: () => oboolean2, - objectUtil: () => objectUtil2, - object: () => objectType2, - number: () => numberType2, - nullable: () => nullableType2, - null: () => nullType2, - never: () => neverType2, - nativeEnum: () => nativeEnumType2, - nan: () => nanType2, - map: () => mapType2, - makeIssue: () => makeIssue2, - literal: () => literalType2, - lazy: () => lazyType2, - late: () => late2, - isValid: () => isValid2, - isDirty: () => isDirty2, - isAsync: () => isAsync2, - isAborted: () => isAborted2, - intersection: () => intersectionType2, - instanceof: () => instanceOfType2, - getParsedType: () => getParsedType4, - getErrorMap: () => getErrorMap4, - function: () => functionType2, - enum: () => enumType2, - effect: () => effectsType2, - discriminatedUnion: () => discriminatedUnionType2, - defaultErrorMap: () => en_default4, - datetimeRegex: () => datetimeRegex2, - date: () => dateType2, - custom: () => custom4, - coerce: () => coerce2, - boolean: () => booleanType2, - bigint: () => bigIntType2, - array: () => arrayType2, - any: () => anyType2, - addIssueToContext: () => addIssueToContext2, - ZodVoid: () => ZodVoid4, - ZodUnknown: () => ZodUnknown4, - ZodUnion: () => ZodUnion4, - ZodUndefined: () => ZodUndefined4, - ZodType: () => ZodType4, - ZodTuple: () => ZodTuple4, - ZodTransformer: () => ZodEffects2, - ZodSymbol: () => ZodSymbol4, - ZodString: () => ZodString4, - ZodSet: () => ZodSet4, - ZodSchema: () => ZodType4, - ZodRecord: () => ZodRecord4, - ZodReadonly: () => ZodReadonly4, - ZodPromise: () => ZodPromise4, - ZodPipeline: () => ZodPipeline2, - ZodParsedType: () => ZodParsedType2, - ZodOptional: () => ZodOptional4, - ZodObject: () => ZodObject4, - ZodNumber: () => ZodNumber4, - ZodNullable: () => ZodNullable4, - ZodNull: () => ZodNull4, - ZodNever: () => ZodNever4, - ZodNativeEnum: () => ZodNativeEnum2, - ZodNaN: () => ZodNaN4, - ZodMap: () => ZodMap4, - ZodLiteral: () => ZodLiteral4, - ZodLazy: () => ZodLazy4, - ZodIssueCode: () => ZodIssueCode4, - ZodIntersection: () => ZodIntersection4, - ZodFunction: () => ZodFunction3, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind3, - ZodError: () => ZodError5, - ZodEnum: () => ZodEnum4, - ZodEffects: () => ZodEffects2, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion4, - ZodDefault: () => ZodDefault4, - ZodDate: () => ZodDate4, - ZodCatch: () => ZodCatch4, - ZodBranded: () => ZodBranded2, - ZodBoolean: () => ZodBoolean4, - ZodBigInt: () => ZodBigInt4, - ZodArray: () => ZodArray4, - ZodAny: () => ZodAny4, - Schema: () => ZodType4, - ParseStatus: () => ParseStatus2, - OK: () => OK2, - NEVER: () => NEVER4, - INVALID: () => INVALID2, - EMPTY_PATH: () => EMPTY_PATH2, - DIRTY: () => DIRTY2, - BRAND: () => BRAND2 -}); -var init_external4 = __esm(() => { - init_errors13(); - init_parseUtil2(); - init_typeAliases2(); - init_util4(); - init_types16(); - init_ZodError2(); -}); - -// ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/index.js -var init_v32 = __esm(() => { - init_external4(); - init_external4(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/messages_annotation.js -var MessagesAnnotation2, MessagesZodMeta2, MessagesZodState2; -var init_messages_annotation2 = __esm(() => { - init_annotation3(); - init_messages_reducer2(); - init_meta2(); - init_v32(); - MessagesAnnotation2 = Annotation2.Root({ messages: Annotation2({ - reducer: messagesStateReducer2, - default: () => [] - }) }); - MessagesZodMeta2 = { - reducer: { fn: messagesStateReducer2 }, - jsonSchemaExtra: { langgraph_type: "messages" }, - default: () => [] - }; - MessagesZodState2 = exports_external4.object({ messages: withLangGraph2(exports_external4.custom(), MessagesZodMeta2) }); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/writer.js -function writer2(chunk) { - const config3 = AsyncLocalStorageProviderSingleton2.getRunnableConfig(); - if (!config3) - throw new Error("Called interrupt() outside the context of a graph."); - const conf = config3.configurable; - if (!conf) - throw new Error("No configurable found in config"); - return conf.writer?.(chunk); -} -var init_writer2 = __esm(() => { - init_singletons(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/graph/index.js -var init_graph5 = __esm(() => { - init_constants8(); - init_annotation3(); - init_graph4(); - init_messages_reducer2(); - init_state4(); - init_message3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/web.js -var init_web2 = __esm(() => { - init_constants8(); - init_errors10(); - init_base17(); - init_binop2(); - init_annotation3(); - init_config3(); - init_stream_channel2(); - init_convert2(); - init_lifecycle2(); - init_messages10(); - init_subgraphs4(); - init_values5(); - init_types12(); - init_run_stream2(); - init_stream11(); - init_interrupt2(); - init_graph4(); - init_types14(); - init_adapter2(); - init_untracked_value2(); - init_channels2(); - init_reduced2(); - init_untracked2(); - init_schema2(); - init_messages_reducer2(); - init_messages12(); - init_state3(); - init_state4(); - init_message3(); - init_graph5(); - init_func2(); - init_messages_annotation2(); - init_writer2(); - init_dist3(); -}); - -// ../../node_modules/.pnpm/@langchain+langgraph@1.3.0_@langchain+core@1.1.46_@opentelemetry+api@1.9.1_@opentelemetry+sdk_jqdhkebu5murtdxdtzeh5jt22q/node_modules/@langchain/langgraph/dist/index.js -var exports_dist4 = {}; -__export(exports_dist4, { - writer: () => writer2, - task: () => task2, - pushMessage: () => pushMessage2, - messagesStateReducer: () => messagesStateReducer2, - isStandardSchema: () => isStandardSchema3, - isSerializableSchema: () => isSerializableSchema3, - isParentCommand: () => isParentCommand2, - isNativeTransformer: () => isNativeTransformer2, - isInterrupted: () => isInterrupted2, - isGraphInterrupt: () => isGraphInterrupt2, - isGraphBubbleUp: () => isGraphBubbleUp2, - isCommand: () => isCommand2, - interrupt: () => interrupt2, - getWriter: () => getWriter2, - getSubgraphsSeenSet: () => getSubgraphsSeenSet2, - getStore: () => getStore2, - getSchemaDefaultGetter: () => getSchemaDefaultGetter2, - getPreviousState: () => getPreviousState2, - getJsonSchemaFromSchema: () => getJsonSchemaFromSchema2, - getCurrentTaskInput: () => getCurrentTaskInput2, - getConfig: () => getConfig2, - filterSubgraphHandles: () => filterSubgraphHandles2, - filterLifecycleEntries: () => filterLifecycleEntries2, - entrypoint: () => entrypoint3, - emptyCheckpoint: () => emptyCheckpoint, - createValuesTransformer: () => createValuesTransformer2, - createSubgraphDiscoveryTransformer: () => createSubgraphDiscoveryTransformer2, - createMessagesTransformer: () => createMessagesTransformer2, - createLifecycleTransformer: () => createLifecycleTransformer2, - createGraphRunStream: () => createGraphRunStream2, - copyCheckpoint: () => copyCheckpoint, - convertToProtocolEvent: () => convertToProtocolEvent2, - addMessages: () => messagesStateReducer2, - UntrackedValueChannel: () => UntrackedValueChannel3, - UntrackedValue: () => UntrackedValue2, - UnreachableNodeError: () => UnreachableNodeError2, - SubgraphRunStream: () => SubgraphRunStream2, - StreamChannel: () => StreamChannel3, - StateSchema: () => StateSchema2, - StateGraphInputError: () => StateGraphInputError2, - StateGraph: () => StateGraph2, - Send: () => Send2, - STREAM_EVENTS_V3_MODES: () => STREAM_EVENTS_V3_MODES2, - START: () => START2, - RemoteException: () => RemoteException2, - ReducedValue: () => ReducedValue2, - REMOVE_ALL_MESSAGES: () => REMOVE_ALL_MESSAGES2, - ParentCommand: () => ParentCommand2, - Overwrite: () => Overwrite2, - NodeInterrupt: () => NodeInterrupt2, - MultipleSubgraphsError: () => MultipleSubgraphsError2, - MessagesZodState: () => MessagesZodState2, - MessagesZodMeta: () => MessagesZodMeta2, - MessagesValue: () => MessagesValue2, - MessagesAnnotation: () => MessagesAnnotation2, - MessageGraph: () => MessageGraph2, - MemorySaver: () => MemorySaver, - InvalidUpdateError: () => InvalidUpdateError2, - InMemoryStore: () => InMemoryStore2, - INTERRUPT: () => INTERRUPT3, - GraphValueError: () => GraphValueError2, - GraphRunStream: () => GraphRunStream2, - GraphRecursionError: () => GraphRecursionError2, - GraphInterrupt: () => GraphInterrupt2, - GraphBubbleUp: () => GraphBubbleUp2, - Graph: () => Graph$12, - EventLog: () => StreamChannel3, - EmptyInputError: () => EmptyInputError2, - EmptyChannelError: () => EmptyChannelError2, - END: () => END2, - CompiledStateGraph: () => CompiledStateGraph2, - CommandInstance: () => CommandInstance2, - Command: () => Command2, - ChatModelStreamImpl: () => ChatModelStream, - COMMAND_SYMBOL: () => COMMAND_SYMBOL2, - BinaryOperatorAggregate: () => BinaryOperatorAggregate3, - BaseStore: () => BaseStore2, - BaseLangGraphError: () => BaseLangGraphError2, - BaseCheckpointSaver: () => BaseCheckpointSaver, - BaseChannel: () => BaseChannel2, - AsyncBatchedStore: () => AsyncBatchedStore, - Annotation: () => Annotation2 -}); -var init_dist10 = __esm(() => { - init_async_local_storage3(); - init_constants8(); - init_errors10(); - init_base17(); - init_binop2(); - init_annotation3(); - init_config3(); - init_stream_channel2(); - init_convert2(); - init_lifecycle2(); - init_messages10(); - init_subgraphs4(); - init_values5(); - init_types12(); - init_run_stream2(); - init_stream11(); - init_interrupt2(); - init_graph4(); - init_types14(); - init_adapter2(); - init_untracked_value2(); - init_reduced2(); - init_untracked2(); - init_schema2(); - init_messages_reducer2(); - init_messages12(); - init_state4(); - init_message3(); - init_func2(); - init_messages_annotation2(); - init_writer2(); - init_web2(); - initializeAsyncLocalStorageSingleton2(); -}); - -// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js -var require_ms = __commonJS((exports, module) => { - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse15(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); + if (i2 >= buffer2.length) + throw new BSONError("Bad BSON Document: illegal CString"); + const source = ByteUtils.toUTF8(buffer2, index2, i2, false); + index2 = i2 + 1; + i2 = index2; + while (buffer2[i2] !== 0 && i2 < buffer2.length) { + i2++; + } + if (i2 >= buffer2.length) + throw new BSONError("Bad BSON Document: illegal CString"); + const regExpOptions = ByteUtils.toUTF8(buffer2, index2, i2, false); + index2 = i2 + 1; + const optionsArray = new Array(regExpOptions.length); + for (i2 = 0;i2 < regExpOptions.length; i2++) { + switch (regExpOptions[i2]) { + case "m": + optionsArray[i2] = "m"; + break; + case "s": + optionsArray[i2] = "g"; + break; + case "i": + optionsArray[i2] = "i"; + break; + } + } + value = new RegExp(source, optionsArray.join("")); + } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { + i2 = index2; + while (buffer2[i2] !== 0 && i2 < buffer2.length) { + i2++; + } + if (i2 >= buffer2.length) + throw new BSONError("Bad BSON Document: illegal CString"); + const source = ByteUtils.toUTF8(buffer2, index2, i2, false); + index2 = i2 + 1; + i2 = index2; + while (buffer2[i2] !== 0 && i2 < buffer2.length) { + i2++; + } + if (i2 >= buffer2.length) + throw new BSONError("Bad BSON Document: illegal CString"); + const regExpOptions = ByteUtils.toUTF8(buffer2, index2, i2, false); + index2 = i2 + 1; + value = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON_DATA_SYMBOL) { + const stringSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { + throw new BSONError("bad string length in bson"); + } + const symbol3 = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); + value = promoteValues ? symbol3 : new BSONSymbol(symbol3); + index2 = index2 + stringSize; + } else if (elementType === BSON_DATA_TIMESTAMP) { + value = new Timestamp({ + i: NumberUtils.getUint32LE(buffer2, index2), + t: NumberUtils.getUint32LE(buffer2, index2 + 4) + }); + index2 += 8; + } else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey; + } else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey; + } else if (elementType === BSON_DATA_CODE) { + const stringSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { + throw new BSONError("bad string length in bson"); + } + const functionString = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); + value = new Code(functionString); + index2 = index2 + stringSize; + } else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError("code_w_scope total size shorter minimum expected length"); + } + const stringSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { + throw new BSONError("bad string length in bson"); + } + const functionString = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); + index2 = index2 + stringSize; + const _index = index2; + const objectSize = NumberUtils.getInt32LE(buffer2, index2); + const scopeObject = deserializeObject(buffer2, _index, options, false); + index2 = index2 + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError("code_w_scope total size is too short, truncating scope"); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError("code_w_scope total size is too long, clips outer document"); + } + value = new Code(functionString, scopeObject); + } else if (elementType === BSON_DATA_DBPOINTER) { + const stringSize = NumberUtils.getInt32LE(buffer2, index2); + index2 += 4; + if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) + throw new BSONError("bad string length in bson"); + const namespace = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); + index2 = index2 + stringSize; + const oidBuffer = ByteUtils.allocateUnsafe(12); + for (let i3 = 0;i3 < 12; i3++) + oidBuffer[i3] = buffer2[index2 + i3]; + const oid = new ObjectId(oidBuffer); + index2 = index2 + 12; + value = new DBRef(namespace, oid); + } else { + throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); + } + if (name === "__proto__") { + Object.defineProperty(object3, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } else { + object3[name] = value; + } } - throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); - }; - function parse15(str) { - str = String(str); - if (str.length > 100) { - return; + if (size !== index2 - startIndex) { + if (isArray3) + throw new BSONError("corrupt array bson"); + throw new BSONError("corrupt object bson"); } - var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); - if (!match2) { - return; + if (!isPossibleDBRef) + return object3; + if (isDBRefLike(object3)) { + const copy = Object.assign({}, object3); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object3.$ref, object3.$id, object3.$db, copy); } - var n4 = parseFloat(match2[1]); - var type = (match2[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n4 * y; - case "weeks": - case "week": - case "w": - return n4 * w; - case "days": - case "day": - case "d": - return n4 * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n4 * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n4 * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n4 * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n4; - default: - return; + return object3; + } + var regexp = /\x00/; + var ignoreKeys = new Set(["$db", "$ref", "$id", "$clusterTime"]); + function serializeString(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes + 1; + buffer2[index2 - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer2, value, index2 + 4); + NumberUtils.setInt32LE(buffer2, index2, size + 1); + index2 = index2 + 4 + size; + buffer2[index2++] = 0; + return index2; + } + function serializeNumber(buffer2, key, value, index2) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && Number.isSafeInteger(value) && value <= BSON_INT32_MAX && value >= BSON_INT32_MIN ? BSON_DATA_INT : BSON_DATA_NUMBER; + buffer2[index2++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + if (type === BSON_DATA_INT) { + index2 += NumberUtils.setInt32LE(buffer2, index2, value); + } else { + index2 += NumberUtils.setFloat64LE(buffer2, index2, value); } + return index2; } - function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + "d"; + function serializeBigInt(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 += numberOfWrittenBytes; + buffer2[index2++] = 0; + index2 += NumberUtils.setBigInt64LE(buffer2, index2, value); + return index2; + } + function serializeNull(buffer2, key, _2, index2) { + buffer2[index2++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + return index2; + } + function serializeBoolean(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + buffer2[index2++] = value ? 1 : 0; + return index2; + } + function serializeDate(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + index2 += NumberUtils.setInt32LE(buffer2, index2, lowBits); + index2 += NumberUtils.setInt32LE(buffer2, index2, highBits); + return index2; + } + function serializeRegExp(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError("value " + value.source + " must not contain null bytes"); } - if (msAbs >= h) { - return Math.round(ms / h) + "h"; + index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, value.source, index2); + buffer2[index2++] = 0; + if (value.ignoreCase) + buffer2[index2++] = 105; + if (value.global) + buffer2[index2++] = 115; + if (value.multiline) + buffer2[index2++] = 109; + buffer2[index2++] = 0; + return index2; + } + function serializeBSONRegExp(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError("pattern " + value.pattern + " must not contain null bytes"); } - if (msAbs >= m) { - return Math.round(ms / m) + "m"; + index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, value.pattern, index2); + buffer2[index2++] = 0; + const sortedOptions = value.options.split("").sort().join(""); + index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, sortedOptions, index2); + buffer2[index2++] = 0; + return index2; + } + function serializeMinMax(buffer2, key, value, index2) { + if (value === null) { + buffer2[index2++] = BSON_DATA_NULL; + } else if (value._bsontype === "MinKey") { + buffer2[index2++] = BSON_DATA_MIN_KEY; + } else { + buffer2[index2++] = BSON_DATA_MAX_KEY; } - if (msAbs >= s) { - return Math.round(ms / s) + "s"; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + return index2; + } + function serializeObjectId(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + index2 += value.serializeInto(buffer2, index2); + return index2; + } + function serializeBuffer(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const size = value.length; + index2 += NumberUtils.setInt32LE(buffer2, index2, size); + buffer2[index2++] = BSON_BINARY_SUBTYPE_DEFAULT; + if (size <= 16) { + for (let i2 = 0;i2 < size; i2++) + buffer2[index2 + i2] = value[i2]; + } else { + buffer2.set(value, index2); } - return ms + "ms"; + index2 = index2 + size; + return index2; } - function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, "day"); + function serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4) { + if (path4.has(value)) { + throw new BSONError("Cannot convert circular structure to BSON"); } - if (msAbs >= h) { - return plural(ms, msAbs, h, "hour"); + path4.add(value); + buffer2[index2++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const endIndex = serializeInto(buffer2, value, checkKeys, index2, depth + 1, serializeFunctions, ignoreUndefined, path4); + path4.delete(value); + return endIndex; + } + function serializeDecimal128(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + for (let i2 = 0;i2 < 16; i2++) + buffer2[index2 + i2] = value.bytes[i2]; + return index2 + 16; + } + function serializeLong(buffer2, key, value, index2) { + buffer2[index2++] = value._bsontype === "Long" ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + index2 += NumberUtils.setInt32LE(buffer2, index2, lowBits); + index2 += NumberUtils.setInt32LE(buffer2, index2, highBits); + return index2; + } + function serializeInt32(buffer2, key, value, index2) { + value = value.valueOf(); + buffer2[index2++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + index2 += NumberUtils.setInt32LE(buffer2, index2, value); + return index2; + } + function serializeDouble(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + index2 += NumberUtils.setFloat64LE(buffer2, index2, value.value); + return index2; + } + function serializeFunction(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; + NumberUtils.setInt32LE(buffer2, index2, size); + index2 = index2 + 4 + size - 1; + buffer2[index2++] = 0; + return index2; + } + function serializeCode(buffer2, key, value, index2, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path4) { + if (value.scope && typeof value.scope === "object") { + buffer2[index2++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + let startIndex = index2; + const functionString = value.code; + index2 = index2 + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; + NumberUtils.setInt32LE(buffer2, index2, codeSize); + buffer2[index2 + 4 + codeSize - 1] = 0; + index2 = index2 + codeSize + 4; + const endIndex = serializeInto(buffer2, value.scope, checkKeys, index2, depth + 1, serializeFunctions, ignoreUndefined, path4); + index2 = endIndex - 1; + const totalSize = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer2, startIndex, totalSize); + buffer2[index2++] = 0; + } else { + buffer2[index2++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; + NumberUtils.setInt32LE(buffer2, index2, size); + index2 = index2 + 4 + size - 1; + buffer2[index2++] = 0; } - if (msAbs >= m) { - return plural(ms, msAbs, m, "minute"); + return index2; + } + function serializeBinary(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const data = value.buffer; + let size = value.position; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) + size = size + 4; + index2 += NumberUtils.setInt32LE(buffer2, index2, size); + buffer2[index2++] = value.sub_type; + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + index2 += NumberUtils.setInt32LE(buffer2, index2, size); } - if (msAbs >= s) { - return plural(ms, msAbs, s, "second"); + if (value.sub_type === Binary.SUBTYPE_VECTOR) { + validateBinaryVector(value); } - return ms + " ms"; + if (size <= 16) { + for (let i2 = 0;i2 < size; i2++) + buffer2[index2 + i2] = data[i2]; + } else { + buffer2.set(data, index2); + } + index2 = index2 + value.position; + return index2; } - function plural(ms, msAbs, n4, name) { - var isPlural = msAbs >= n4 * 1.5; - return Math.round(ms / n4) + " " + name + (isPlural ? "s" : ""); + function serializeSymbol(buffer2, key, value, index2) { + buffer2[index2++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer2, value.value, index2 + 4) + 1; + NumberUtils.setInt32LE(buffer2, index2, size); + index2 = index2 + 4 + size - 1; + buffer2[index2++] = 0; + return index2; } -}); - -// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js -var require_common3 = __commonJS((exports, module) => { - function setup(env2) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce3; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require_ms(); - createDebug.destroy = destroy; - Object.keys(env2).forEach((key) => { - createDebug[key] = env2[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash2 = 0; - for (let i = 0;i < namespace.length; i++) { - hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); - hash2 |= 0; + function serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4) { + buffer2[index2++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); + index2 = index2 + numberOfWrittenBytes; + buffer2[index2++] = 0; + let startIndex = index2; + let output = { + $ref: value.collection || value.namespace, + $id: value.oid + }; + if (value.db != null) { + output.$db = value.db; + } + output = Object.assign(output, value.fields); + const endIndex = serializeInto(buffer2, output, false, index2, depth + 1, serializeFunctions, true, path4); + const size = endIndex - startIndex; + startIndex += NumberUtils.setInt32LE(buffer2, index2, size); + return endIndex; + } + function serializeInto(buffer2, object3, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path4) { + if (path4 == null) { + if (object3 == null) { + buffer2[0] = 5; + buffer2[1] = 0; + buffer2[2] = 0; + buffer2[3] = 0; + buffer2[4] = 0; + return 5; } - return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + if (Array.isArray(object3)) { + throw new BSONError("serialize does not support an array as the root input"); + } + if (typeof object3 !== "object") { + throw new BSONError("serialize does not support non-object as the root input"); + } else if ("_bsontype" in object3 && typeof object3._bsontype === "string") { + throw new BSONError(`BSON types cannot be serialized as a document`); + } else if (isDate(object3) || isRegExp(object3) || isUint8Array(object3) || isAnyArrayBuffer(object3)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path4 = new Set; } - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug(...args) { - if (!debug.enabled) { - return; + path4.add(object3); + let index2 = startingIndex + 4; + if (Array.isArray(object3)) { + for (let i2 = 0;i2 < object3.length; i2++) { + const key = `${i2}`; + let value = object3[i2]; + if (typeof value?.toBSON === "function") { + value = value.toBSON(); } - const self2 = debug; - const curr = Number(new Date); - const ms = curr - (prevTime || curr); - self2.diff = ms; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); + const type = typeof value; + if (value === undefined) { + index2 = serializeNull(buffer2, key, value, index2); + } else if (value === null) { + index2 = serializeNull(buffer2, key, value, index2); + } else if (type === "string") { + index2 = serializeString(buffer2, key, value, index2); + } else if (type === "number") { + index2 = serializeNumber(buffer2, key, value, index2); + } else if (type === "bigint") { + index2 = serializeBigInt(buffer2, key, value, index2); + } else if (type === "boolean") { + index2 = serializeBoolean(buffer2, key, value, index2); + } else if (type === "object" && value._bsontype == null) { + if (value instanceof Date || isDate(value)) { + index2 = serializeDate(buffer2, key, value, index2); + } else if (value instanceof Uint8Array || isUint8Array(value)) { + index2 = serializeBuffer(buffer2, key, value, index2); + } else if (value instanceof RegExp || isRegExp(value)) { + index2 = serializeRegExp(buffer2, key, value, index2); + } else { + index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } + } else if (type === "object") { + if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError; + } else if (value._bsontype === "ObjectId") { + index2 = serializeObjectId(buffer2, key, value, index2); + } else if (value._bsontype === "Decimal128") { + index2 = serializeDecimal128(buffer2, key, value, index2); + } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { + index2 = serializeLong(buffer2, key, value, index2); + } else if (value._bsontype === "Double") { + index2 = serializeDouble(buffer2, key, value, index2); + } else if (value._bsontype === "Code") { + index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } else if (value._bsontype === "Binary") { + index2 = serializeBinary(buffer2, key, value, index2); + } else if (value._bsontype === "BSONSymbol") { + index2 = serializeSymbol(buffer2, key, value, index2); + } else if (value._bsontype === "DBRef") { + index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); + } else if (value._bsontype === "BSONRegExp") { + index2 = serializeBSONRegExp(buffer2, key, value, index2); + } else if (value._bsontype === "Int32") { + index2 = serializeInt32(buffer2, key, value, index2); + } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { + index2 = serializeMinMax(buffer2, key, value, index2); + } else if (typeof value._bsontype !== "undefined") { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } else if (type === "function" && serializeFunctions) { + index2 = serializeFunction(buffer2, key, value, index2); } - let index2 = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format3) => { - if (match2 === "%%") { - return "%"; + } + } else if (object3 instanceof Map || isMap(object3)) { + const iterator = object3.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value ? entry.value[0] : undefined; + let value = entry.value ? entry.value[1] : undefined; + if (typeof value?.toBSON === "function") { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === "string" && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError("key " + key + " must not contain null bytes"); } - index2++; - const formatter = createDebug.formatters[format3]; - if (typeof formatter === "function") { - const val = args[index2]; - match2 = formatter.call(self2, val); - args.splice(index2, 1); - index2--; + if (checkKeys) { + if (key[0] === "$") { + throw new BSONError("key " + key + " must not start with '$'"); + } else if (key.includes(".")) { + throw new BSONError("key " + key + " must not contain '.'"); + } } - return match2; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); + } + if (value === undefined) { + if (ignoreUndefined === false) + index2 = serializeNull(buffer2, key, value, index2); + } else if (value === null) { + index2 = serializeNull(buffer2, key, value, index2); + } else if (type === "string") { + index2 = serializeString(buffer2, key, value, index2); + } else if (type === "number") { + index2 = serializeNumber(buffer2, key, value, index2); + } else if (type === "bigint") { + index2 = serializeBigInt(buffer2, key, value, index2); + } else if (type === "boolean") { + index2 = serializeBoolean(buffer2, key, value, index2); + } else if (type === "object" && value._bsontype == null) { + if (value instanceof Date || isDate(value)) { + index2 = serializeDate(buffer2, key, value, index2); + } else if (value instanceof Uint8Array || isUint8Array(value)) { + index2 = serializeBuffer(buffer2, key, value, index2); + } else if (value instanceof RegExp || isRegExp(value)) { + index2 = serializeRegExp(buffer2, key, value, index2); + } else { + index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } + } else if (type === "object") { + if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError; + } else if (value._bsontype === "ObjectId") { + index2 = serializeObjectId(buffer2, key, value, index2); + } else if (value._bsontype === "Decimal128") { + index2 = serializeDecimal128(buffer2, key, value, index2); + } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { + index2 = serializeLong(buffer2, key, value, index2); + } else if (value._bsontype === "Double") { + index2 = serializeDouble(buffer2, key, value, index2); + } else if (value._bsontype === "Code") { + index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } else if (value._bsontype === "Binary") { + index2 = serializeBinary(buffer2, key, value, index2); + } else if (value._bsontype === "BSONSymbol") { + index2 = serializeSymbol(buffer2, key, value, index2); + } else if (value._bsontype === "DBRef") { + index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); + } else if (value._bsontype === "BSONRegExp") { + index2 = serializeBSONRegExp(buffer2, key, value, index2); + } else if (value._bsontype === "Int32") { + index2 = serializeInt32(buffer2, key, value, index2); + } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { + index2 = serializeMinMax(buffer2, key, value, index2); + } else if (typeof value._bsontype !== "undefined") { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } else if (type === "function" && serializeFunctions) { + index2 = serializeFunction(buffer2, key, value, index2); + } } - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend3; - debug.destroy = createDebug.destroy; - Object.defineProperty(debug, "enabled", { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; + } else { + if (typeof object3?.toBSON === "function") { + object3 = object3.toBSON(); + if (object3 != null && typeof object3 !== "object") { + throw new BSONError("toBSON function did not return an object"); + } + } + for (const key of Object.keys(object3)) { + let value = object3[key]; + if (typeof value?.toBSON === "function") { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === "string" && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError("key " + key + " must not contain null bytes"); } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); + if (checkKeys) { + if (key[0] === "$") { + throw new BSONError("key " + key + " must not start with '$'"); + } else if (key.includes(".")) { + throw new BSONError("key " + key + " must not contain '.'"); + } } - return enabledCache; - }, - set: (v) => { - enableOverride = v; } + if (value === undefined) { + if (ignoreUndefined === false) + index2 = serializeNull(buffer2, key, value, index2); + } else if (value === null) { + index2 = serializeNull(buffer2, key, value, index2); + } else if (type === "string") { + index2 = serializeString(buffer2, key, value, index2); + } else if (type === "number") { + index2 = serializeNumber(buffer2, key, value, index2); + } else if (type === "bigint") { + index2 = serializeBigInt(buffer2, key, value, index2); + } else if (type === "boolean") { + index2 = serializeBoolean(buffer2, key, value, index2); + } else if (type === "object" && value._bsontype == null) { + if (value instanceof Date || isDate(value)) { + index2 = serializeDate(buffer2, key, value, index2); + } else if (value instanceof Uint8Array || isUint8Array(value)) { + index2 = serializeBuffer(buffer2, key, value, index2); + } else if (value instanceof RegExp || isRegExp(value)) { + index2 = serializeRegExp(buffer2, key, value, index2); + } else { + index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } + } else if (type === "object") { + if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError; + } else if (value._bsontype === "ObjectId") { + index2 = serializeObjectId(buffer2, key, value, index2); + } else if (value._bsontype === "Decimal128") { + index2 = serializeDecimal128(buffer2, key, value, index2); + } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { + index2 = serializeLong(buffer2, key, value, index2); + } else if (value._bsontype === "Double") { + index2 = serializeDouble(buffer2, key, value, index2); + } else if (value._bsontype === "Code") { + index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); + } else if (value._bsontype === "Binary") { + index2 = serializeBinary(buffer2, key, value, index2); + } else if (value._bsontype === "BSONSymbol") { + index2 = serializeSymbol(buffer2, key, value, index2); + } else if (value._bsontype === "DBRef") { + index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); + } else if (value._bsontype === "BSONRegExp") { + index2 = serializeBSONRegExp(buffer2, key, value, index2); + } else if (value._bsontype === "Int32") { + index2 = serializeInt32(buffer2, key, value, index2); + } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { + index2 = serializeMinMax(buffer2, key, value, index2); + } else if (typeof value._bsontype !== "undefined") { + throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } else if (type === "function" && serializeFunctions) { + index2 = serializeFunction(buffer2, key, value, index2); + } + } + } + path4.delete(object3); + buffer2[index2++] = 0; + const size = index2 - startingIndex; + startingIndex += NumberUtils.setInt32LE(buffer2, startingIndex, size); + return index2; + } + function isBSONType(value) { + return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string"; + } + var keysToCodecs = { + $oid: ObjectId, + $binary: Binary, + $uuid: Binary, + $symbol: BSONSymbol, + $numberInt: Int32, + $numberDecimal: Decimal128, + $numberDouble: Double, + $numberLong: Long, + $minKey: MinKey, + $maxKey: MaxKey, + $regex: BSONRegExp, + $regularExpression: BSONRegExp, + $timestamp: Timestamp + }; + function deserializeValue(value, options = {}) { + if (typeof value === "number") { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== "object") + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter((k2) => k2.startsWith("$") && value[k2] != null); + for (let i2 = 0;i2 < keys.length; i2++) { + const c3 = keysToCodecs[keys[i2]]; + if (c3) + return c3.fromExtendedJSON(value, options); + } + if (value.$date != null) { + const d = value.$date; + const date10 = new Date; + if (options.legacy) { + if (typeof d === "number") + date10.setTime(d); + else if (typeof d === "string") + date10.setTime(Date.parse(d)); + else if (typeof d === "bigint") + date10.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } else { + if (typeof d === "string") + date10.setTime(Date.parse(d)); + else if (Long.isLong(d)) + date10.setTime(d.toNumber()); + else if (typeof d === "number" && options.relaxed) + date10.setTime(d); + else if (typeof d === "bigint") + date10.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); + } + return date10; + } + if (value.$code != null) { + const copy = Object.assign({}, value); + if (value.$scope) { + copy.$scope = deserializeValue(value.$scope); + } + return Code.fromExtendedJSON(value); + } + if (isDBRefLike(value) || value.$dbPointer) { + const v = value.$ref ? value : value.$dbPointer; + if (v instanceof DBRef) + return v; + const dollarKeys = Object.keys(v).filter((k2) => k2.startsWith("$")); + let valid = true; + dollarKeys.forEach((k2) => { + if (["$ref", "$id", "$db"].indexOf(k2) === -1) + valid = false; }); - if (typeof createDebug.init === "function") { - createDebug.init(debug); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; + } + function serializeArray(array3, options) { + return array3.map((v, index2) => { + options.seenObjects.push({ propertyName: `index ${index2}`, obj: null }); + try { + return serializeValue(v, options); + } finally { + options.seenObjects.pop(); } - return debug; + }); + } + function getISOString(date10) { + const isoStr = date10.toISOString(); + return date10.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z"; + } + function serializeValue(value, options) { + if (value instanceof Map || isMap(value)) { + const obj = Object.create(null); + for (const [k2, v] of value) { + if (typeof k2 !== "string") { + throw new BSONError("Can only serialize maps with string keys"); + } + obj[k2] = v; + } + return serializeValue(obj, options); } - function extend3(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; + if ((typeof value === "object" || typeof value === "function") && value !== null) { + const index2 = options.seenObjects.findIndex((entry) => entry.obj === value); + if (index2 !== -1) { + const props = options.seenObjects.map((entry) => entry.propertyName); + const leadingPart = props.slice(0, index2).map((prop) => `${prop} -> `).join(""); + const alreadySeen = props[index2]; + const circularPart = " -> " + props.slice(index2 + 1, props.length - 1).map((prop) => `${prop} -> `).join(""); + const current = props[props.length - 1]; + const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2); + const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); + throw new BSONError(`Converting circular structure to EJSON: +` + ` ${leadingPart}${alreadySeen}${circularPart}${current} +` + ` ${leadingSpace}\\${dashes}/`); + } + options.seenObjects[options.seenObjects.length - 1].obj = value; } - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns3 of split) { - if (ns3[0] === "-") { - createDebug.skips.push(ns3.slice(1)); - } else { - createDebug.names.push(ns3); + if (Array.isArray(value)) + return serializeArray(value, options); + if (value === undefined) + return null; + if (value instanceof Date || isDate(value)) { + const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; + if (options.legacy) { + return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) }; + } + return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } }; + } + if (typeof value === "number" && (!options.relaxed || !isFinite(value))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; } } + return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() }; } - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; + if (typeof value === "bigint") { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + if (value instanceof RegExp || isRegExp(value)) { + let flags = value.flags; + if (flags === undefined) { + const match2 = value.toString().match(/[gimuy]*$/); + if (match2) { + flags = match2[0]; + } + } + const rx = new BSONRegExp(value.source, flags); + return rx.toExtendedJSON(options); + } + if (value != null && typeof value === "object") + return serializeDocument(value, options); + return value; + } + var BSON_TYPE_MAPPINGS = { + Binary: (o2) => new Binary(o2.value(), o2.sub_type), + Code: (o2) => new Code(o2.code, o2.scope), + DBRef: (o2) => new DBRef(o2.collection || o2.namespace, o2.oid, o2.db, o2.fields), + Decimal128: (o2) => new Decimal128(o2.bytes), + Double: (o2) => new Double(o2.value), + Int32: (o2) => new Int32(o2.value), + Long: (o2) => Long.fromBits(o2.low != null ? o2.low : o2.low_, o2.low != null ? o2.high : o2.high_, o2.low != null ? o2.unsigned : o2.unsigned_), + MaxKey: () => new MaxKey, + MinKey: () => new MinKey, + ObjectId: (o2) => new ObjectId(o2), + BSONRegExp: (o2) => new BSONRegExp(o2.pattern, o2.options), + BSONSymbol: (o2) => new BSONSymbol(o2.value), + Timestamp: (o2) => Timestamp.fromBits(o2.low, o2.high) + }; + function serializeDocument(doc3, options) { + if (doc3 == null || typeof doc3 !== "object") + throw new BSONError("not an object instance"); + const bsontype = doc3._bsontype; + if (typeof bsontype === "undefined") { + const _doc = {}; + for (const name of Object.keys(doc3)) { + options.seenObjects.push({ propertyName: name, obj: null }); + try { + const value = serializeValue(doc3[name], options); + if (name === "__proto__") { + Object.defineProperty(_doc, name, { + value, + writable: true, + enumerable: true, + configurable: true + }); } else { - searchIndex++; - templateIndex++; + _doc[name] = value; } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; - } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; + } finally { + options.seenObjects.pop(); } } - for (const ns3 of createDebug.names) { - if (matchesTemplate(name, ns3)) { - return true; + return _doc; + } else if (doc3 != null && typeof doc3 === "object" && typeof doc3._bsontype === "string" && doc3[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError; + } else if (isBSONType(doc3)) { + let outDoc = doc3; + if (typeof outDoc.toExtendedJSON !== "function") { + const mapper = BSON_TYPE_MAPPINGS[doc3._bsontype]; + if (!mapper) { + throw new BSONError("Unrecognized or invalid _bsontype: " + doc3._bsontype); } + outDoc = mapper(outDoc); } - return false; - } - function coerce3(val) { - if (val instanceof Error) { - return val.stack || val.message; + if (bsontype === "Code" && outDoc.scope) { + outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); + } else if (bsontype === "DBRef" && outDoc.oid) { + outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); } - return val; - } - function destroy() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + return outDoc.toExtendedJSON(options); + } else { + throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype); } - createDebug.enable(createDebug.load()); - return createDebug; } - module.exports = setup; -}); - -// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js -var require_browser = __commonJS((exports, module) => { - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load2; - exports.useColors = useColors; - exports.storage = localstorage(); - exports.destroy = (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } + function parse16(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false }; - })(); - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + return JSON.parse(text, (key, value) => { + if (key.indexOf("\x00") !== -1) { + throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + } + return deserializeValue(value, ejsonOptions); + }); } - function formatArgs(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); - if (!this.useColors) { - return; + function stringify7(value, replacer, space, options) { + if (space != null && typeof space === "object") { + options = space; + space = 0; } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index2 = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match2) => { - if (match2 === "%%") { - return; - } - index2++; - if (match2 === "%c") { - lastC = index2; - } + if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) { + options = replacer; + replacer = undefined; + space = 0; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: "(root)", obj: null }] }); - args.splice(lastC, 0, c); + const doc3 = serializeValue(value, serializeOptions); + return JSON.stringify(doc3, replacer, space); } - exports.log = console.debug || console.log || (() => {}); - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); - } else { - exports.storage.removeItem("debug"); - } - } catch (error91) {} + function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify7(value, options)); } - function load2() { - let r; + function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse16(JSON.stringify(ejson), options); + } + var EJSON = Object.create(null); + EJSON.parse = parse16; + EJSON.stringify = stringify7; + EJSON.serialize = EJSONserialize; + EJSON.deserialize = EJSONdeserialize; + Object.freeze(EJSON); + var BSONElementType = { + double: 1, + string: 2, + object: 3, + array: 4, + binData: 5, + undefined: 6, + objectId: 7, + bool: 8, + date: 9, + null: 10, + regex: 11, + dbPointer: 12, + javascript: 13, + symbol: 14, + javascriptWithScope: 15, + int: 16, + timestamp: 17, + long: 18, + decimal: 19, + minKey: 255, + maxKey: 127 + }; + function getSize(source, offset) { try { - r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); - } catch (error91) {} - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; + return NumberUtils.getNonnegativeInt32LE(source, offset); + } catch (cause) { + throw new BSONOffsetError("BSON size cannot be negative", offset, { cause }); } - return r; } - function localstorage() { - try { - return localStorage; - } catch (error91) {} + function findNull(bytes, offset) { + let nullTerminatorOffset = offset; + for (;bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++) + ; + if (nullTerminatorOffset === bytes.length - 1) { + throw new BSONOffsetError("Null terminator not found", offset); + } + return nullTerminatorOffset; } - module.exports = require_common3()(exports); - var { formatters } = module.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error91) { - return "[UnexpectedJSONParseError]: " + error91.message; + function parseToElements(bytes, startOffset = 0) { + startOffset ??= 0; + if (bytes.length < 5) { + throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); } - }; -}); - -// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js -var require_node = __commonJS((exports, module) => { - var tty = __require("tty"); - var util5 = __require("util"); - exports.init = init; - exports.log = log2; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load2; - exports.useColors = useColors; - exports.destroy = util5.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - exports.colors = [6, 2, 3, 4, 5, 1]; - try { - const supportsColor = (()=>{throw new Error("Cannot require module "+"supports-color");})(); - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; + const documentSize = getSize(bytes, startOffset); + if (documentSize > bytes.length - startOffset) { + throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); } - } catch (error91) {} - exports.inspectOpts = Object.keys(process.env).filter((key) => { - return /^debug_/i.test(key); - }).reduce((obj, key) => { - const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === "null") { - val = null; - } else { - val = Number(val); + if (bytes[startOffset + documentSize - 1] !== 0) { + throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize); } - obj[prop] = val; - return obj; - }, {}); - function useColors() { - return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); + const elements = []; + let offset = startOffset + 4; + while (offset <= documentSize + startOffset) { + const type = bytes[offset]; + offset += 1; + if (type === 0) { + if (offset - startOffset !== documentSize) { + throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); + } + break; + } + const nameOffset = offset; + const nameLength = findNull(bytes, offset) - nameOffset; + offset += nameLength + 1; + let length; + if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) { + length = 8; + } else if (type === BSONElementType.int) { + length = 4; + } else if (type === BSONElementType.objectId) { + length = 12; + } else if (type === BSONElementType.decimal) { + length = 16; + } else if (type === BSONElementType.bool) { + length = 1; + } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) { + length = 0; + } else if (type === BSONElementType.regex) { + length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; + } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) { + length = getSize(bytes, offset); + } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) { + length = getSize(bytes, offset) + 4; + if (type === BSONElementType.binData) { + length += 1; + } + if (type === BSONElementType.dbPointer) { + length += 12; + } + } else { + throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset); + } + if (length > documentSize) { + throw new BSONOffsetError("value reports length larger than document", offset); + } + elements.push([type, nameOffset, nameLength, offset, length]); + offset += length; + } + return elements; } - function formatArgs(args) { - const { namespace: name, useColors: useColors2 } = this; - if (useColors2) { - const c = this.color; - const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); - const prefix = ` ${colorCode};1m${name} \x1B[0m`; - args[0] = prefix + args[0].split(` -`).join(` -` + prefix); - args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); - } else { - args[0] = getDate() + name + " " + args[0]; + var onDemand = Object.create(null); + onDemand.parseToElements = parseToElements; + onDemand.ByteUtils = ByteUtils; + onDemand.NumberUtils = NumberUtils; + Object.freeze(onDemand); + var MAXSIZE = 1024 * 1024 * 17; + var buffer = ByteUtils.allocate(MAXSIZE); + function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); } } - function getDate() { - if (exports.inspectOpts.hideDate) { - return ""; + function serialize2(object3, options = {}) { + const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; + const minInternalBufferSize = typeof options.minInternalBufferSize === "number" ? options.minInternalBufferSize : MAXSIZE; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); } - return new Date().toISOString() + " "; + const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; } - function log2(...args) { - return process.stderr.write(util5.formatWithOptions(exports.inspectOpts, ...args) + ` -`); + function serializeWithBufferAndIndex(object3, finalBuffer, options = {}) { + const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; + const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; + const startIndex = typeof options.index === "number" ? options.index : 0; + const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; } - function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - delete process.env.DEBUG; - } + function deserialize(buffer2, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer2), options); } - function load2() { - return process.env.DEBUG; + function calculateObjectSize(object3, options = {}) { + options = options || {}; + const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; + const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; + return internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined); } - function init(debug) { - debug.inspectOpts = {}; - const keys = Object.keys(exports.inspectOpts); - for (let i = 0;i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index2 = startIndex; + for (let i2 = 0;i2 < numberOfDocuments; i2++) { + const size = NumberUtils.getInt32LE(bufferData, index2); + internalOptions.index = index2; + documents[docStartIndex + i2] = internalDeserialize(bufferData, internalOptions); + index2 = index2 + size; } + return index2; } - module.exports = require_common3()(exports); - var { formatters } = module.exports; - formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util5.inspect(v, this.inspectOpts).split(` -`).map((str) => str.trim()).join(" "); - }; - formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util5.inspect(v, this.inspectOpts); - }; + var bson = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BSONError, + BSONOffsetError, + BSONRegExp, + BSONRuntimeError, + BSONSymbol, + BSONType, + BSONValue, + BSONVersionError, + Binary, + Code, + DBRef, + Decimal128, + Double, + EJSON, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + Timestamp, + UUID: UUID2, + calculateObjectSize, + deserialize, + deserializeStream, + onDemand, + serialize: serialize2, + serializeWithBufferAndIndex, + setInternalBufferSize + }); + exports.BSON = bson; + exports.BSONError = BSONError; + exports.BSONOffsetError = BSONOffsetError; + exports.BSONRegExp = BSONRegExp; + exports.BSONRuntimeError = BSONRuntimeError; + exports.BSONSymbol = BSONSymbol; + exports.BSONType = BSONType; + exports.BSONValue = BSONValue; + exports.BSONVersionError = BSONVersionError; + exports.Binary = Binary; + exports.Code = Code; + exports.DBRef = DBRef; + exports.Decimal128 = Decimal128; + exports.Double = Double; + exports.EJSON = EJSON; + exports.Int32 = Int32; + exports.Long = Long; + exports.MaxKey = MaxKey; + exports.MinKey = MinKey; + exports.ObjectId = ObjectId; + exports.Timestamp = Timestamp; + exports.UUID = UUID2; + exports.calculateObjectSize = calculateObjectSize; + exports.deserialize = deserialize; + exports.deserializeStream = deserializeStream; + exports.onDemand = onDemand; + exports.serialize = serialize2; + exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; + exports.setInternalBufferSize = setInternalBufferSize; }); -// ../../node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js -var require_src = __commonJS((exports, module) => { - if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) { - module.exports = require_browser(); - } else { - module.exports = require_node(); +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bson.js +var require_bson2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toUTF8 = exports.getBigInt64LE = exports.getFloat64LE = exports.getInt32LE = exports.UUID = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.EJSON = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSONError = exports.BSON = exports.Binary = undefined; + exports.parseToElementsToArray = parseToElementsToArray; + exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; + exports.resolveBSONOptions = resolveBSONOptions; + exports.parseUtf8ValidationOption = parseUtf8ValidationOption; + var bson_1 = require_bson(); + var bson_2 = require_bson(); + Object.defineProperty(exports, "Binary", { enumerable: true, get: function() { + return bson_2.Binary; + } }); + Object.defineProperty(exports, "BSON", { enumerable: true, get: function() { + return bson_2.BSON; + } }); + Object.defineProperty(exports, "BSONError", { enumerable: true, get: function() { + return bson_2.BSONError; + } }); + Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function() { + return bson_2.BSONRegExp; + } }); + Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function() { + return bson_2.BSONSymbol; + } }); + Object.defineProperty(exports, "BSONType", { enumerable: true, get: function() { + return bson_2.BSONType; + } }); + Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function() { + return bson_2.calculateObjectSize; + } }); + Object.defineProperty(exports, "Code", { enumerable: true, get: function() { + return bson_2.Code; + } }); + Object.defineProperty(exports, "DBRef", { enumerable: true, get: function() { + return bson_2.DBRef; + } }); + Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function() { + return bson_2.Decimal128; + } }); + Object.defineProperty(exports, "deserialize", { enumerable: true, get: function() { + return bson_2.deserialize; + } }); + Object.defineProperty(exports, "Double", { enumerable: true, get: function() { + return bson_2.Double; + } }); + Object.defineProperty(exports, "EJSON", { enumerable: true, get: function() { + return bson_2.EJSON; + } }); + Object.defineProperty(exports, "Int32", { enumerable: true, get: function() { + return bson_2.Int32; + } }); + Object.defineProperty(exports, "Long", { enumerable: true, get: function() { + return bson_2.Long; + } }); + Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function() { + return bson_2.MaxKey; + } }); + Object.defineProperty(exports, "MinKey", { enumerable: true, get: function() { + return bson_2.MinKey; + } }); + Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function() { + return bson_2.ObjectId; + } }); + Object.defineProperty(exports, "serialize", { enumerable: true, get: function() { + return bson_2.serialize; + } }); + Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function() { + return bson_2.Timestamp; + } }); + Object.defineProperty(exports, "UUID", { enumerable: true, get: function() { + return bson_2.UUID; + } }); + function parseToElementsToArray(bytes, offset) { + const res = bson_1.BSON.onDemand.parseToElements(bytes, offset); + return Array.isArray(res) ? res : [...res]; + } + exports.getInt32LE = bson_1.BSON.onDemand.NumberUtils.getInt32LE; + exports.getFloat64LE = bson_1.BSON.onDemand.NumberUtils.getFloat64LE; + exports.getBigInt64LE = bson_1.BSON.onDemand.NumberUtils.getBigInt64LE; + exports.toUTF8 = bson_1.BSON.onDemand.ByteUtils.toUTF8; + function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw: raw2, enableUtf8Validation } = options; + return { + fieldsAsRaw, + useBigInt64, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw: raw2, + enableUtf8Validation + }; + } + function resolveBSONOptions(options, parent) { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false, + promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, + promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, + promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, + ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, + bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, + serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, + fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, + enableUtf8Validation: options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true + }; + } + function parseUtf8ValidationOption(options) { + const enableUtf8Validation = options?.enableUtf8Validation; + if (enableUtf8Validation === false) { + return { utf8: false }; + } + return { utf8: { writeErrors: false } }; } }); -// ../../node_modules/.pnpm/@kwsites+file-exists@1.1.1/node_modules/@kwsites/file-exists/dist/src/index.js -var require_src2 = __commonJS((exports) => { - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/error.js +var require_error2 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - var fs_1 = __require("fs"); - var debug_1 = __importDefault(require_src()); - var log2 = debug_1.default("@kwsites/file-exists"); - function check3(path4, isFile, isDirectory) { - log2(`checking %s`, path4); - try { - const stat4 = fs_1.statSync(path4); - if (stat4.isFile() && isFile) { - log2(`[OK] path represents a file`); - return true; - } - if (stat4.isDirectory() && isDirectory) { - log2(`[OK] path represents a directory`); - return true; + exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoClientClosedError = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoOperationTimeoutError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoClientBulkWriteExecutionError = exports.MongoClientBulkWriteCursorError = exports.MongoClientBulkWriteError = exports.MongoGCPError = exports.MongoAzureError = exports.MongoOIDCError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoStalePrimaryError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = undefined; + exports.needsRetryableWriteLabel = needsRetryableWriteLabel; + exports.isRetryableWriteError = isRetryableWriteError; + exports.isRetryableReadError = isRetryableReadError; + exports.isNodeShuttingDownError = isNodeShuttingDownError; + exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; + exports.isNetworkTimeoutError = isNetworkTimeoutError; + exports.isResumableError = isResumableError; + exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i"); + exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i"); + exports.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp("node is recovering", "i"); + exports.MONGODB_ERROR_CODES = Object.freeze({ + HostUnreachable: 6, + HostNotFound: 7, + AuthenticationFailed: 18, + NetworkTimeout: 89, + ShutdownInProgress: 91, + PrimarySteppedDown: 189, + ExceededTimeLimit: 262, + SocketException: 9001, + NotWritablePrimary: 10107, + InterruptedAtShutdown: 11600, + InterruptedDueToReplStateChange: 11602, + NotPrimaryNoSecondaryOk: 13435, + NotPrimaryOrSecondary: 13436, + StaleShardVersion: 63, + StaleEpoch: 150, + StaleConfig: 13388, + RetryChangeStream: 234, + FailedToSatisfyReadPreference: 133, + CursorNotFound: 43, + LegacyNotPrimary: 10058, + WriteConcernTimeout: 64, + NamespaceNotFound: 26, + IllegalOperation: 20, + MaxTimeMSExpired: 50, + UnknownReplWriteConcern: 79, + UnsatisfiableWriteConcern: 100, + Reauthenticate: 391, + ReadConcernMajorityNotAvailableYet: 134 + }); + exports.GET_MORE_RESUMABLE_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.StaleShardVersion, + exports.MONGODB_ERROR_CODES.StaleEpoch, + exports.MONGODB_ERROR_CODES.StaleConfig, + exports.MONGODB_ERROR_CODES.RetryChangeStream, + exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, + exports.MONGODB_ERROR_CODES.CursorNotFound + ]); + exports.MongoErrorLabel = Object.freeze({ + RetryableWriteError: "RetryableWriteError", + TransientTransactionError: "TransientTransactionError", + UnknownTransactionCommitResult: "UnknownTransactionCommitResult", + ResumableChangeStreamError: "ResumableChangeStreamError", + HandshakeError: "HandshakeError", + ResetPool: "ResetPool", + PoolRequstedRetry: "PoolRequstedRetry", + InterruptInUseConnections: "InterruptInUseConnections", + NoWritesPerformed: "NoWritesPerformed" + }); + function isAggregateError(e) { + return e != null && typeof e === "object" && "errors" in e && Array.isArray(e.errors); + } + + class MongoError extends Error { + get errorLabels() { + return Array.from(this.errorLabelSet); + } + constructor(message, options) { + super(message, options); + this.errorLabelSet = new Set; + } + static buildErrorMessage(e) { + if (typeof e === "string") { + return e; } - log2(`[FAIL] path represents something other than a file or directory`); - return false; - } catch (e) { - if (e.code === "ENOENT") { - log2(`[FAIL] path is not accessible: %o`, e); - return false; + if (isAggregateError(e) && e.message.length === 0) { + return e.errors.length === 0 ? "AggregateError has an empty errors array. Please check the `cause` property for more information." : e.errors.map(({ message }) => message).join(", "); } - log2(`[FATAL] %o`, e); - throw e; + return e != null && typeof e === "object" && "message" in e && typeof e.message === "string" ? e.message : "empty error message"; + } + get name() { + return "MongoError"; + } + get errmsg() { + return this.message; + } + hasErrorLabel(label) { + return this.errorLabelSet.has(label); + } + addErrorLabel(label) { + this.errorLabelSet.add(label); } } - function exists(path4, type = exports.READABLE) { - return check3(path4, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0); + exports.MongoError = MongoError; + + class MongoServerError extends MongoError { + constructor(message) { + super(message.message || message.errmsg || message.$err || "n/a"); + if (message.errorLabels) { + for (const label of message.errorLabels) + this.addErrorLabel(label); + } + this.errorResponse = message; + for (const name in message) { + if (name !== "errorLabels" && name !== "errmsg" && name !== "message" && name !== "errorResponse") { + this[name] = message[name]; + } + } + } + get name() { + return "MongoServerError"; + } } - exports.exists = exists; - exports.FILE = 1; - exports.FOLDER = 2; - exports.READABLE = exports.FILE + exports.FOLDER; -}); + exports.MongoServerError = MongoServerError; -// ../../node_modules/.pnpm/@kwsites+file-exists@1.1.1/node_modules/@kwsites/file-exists/dist/index.js -var require_dist4 = __commonJS((exports) => { - function __export2(m) { - for (var p in m) - if (!exports.hasOwnProperty(p)) - exports[p] = m[p]; + class MongoDriverError extends MongoError { + constructor(message, options) { + super(message, options); + } + get name() { + return "MongoDriverError"; + } } - Object.defineProperty(exports, "__esModule", { value: true }); - __export2(require_src2()); -}); + exports.MongoDriverError = MongoDriverError; -// ../../node_modules/.pnpm/@kwsites+promise-deferred@1.1.1/node_modules/@kwsites/promise-deferred/dist/index.js -var require_dist5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createDeferred = exports.deferred = undefined; - function deferred() { - let done; - let fail; - let status = "pending"; - const promise3 = new Promise((_done, _fail) => { - done = _done; - fail = _fail; - }); - return { - promise: promise3, - done(result) { - if (status === "pending") { - status = "resolved"; - done(result); - } - }, - fail(error91) { - if (status === "pending") { - status = "rejected"; - fail(error91); - } - }, - get fulfilled() { - return status !== "pending"; - }, - get status() { - return status; - } - }; + class MongoAPIError extends MongoDriverError { + constructor(message, options) { + super(message, options); + } + get name() { + return "MongoAPIError"; + } } - exports.deferred = deferred; - exports.createDeferred = deferred; - exports.default = deferred; -}); + exports.MongoAPIError = MongoAPIError; -// ../../node_modules/.pnpm/bson@6.10.4/node_modules/bson/lib/bson.cjs -var require_bson = __commonJS((exports) => { - var TypedArrayPrototypeGetSymbolToStringTag = (() => { - const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get; - return (value) => g.call(value); - })(); - function isUint8Array(value) { - return TypedArrayPrototypeGetSymbolToStringTag(value) === "Uint8Array"; + class MongoRuntimeError extends MongoDriverError { + constructor(message, options) { + super(message, options); + } + get name() { + return "MongoRuntimeError"; + } } - function isAnyArrayBuffer(value) { - return typeof value === "object" && value != null && Symbol.toStringTag in value && (value[Symbol.toStringTag] === "ArrayBuffer" || value[Symbol.toStringTag] === "SharedArrayBuffer"); + exports.MongoRuntimeError = MongoRuntimeError; + + class MongoStalePrimaryError extends MongoRuntimeError { + constructor(message, options) { + super(message, options); + } + get name() { + return "MongoStalePrimaryError"; + } } - function isRegExp(regexp2) { - return regexp2 instanceof RegExp || Object.prototype.toString.call(regexp2) === "[object RegExp]"; + exports.MongoStalePrimaryError = MongoStalePrimaryError; + + class MongoBatchReExecutionError extends MongoAPIError { + constructor(message = "This batch has already been executed, create new batch to execute") { + super(message); + } + get name() { + return "MongoBatchReExecutionError"; + } } - function isMap(value) { - return typeof value === "object" && value != null && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Map"; + exports.MongoBatchReExecutionError = MongoBatchReExecutionError; + + class MongoDecompressionError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return "MongoDecompressionError"; + } } - function isDate(date10) { - return date10 instanceof Date || Object.prototype.toString.call(date10) === "[object Date]"; + exports.MongoDecompressionError = MongoDecompressionError; + + class MongoNotConnectedError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return "MongoNotConnectedError"; + } } - function defaultInspect(x2, _options) { - return JSON.stringify(x2, (k2, v) => { - if (typeof v === "bigint") { - return { $numberLong: `${v}` }; - } else if (isMap(v)) { - return Object.fromEntries(v); - } - return v; - }); + exports.MongoNotConnectedError = MongoNotConnectedError; + + class MongoTransactionError extends MongoAPIError { + constructor(message) { + super(message); + } + get name() { + return "MongoTransactionError"; + } } - function getStylizeFunction(options) { - const stylizeExists = options != null && typeof options === "object" && "stylize" in options && typeof options.stylize === "function"; - if (stylizeExists) { - return options.stylize; + exports.MongoTransactionError = MongoTransactionError; + + class MongoExpiredSessionError extends MongoAPIError { + constructor(message = "Cannot use a session that has ended") { + super(message); + } + get name() { + return "MongoExpiredSessionError"; } } - var BSON_MAJOR_VERSION = 6; - var BSON_VERSION_SYMBOL = Symbol.for("@@mdb.bson.version"); - var BSON_INT32_MAX = 2147483647; - var BSON_INT32_MIN = -2147483648; - var BSON_INT64_MAX = Math.pow(2, 63) - 1; - var BSON_INT64_MIN = -Math.pow(2, 63); - var JS_INT_MAX = Math.pow(2, 53); - var JS_INT_MIN = -Math.pow(2, 53); - var BSON_DATA_NUMBER = 1; - var BSON_DATA_STRING = 2; - var BSON_DATA_OBJECT = 3; - var BSON_DATA_ARRAY = 4; - var BSON_DATA_BINARY = 5; - var BSON_DATA_UNDEFINED = 6; - var BSON_DATA_OID = 7; - var BSON_DATA_BOOLEAN = 8; - var BSON_DATA_DATE = 9; - var BSON_DATA_NULL = 10; - var BSON_DATA_REGEXP = 11; - var BSON_DATA_DBPOINTER = 12; - var BSON_DATA_CODE = 13; - var BSON_DATA_SYMBOL = 14; - var BSON_DATA_CODE_W_SCOPE = 15; - var BSON_DATA_INT = 16; - var BSON_DATA_TIMESTAMP = 17; - var BSON_DATA_LONG = 18; - var BSON_DATA_DECIMAL128 = 19; - var BSON_DATA_MIN_KEY = 255; - var BSON_DATA_MAX_KEY = 127; - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - var BSON_BINARY_SUBTYPE_UUID_NEW = 4; - var BSONType = Object.freeze({ - double: 1, - string: 2, - object: 3, - array: 4, - binData: 5, - undefined: 6, - objectId: 7, - bool: 8, - date: 9, - null: 10, - regex: 11, - dbPointer: 12, - javascript: 13, - symbol: 14, - javascriptWithScope: 15, - int: 16, - timestamp: 17, - long: 18, - decimal: 19, - minKey: -1, - maxKey: 127 - }); + exports.MongoExpiredSessionError = MongoExpiredSessionError; - class BSONError extends Error { - get bsonError() { - return true; + class MongoKerberosError extends MongoRuntimeError { + constructor(message) { + super(message); } get name() { - return "BSONError"; + return "MongoKerberosError"; } + } + exports.MongoKerberosError = MongoKerberosError; + + class MongoAWSError extends MongoRuntimeError { constructor(message, options) { super(message, options); } - static isBSONError(value) { - return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value; + get name() { + return "MongoAWSError"; } } + exports.MongoAWSError = MongoAWSError; - class BSONVersionError extends BSONError { + class MongoOIDCError extends MongoRuntimeError { + constructor(message) { + super(message); + } get name() { - return "BSONVersionError"; + return "MongoOIDCError"; } - constructor() { - super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`); + } + exports.MongoOIDCError = MongoOIDCError; + + class MongoAzureError extends MongoOIDCError { + constructor(message) { + super(message); + } + get name() { + return "MongoAzureError"; } } + exports.MongoAzureError = MongoAzureError; - class BSONRuntimeError extends BSONError { + class MongoGCPError extends MongoOIDCError { + constructor(message) { + super(message); + } get name() { - return "BSONRuntimeError"; + return "MongoGCPError"; } + } + exports.MongoGCPError = MongoGCPError; + + class MongoClientBulkWriteError extends MongoServerError { constructor(message) { super(message); + this.writeConcernErrors = []; + this.writeErrors = new Map; + } + get name() { + return "MongoClientBulkWriteError"; } } + exports.MongoClientBulkWriteError = MongoClientBulkWriteError; - class BSONOffsetError extends BSONError { + class MongoClientBulkWriteCursorError extends MongoRuntimeError { + constructor(message) { + super(message); + } get name() { - return "BSONOffsetError"; + return "MongoClientBulkWriteCursorError"; } - constructor(message, offset, options) { - super(`${message}. offset: ${offset}`, options); - this.offset = offset; + } + exports.MongoClientBulkWriteCursorError = MongoClientBulkWriteCursorError; + + class MongoClientBulkWriteExecutionError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return "MongoClientBulkWriteExecutionError"; } } - var TextDecoderFatal; - var TextDecoderNonFatal; - function parseUtf8(buffer2, start, end, fatal) { - if (fatal) { - TextDecoderFatal ??= new TextDecoder("utf8", { fatal: true }); - try { - return TextDecoderFatal.decode(buffer2.subarray(start, end)); - } catch (cause) { - throw new BSONError("Invalid UTF-8 string in BSON document", { cause }); - } + exports.MongoClientBulkWriteExecutionError = MongoClientBulkWriteExecutionError; + + class MongoChangeStreamError extends MongoRuntimeError { + constructor(message) { + super(message); + } + get name() { + return "MongoChangeStreamError"; } - TextDecoderNonFatal ??= new TextDecoder("utf8", { fatal: false }); - return TextDecoderNonFatal.decode(buffer2.subarray(start, end)); } - function tryReadBasicLatin(uint8array, start, end) { - if (uint8array.length === 0) { - return ""; + exports.MongoChangeStreamError = MongoChangeStreamError; + + class MongoTailableCursorError extends MongoAPIError { + constructor(message = "Tailable cursor does not support this operation") { + super(message); } - const stringByteLength = end - start; - if (stringByteLength === 0) { - return ""; + get name() { + return "MongoTailableCursorError"; } - if (stringByteLength > 20) { - return null; + } + exports.MongoTailableCursorError = MongoTailableCursorError; + + class MongoGridFSStreamError extends MongoRuntimeError { + constructor(message) { + super(message); } - if (stringByteLength === 1 && uint8array[start] < 128) { - return String.fromCharCode(uint8array[start]); + get name() { + return "MongoGridFSStreamError"; } - if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) { - return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]); + } + exports.MongoGridFSStreamError = MongoGridFSStreamError; + + class MongoGridFSChunkError extends MongoRuntimeError { + constructor(message) { + super(message); } - if (stringByteLength === 3 && uint8array[start] < 128 && uint8array[start + 1] < 128 && uint8array[start + 2] < 128) { - return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]) + String.fromCharCode(uint8array[start + 2]); + get name() { + return "MongoGridFSChunkError"; } - const latinBytes = []; - for (let i2 = start;i2 < end; i2++) { - const byte = uint8array[i2]; - if (byte > 127) { - return null; - } - latinBytes.push(byte); + } + exports.MongoGridFSChunkError = MongoGridFSChunkError; + + class MongoUnexpectedServerResponseError extends MongoRuntimeError { + constructor(message, options) { + super(message, options); + } + get name() { + return "MongoUnexpectedServerResponseError"; } - return String.fromCharCode(...latinBytes); } - function tryWriteBasicLatin(destination, source, offset) { - if (source.length === 0) - return 0; - if (source.length > 25) - return null; - if (destination.length - offset < source.length) - return null; - for (let charOffset = 0, destinationOffset = offset;charOffset < source.length; charOffset++, destinationOffset++) { - const char = source.charCodeAt(charOffset); - if (char > 127) - return null; - destination[destinationOffset] = char; + exports.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError; + + class MongoOperationTimeoutError extends MongoDriverError { + get name() { + return "MongoOperationTimeoutError"; } - return source.length; } - function nodejsMathRandomBytes(byteLength) { - return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); + exports.MongoOperationTimeoutError = MongoOperationTimeoutError; + + class MongoCursorInUseError extends MongoAPIError { + constructor(message = "Cursor is already initialized") { + super(message); + } + get name() { + return "MongoCursorInUseError"; + } } - var nodejsRandomBytes = (() => { - try { - return __require("crypto").randomBytes; - } catch { - return nodejsMathRandomBytes; + exports.MongoCursorInUseError = MongoCursorInUseError; + + class MongoServerClosedError extends MongoAPIError { + constructor(message = "Server is closed") { + super(message); } - })(); - var nodeJsByteUtils = { - toLocalBufferType(potentialBuffer) { - if (Buffer.isBuffer(potentialBuffer)) { - return potentialBuffer; - } - if (ArrayBuffer.isView(potentialBuffer)) { - return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); - } - const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); - if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") { - return Buffer.from(potentialBuffer); - } - throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`); - }, - allocate(size) { - return Buffer.alloc(size); - }, - allocateUnsafe(size) { - return Buffer.allocUnsafe(size); - }, - equals(a, b2) { - return nodeJsByteUtils.toLocalBufferType(a).equals(b2); - }, - fromNumberArray(array3) { - return Buffer.from(array3); - }, - fromBase64(base647) { - return Buffer.from(base647, "base64"); - }, - toBase64(buffer2) { - return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64"); - }, - fromISO88591(codePoints) { - return Buffer.from(codePoints, "binary"); - }, - toISO88591(buffer2) { - return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary"); - }, - fromHex(hex3) { - return Buffer.from(hex3, "hex"); - }, - toHex(buffer2) { - return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex"); - }, - toUTF8(buffer2, start, end, fatal) { - const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null; - if (basicLatin != null) { - return basicLatin; - } - const string7 = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end); - if (fatal) { - for (let i2 = 0;i2 < string7.length; i2++) { - if (string7.charCodeAt(i2) === 65533) { - parseUtf8(buffer2, start, end, true); - break; - } - } - } - return string7; - }, - utf8ByteLength(input) { - return Buffer.byteLength(input, "utf8"); - }, - encodeUTF8Into(buffer2, source, byteOffset) { - const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset); - if (latinBytesWritten != null) { - return latinBytesWritten; - } - return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, undefined, "utf8"); - }, - randomBytes: nodejsRandomBytes, - swap32(buffer2) { - return nodeJsByteUtils.toLocalBufferType(buffer2).swap32(); + get name() { + return "MongoServerClosedError"; } - }; - function isReactNative() { - const { navigator: navigator2 } = globalThis; - return typeof navigator2 === "object" && navigator2.product === "ReactNative"; } - function webMathRandomBytes(byteLength) { - if (byteLength < 0) { - throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + exports.MongoServerClosedError = MongoServerClosedError; + + class MongoCursorExhaustedError extends MongoAPIError { + constructor(message) { + super(message || "Cursor is exhausted"); + } + get name() { + return "MongoCursorExhaustedError"; } - return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); } - var webRandomBytes = (() => { - const { crypto: crypto3 } = globalThis; - if (crypto3 != null && typeof crypto3.getRandomValues === "function") { - return (byteLength) => { - return crypto3.getRandomValues(webByteUtils.allocate(byteLength)); - }; - } else { - if (isReactNative()) { - const { console: console2 } = globalThis; - console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values."); - } - return webMathRandomBytes; + exports.MongoCursorExhaustedError = MongoCursorExhaustedError; + + class MongoTopologyClosedError extends MongoAPIError { + constructor(message = "Topology is closed") { + super(message); } - })(); - var HEX_DIGIT = /(\d|[a-f])/i; - var webByteUtils = { - toLocalBufferType(potentialUint8array) { - const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array); - if (stringTag === "Uint8Array") { - return potentialUint8array; - } - if (ArrayBuffer.isView(potentialUint8array)) { - return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); - } - if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") { - return new Uint8Array(potentialUint8array); - } - throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`); - }, - allocate(size) { - if (typeof size !== "number") { - throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); - } - return new Uint8Array(size); - }, - allocateUnsafe(size) { - return webByteUtils.allocate(size); - }, - equals(a, b2) { - if (a.byteLength !== b2.byteLength) { - return false; - } - for (let i2 = 0;i2 < a.byteLength; i2++) { - if (a[i2] !== b2[i2]) { - return false; - } - } - return true; - }, - fromNumberArray(array3) { - return Uint8Array.from(array3); - }, - fromBase64(base647) { - return Uint8Array.from(atob(base647), (c3) => c3.charCodeAt(0)); - }, - toBase64(uint8array) { - return btoa(webByteUtils.toISO88591(uint8array)); - }, - fromISO88591(codePoints) { - return Uint8Array.from(codePoints, (c3) => c3.charCodeAt(0) & 255); - }, - toISO88591(uint8array) { - return Array.from(Uint16Array.from(uint8array), (b2) => String.fromCharCode(b2)).join(""); - }, - fromHex(hex3) { - const evenLengthHex = hex3.length % 2 === 0 ? hex3 : hex3.slice(0, hex3.length - 1); - const buffer2 = []; - for (let i2 = 0;i2 < evenLengthHex.length; i2 += 2) { - const firstDigit = evenLengthHex[i2]; - const secondDigit = evenLengthHex[i2 + 1]; - if (!HEX_DIGIT.test(firstDigit)) { - break; - } - if (!HEX_DIGIT.test(secondDigit)) { - break; - } - const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); - buffer2.push(hexDigit); - } - return Uint8Array.from(buffer2); - }, - toHex(uint8array) { - return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join(""); - }, - toUTF8(uint8array, start, end, fatal) { - const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null; - if (basicLatin != null) { - return basicLatin; - } - return parseUtf8(uint8array, start, end, fatal); - }, - utf8ByteLength(input) { - return new TextEncoder().encode(input).byteLength; - }, - encodeUTF8Into(uint8array, source, byteOffset) { - const bytes = new TextEncoder().encode(source); - uint8array.set(bytes, byteOffset); - return bytes.byteLength; - }, - randomBytes: webRandomBytes, - swap32(buffer2) { - if (buffer2.length % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i2 = 0;i2 < buffer2.length; i2 += 4) { - const byte0 = buffer2[i2]; - const byte1 = buffer2[i2 + 1]; - const byte2 = buffer2[i2 + 2]; - const byte3 = buffer2[i2 + 3]; - buffer2[i2] = byte3; - buffer2[i2 + 1] = byte2; - buffer2[i2 + 2] = byte1; - buffer2[i2 + 3] = byte0; - } - return buffer2; + get name() { + return "MongoTopologyClosedError"; } - }; - var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true; - var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + } + exports.MongoTopologyClosedError = MongoTopologyClosedError; - class BSONValue { - get [BSON_VERSION_SYMBOL]() { - return BSON_MAJOR_VERSION; + class MongoClientClosedError extends MongoAPIError { + constructor() { + super("Operation interrupted because client was closed"); } - [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) { - return this.inspect(depth, options, inspect); + get name() { + return "MongoClientClosedError"; } } - var FLOAT = new Float64Array(1); - var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8); - FLOAT[0] = -1; - var isBigEndian = FLOAT_BYTES[7] === 0; - var NumberUtils = { - isBigEndian, - getNonnegativeInt32LE(source, offset) { - if (source[offset + 3] > 127) { - throw new RangeError(`Size cannot be negative at offset: ${offset}`); - } - return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24; - }, - getInt32LE(source, offset) { - return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24; - }, - getUint32LE(source, offset) { - return source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216; - }, - getUint32BE(source, offset) { - return source[offset + 3] + source[offset + 2] * 256 + source[offset + 1] * 65536 + source[offset] * 16777216; - }, - getBigInt64LE(source, offset) { - const hi = BigInt(source[offset + 4] + source[offset + 5] * 256 + source[offset + 6] * 65536 + (source[offset + 7] << 24)); - const lo = BigInt(source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216); - return (hi << BigInt(32)) + lo; - }, - getFloat64LE: isBigEndian ? (source, offset) => { - FLOAT_BYTES[7] = source[offset]; - FLOAT_BYTES[6] = source[offset + 1]; - FLOAT_BYTES[5] = source[offset + 2]; - FLOAT_BYTES[4] = source[offset + 3]; - FLOAT_BYTES[3] = source[offset + 4]; - FLOAT_BYTES[2] = source[offset + 5]; - FLOAT_BYTES[1] = source[offset + 6]; - FLOAT_BYTES[0] = source[offset + 7]; - return FLOAT[0]; - } : (source, offset) => { - FLOAT_BYTES[0] = source[offset]; - FLOAT_BYTES[1] = source[offset + 1]; - FLOAT_BYTES[2] = source[offset + 2]; - FLOAT_BYTES[3] = source[offset + 3]; - FLOAT_BYTES[4] = source[offset + 4]; - FLOAT_BYTES[5] = source[offset + 5]; - FLOAT_BYTES[6] = source[offset + 6]; - FLOAT_BYTES[7] = source[offset + 7]; - return FLOAT[0]; - }, - setInt32BE(destination, offset, value) { - destination[offset + 3] = value; - value >>>= 8; - destination[offset + 2] = value; - value >>>= 8; - destination[offset + 1] = value; - value >>>= 8; - destination[offset] = value; - return 4; - }, - setInt32LE(destination, offset, value) { - destination[offset] = value; - value >>>= 8; - destination[offset + 1] = value; - value >>>= 8; - destination[offset + 2] = value; - value >>>= 8; - destination[offset + 3] = value; - return 4; - }, - setBigInt64LE(destination, offset, value) { - const mask32bits = BigInt(4294967295); - let lo = Number(value & mask32bits); - destination[offset] = lo; - lo >>= 8; - destination[offset + 1] = lo; - lo >>= 8; - destination[offset + 2] = lo; - lo >>= 8; - destination[offset + 3] = lo; - let hi = Number(value >> BigInt(32) & mask32bits); - destination[offset + 4] = hi; - hi >>= 8; - destination[offset + 5] = hi; - hi >>= 8; - destination[offset + 6] = hi; - hi >>= 8; - destination[offset + 7] = hi; - return 8; - }, - setFloat64LE: isBigEndian ? (destination, offset, value) => { - FLOAT[0] = value; - destination[offset] = FLOAT_BYTES[7]; - destination[offset + 1] = FLOAT_BYTES[6]; - destination[offset + 2] = FLOAT_BYTES[5]; - destination[offset + 3] = FLOAT_BYTES[4]; - destination[offset + 4] = FLOAT_BYTES[3]; - destination[offset + 5] = FLOAT_BYTES[2]; - destination[offset + 6] = FLOAT_BYTES[1]; - destination[offset + 7] = FLOAT_BYTES[0]; - return 8; - } : (destination, offset, value) => { - FLOAT[0] = value; - destination[offset] = FLOAT_BYTES[0]; - destination[offset + 1] = FLOAT_BYTES[1]; - destination[offset + 2] = FLOAT_BYTES[2]; - destination[offset + 3] = FLOAT_BYTES[3]; - destination[offset + 4] = FLOAT_BYTES[4]; - destination[offset + 5] = FLOAT_BYTES[5]; - destination[offset + 6] = FLOAT_BYTES[6]; - destination[offset + 7] = FLOAT_BYTES[7]; - return 8; + exports.MongoClientClosedError = MongoClientClosedError; + + class MongoNetworkError extends MongoError { + constructor(message, options) { + super(message, { cause: options?.cause }); + this.beforeHandshake = !!options?.beforeHandshake; } - }; + get name() { + return "MongoNetworkError"; + } + } + exports.MongoNetworkError = MongoNetworkError; - class Binary extends BSONValue { - get _bsontype() { - return "Binary"; + class MongoNetworkTimeoutError extends MongoNetworkError { + constructor(message, options) { + super(message, options); } - constructor(buffer2, subType) { - super(); - if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) { - throw new BSONError("Binary can only be constructed from Uint8Array or number[]"); - } - this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; - if (buffer2 == null) { - this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); - this.position = 0; - } else { - this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2); - this.position = this.buffer.byteLength; - } + get name() { + return "MongoNetworkTimeoutError"; } - put(byteValue) { - if (typeof byteValue === "string" && byteValue.length !== 1) { - throw new BSONError("only accepts single character String"); - } else if (typeof byteValue !== "number" && byteValue.length !== 1) - throw new BSONError("only accepts single character Uint8Array or Array"); - let decodedByte; - if (typeof byteValue === "string") { - decodedByte = byteValue.charCodeAt(0); - } else if (typeof byteValue === "number") { - decodedByte = byteValue; - } else { - decodedByte = byteValue[0]; - } - if (decodedByte < 0 || decodedByte > 255) { - throw new BSONError("only accepts number in a valid unsigned byte range 0-255"); - } - if (this.buffer.byteLength > this.position) { - this.buffer[this.position++] = decodedByte; - } else { - const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - this.buffer[this.position++] = decodedByte; - } + } + exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; + + class MongoParseError extends MongoDriverError { + constructor(message) { + super(message); } - write(sequence, offset) { - offset = typeof offset === "number" ? offset : this.position; - if (this.buffer.byteLength < offset + sequence.length) { - const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); - newSpace.set(this.buffer, 0); - this.buffer = newSpace; - } - if (ArrayBuffer.isView(sequence)) { - this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); - this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; - } else if (typeof sequence === "string") { - throw new BSONError("input cannot be string"); - } + get name() { + return "MongoParseError"; } - read(position, length) { - length = length && length > 0 ? length : this.position; - const end = position + length; - return this.buffer.subarray(position, end > this.position ? this.position : end); + } + exports.MongoParseError = MongoParseError; + + class MongoInvalidArgumentError extends MongoAPIError { + constructor(message, options) { + super(message, options); } - value() { - return this.buffer.length === this.position ? this.buffer : this.buffer.subarray(0, this.position); + get name() { + return "MongoInvalidArgumentError"; } - length() { - return this.position; + } + exports.MongoInvalidArgumentError = MongoInvalidArgumentError; + + class MongoCompatibilityError extends MongoAPIError { + constructor(message) { + super(message); } - toJSON() { - return ByteUtils.toBase64(this.buffer.subarray(0, this.position)); + get name() { + return "MongoCompatibilityError"; } - toString(encoding) { - if (encoding === "hex") - return ByteUtils.toHex(this.buffer.subarray(0, this.position)); - if (encoding === "base64") - return ByteUtils.toBase64(this.buffer.subarray(0, this.position)); - if (encoding === "utf8" || encoding === "utf-8") - return ByteUtils.toUTF8(this.buffer, 0, this.position, false); - return ByteUtils.toUTF8(this.buffer, 0, this.position, false); + } + exports.MongoCompatibilityError = MongoCompatibilityError; + + class MongoMissingCredentialsError extends MongoAPIError { + constructor(message) { + super(message); } - toExtendedJSON(options) { - options = options || {}; - if (this.sub_type === Binary.SUBTYPE_VECTOR) { - validateBinaryVector(this); + get name() { + return "MongoMissingCredentialsError"; + } + } + exports.MongoMissingCredentialsError = MongoMissingCredentialsError; + + class MongoMissingDependencyError extends MongoAPIError { + constructor(message, options) { + super(message, options); + this.dependencyName = options.dependencyName; + } + get name() { + return "MongoMissingDependencyError"; + } + } + exports.MongoMissingDependencyError = MongoMissingDependencyError; + + class MongoSystemError extends MongoError { + constructor(message, reason) { + if (reason && reason.error) { + super(MongoError.buildErrorMessage(reason.error.message || reason.error), { + cause: reason.error + }); + } else { + super(message); } - const base64String = ByteUtils.toBase64(this.buffer); - const subType = Number(this.sub_type).toString(16); - if (options.legacy) { - return { - $binary: base64String, - $type: subType.length === 1 ? "0" + subType : subType - }; + if (reason) { + this.reason = reason; } - return { - $binary: { - base64: base64String, - subType: subType.length === 1 ? "0" + subType : subType - } - }; + this.code = reason.error?.code; } - toUUID() { - if (this.sub_type === Binary.SUBTYPE_UUID) { - return new UUID2(this.buffer.subarray(0, this.position)); - } - throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`); + get name() { + return "MongoSystemError"; } - static createFromHexString(hex3, subType) { - return new Binary(ByteUtils.fromHex(hex3), subType); + } + exports.MongoSystemError = MongoSystemError; + + class MongoServerSelectionError extends MongoSystemError { + constructor(message, reason) { + super(message, reason); } - static createFromBase64(base647, subType) { - return new Binary(ByteUtils.fromBase64(base647), subType); + get name() { + return "MongoServerSelectionError"; } - static fromExtendedJSON(doc3, options) { - options = options || {}; - let data; - let type; - if ("$binary" in doc3) { - if (options.legacy && typeof doc3.$binary === "string" && "$type" in doc3) { - type = doc3.$type ? parseInt(doc3.$type, 16) : 0; - data = ByteUtils.fromBase64(doc3.$binary); - } else { - if (typeof doc3.$binary !== "string") { - type = doc3.$binary.subType ? parseInt(doc3.$binary.subType, 16) : 0; - data = ByteUtils.fromBase64(doc3.$binary.base64); - } - } - } else if ("$uuid" in doc3) { - type = 4; - data = UUID2.bytesFromString(doc3.$uuid); - } - if (!data) { - throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc3)}`); - } - return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID2(data) : new Binary(data, type); + } + exports.MongoServerSelectionError = MongoServerSelectionError; + + class MongoWriteConcernError extends MongoServerError { + constructor(result) { + super({ ...result.writeConcernError, ...result }); + this.errInfo = result.writeConcernError.errInfo; + this.result = result; } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - const base647 = ByteUtils.toBase64(this.buffer.subarray(0, this.position)); - const base64Arg = inspect(base647, options); - const subTypeArg = inspect(this.sub_type, options); - return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`; + get name() { + return "MongoWriteConcernError"; } - toInt8Array() { - if (this.sub_type !== Binary.SUBTYPE_VECTOR) { - throw new BSONError("Binary sub_type is not Vector"); - } - if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) { - throw new BSONError("Binary datatype field is not Int8"); - } - validateBinaryVector(this); - return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); + } + exports.MongoWriteConcernError = MongoWriteConcernError; + var RETRYABLE_READ_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.HostUnreachable, + exports.MONGODB_ERROR_CODES.HostNotFound, + exports.MONGODB_ERROR_CODES.NetworkTimeout, + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.SocketException, + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, + exports.MONGODB_ERROR_CODES.ExceededTimeLimit, + exports.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet + ]); + var RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES; + function needsRetryableWriteLabel(error91, maxWireVersion, serverType) { + if (error91 instanceof MongoNetworkError) { + return true; } - toFloat32Array() { - if (this.sub_type !== Binary.SUBTYPE_VECTOR) { - throw new BSONError("Binary sub_type is not Vector"); - } - if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) { - throw new BSONError("Binary datatype field is not Float32"); + if (error91 instanceof MongoError) { + if ((maxWireVersion >= 9 || isRetryableWriteError(error91)) && !error91.hasErrorLabel(exports.MongoErrorLabel.HandshakeError)) { + return false; } - validateBinaryVector(this); - const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); - if (NumberUtils.isBigEndian) - ByteUtils.swap32(floatBytes); - return new Float32Array(floatBytes.buffer); } - toPackedBits() { - if (this.sub_type !== Binary.SUBTYPE_VECTOR) { - throw new BSONError("Binary sub_type is not Vector"); - } - if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) { - throw new BSONError("Binary datatype field is not packed bit"); + if (error91 instanceof MongoWriteConcernError) { + if (serverType === "Mongos" && maxWireVersion < 9) { + return RETRYABLE_WRITE_ERROR_CODES.has(error91.result.code ?? 0); } - validateBinaryVector(this); - return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position)); + const code = error91.result.writeConcernError.code ?? Number(error91.code); + return RETRYABLE_WRITE_ERROR_CODES.has(Number.isNaN(code) ? 0 : code); } - toBits() { - if (this.sub_type !== Binary.SUBTYPE_VECTOR) { - throw new BSONError("Binary sub_type is not Vector"); - } - if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) { - throw new BSONError("Binary datatype field is not packed bit"); - } - validateBinaryVector(this); - const byteCount = this.length() - 2; - const bitCount = byteCount * 8 - this.buffer[1]; - const bits = new Int8Array(bitCount); - for (let bitOffset = 0;bitOffset < bits.length; bitOffset++) { - const byteOffset = bitOffset / 8 | 0; - const byte = this.buffer[byteOffset + 2]; - const shift = 7 - bitOffset % 8; - const bit = byte >> shift & 1; - bits[bitOffset] = bit; - } - return bits; + if (error91 instanceof MongoError) { + return RETRYABLE_WRITE_ERROR_CODES.has(Number(error91.code)); } - static fromInt8Array(array3) { - const buffer2 = ByteUtils.allocate(array3.byteLength + 2); - buffer2[0] = Binary.VECTOR_TYPE.Int8; - buffer2[1] = 0; - const intBytes = new Uint8Array(array3.buffer, array3.byteOffset, array3.byteLength); - buffer2.set(intBytes, 2); - const bin = new this(buffer2, this.SUBTYPE_VECTOR); - validateBinaryVector(bin); - return bin; + const isNotWritablePrimaryError2 = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error91.message); + if (isNotWritablePrimaryError2) { + return true; } - static fromFloat32Array(array3) { - const binaryBytes = ByteUtils.allocate(array3.byteLength + 2); - binaryBytes[0] = Binary.VECTOR_TYPE.Float32; - binaryBytes[1] = 0; - const floatBytes = new Uint8Array(array3.buffer, array3.byteOffset, array3.byteLength); - binaryBytes.set(floatBytes, 2); - if (NumberUtils.isBigEndian) - ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2)); - const bin = new this(binaryBytes, this.SUBTYPE_VECTOR); - validateBinaryVector(bin); - return bin; + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error91.message); + if (isNodeIsRecoveringError) { + return true; } - static fromPackedBits(array3, padding = 0) { - const buffer2 = ByteUtils.allocate(array3.byteLength + 2); - buffer2[0] = Binary.VECTOR_TYPE.PackedBit; - buffer2[1] = padding; - buffer2.set(array3, 2); - const bin = new this(buffer2, this.SUBTYPE_VECTOR); - validateBinaryVector(bin); - return bin; + return false; + } + function isRetryableWriteError(error91) { + return error91.hasErrorLabel(exports.MongoErrorLabel.RetryableWriteError) || error91.hasErrorLabel(exports.MongoErrorLabel.PoolRequstedRetry); + } + function isRetryableReadError(error91) { + const hasRetryableErrorCode = typeof error91.code === "number" ? RETRYABLE_READ_ERROR_CODES.has(error91.code) : false; + if (hasRetryableErrorCode) { + return true; } - static fromBits(bits) { - const byteLength = bits.length + 7 >>> 3; - const bytes = new Uint8Array(byteLength + 2); - bytes[0] = Binary.VECTOR_TYPE.PackedBit; - const remainder = bits.length % 8; - bytes[1] = remainder === 0 ? 0 : 8 - remainder; - for (let bitOffset = 0;bitOffset < bits.length; bitOffset++) { - const byteOffset = bitOffset >>> 3; - const bit = bits[bitOffset]; - if (bit !== 0 && bit !== 1) { - throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`); - } - if (bit === 0) - continue; - const shift = 7 - bitOffset % 8; - bytes[byteOffset + 2] |= bit << shift; - } - return new this(bytes, Binary.SUBTYPE_VECTOR); + if (error91 instanceof MongoNetworkError) { + return true; + } + const isNotWritablePrimaryError2 = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error91.message); + if (isNotWritablePrimaryError2) { + return true; + } + const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error91.message); + if (isNodeIsRecoveringError) { + return true; } + return false; } - Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; - Binary.BUFFER_SIZE = 256; - Binary.SUBTYPE_DEFAULT = 0; - Binary.SUBTYPE_FUNCTION = 1; - Binary.SUBTYPE_BYTE_ARRAY = 2; - Binary.SUBTYPE_UUID_OLD = 3; - Binary.SUBTYPE_UUID = 4; - Binary.SUBTYPE_MD5 = 5; - Binary.SUBTYPE_ENCRYPTED = 6; - Binary.SUBTYPE_COLUMN = 7; - Binary.SUBTYPE_SENSITIVE = 8; - Binary.SUBTYPE_VECTOR = 9; - Binary.SUBTYPE_USER_DEFINED = 128; - Binary.VECTOR_TYPE = Object.freeze({ - Int8: 3, - Float32: 39, - PackedBit: 16 - }); - function validateBinaryVector(vector) { - if (vector.sub_type !== Binary.SUBTYPE_VECTOR) - return; - const size = vector.position; - const datatype = vector.buffer[0]; - const padding = vector.buffer[1]; - if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) && padding !== 0) { - throw new BSONError("Invalid Vector: padding must be zero for int8 and float32 vectors"); + var SDAM_RECOVERING_CODES = new Set([ + exports.MONGODB_ERROR_CODES.ShutdownInProgress, + exports.MONGODB_ERROR_CODES.PrimarySteppedDown, + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, + exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary + ]); + var SDAM_NOT_PRIMARY_CODES = new Set([ + exports.MONGODB_ERROR_CODES.NotWritablePrimary, + exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, + exports.MONGODB_ERROR_CODES.LegacyNotPrimary + ]); + var SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, + exports.MONGODB_ERROR_CODES.ShutdownInProgress + ]); + function isRecoveringError(err) { + if (typeof err.code === "number") { + return SDAM_RECOVERING_CODES.has(err.code); } - if (datatype === Binary.VECTOR_TYPE.Float32) { - if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) { - throw new BSONError("Invalid Vector: Float32 vector must contain a multiple of 4 bytes"); - } + return exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message); + } + function isNotWritablePrimaryError(err) { + if (typeof err.code === "number") { + return SDAM_NOT_PRIMARY_CODES.has(err.code); } - if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) { - throw new BSONError("Invalid Vector: padding must be zero for packed bit vectors that are empty"); + if (isRecoveringError(err)) { + return false; } - if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) { - throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`); + return exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); + } + function isNodeShuttingDownError(err) { + return !!(typeof err.code === "number" && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); + } + function isSDAMUnrecoverableError(error91) { + if (error91 instanceof MongoParseError || error91 == null) { + return true; } + return isRecoveringError(error91) || isNotWritablePrimaryError(error91); } - var UUID_BYTE_LENGTH = 16; - var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i; - var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; - - class UUID2 extends Binary { - constructor(input) { - let bytes; - if (input == null) { - bytes = UUID2.generate(); - } else if (input instanceof UUID2) { - bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); - } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { - bytes = ByteUtils.toLocalBufferType(input); - } else if (typeof input === "string") { - bytes = UUID2.bytesFromString(input); - } else { - throw new BSONError("Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."); - } - super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + function isNetworkTimeoutError(err) { + return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); + } + function isResumableError(error91, wireVersion) { + if (error91 == null || !(error91 instanceof MongoError)) { + return false; } - get id() { - return this.buffer; + if (error91 instanceof MongoNetworkError) { + return true; } - set id(value) { - this.buffer = value; + if (error91 instanceof MongoServerSelectionError) { + return true; } - toHexString(includeDashes = true) { - if (includeDashes) { - return [ - ByteUtils.toHex(this.buffer.subarray(0, 4)), - ByteUtils.toHex(this.buffer.subarray(4, 6)), - ByteUtils.toHex(this.buffer.subarray(6, 8)), - ByteUtils.toHex(this.buffer.subarray(8, 10)), - ByteUtils.toHex(this.buffer.subarray(10, 16)) - ].join("-"); + if (wireVersion != null && wireVersion >= 9) { + if (error91.code === exports.MONGODB_ERROR_CODES.CursorNotFound) { + return true; } - return ByteUtils.toHex(this.buffer); - } - toString(encoding) { - if (encoding === "hex") - return ByteUtils.toHex(this.id); - if (encoding === "base64") - return ByteUtils.toBase64(this.id); - return this.toHexString(); + return error91.hasErrorLabel(exports.MongoErrorLabel.ResumableChangeStreamError); } - toJSON() { - return this.toHexString(); + if (typeof error91.code === "number") { + return exports.GET_MORE_RESUMABLE_CODES.has(error91.code); } - equals(otherId) { - if (!otherId) { - return false; + return false; + } +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/read_preference.js +var require_read_preference = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ReadPreference = exports.ReadPreferenceMode = undefined; + var error_1 = require_error2(); + exports.ReadPreferenceMode = Object.freeze({ + primary: "primary", + primaryPreferred: "primaryPreferred", + secondary: "secondary", + secondaryPreferred: "secondaryPreferred", + nearest: "nearest" + }); + + class ReadPreference { + constructor(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); } - if (otherId instanceof UUID2) { - return ByteUtils.equals(otherId.id, this.id); + if (options == null && typeof tags === "object" && !Array.isArray(tags)) { + options = tags; + tags = undefined; + } else if (tags && !Array.isArray(tags)) { + throw new error_1.MongoInvalidArgumentError("ReadPreference tags must be an array"); } - try { - return ByteUtils.equals(new UUID2(otherId).id, this.id); - } catch { - return false; + this.mode = mode; + this.tags = tags; + this.hedge = options?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = options ?? {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new error_1.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer"); + } + this.maxStalenessSeconds = options.maxStalenessSeconds; + this.minWireVersion = 5; + } + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with tags"); + } + if (this.maxStalenessSeconds) { + throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds"); + } + if (this.hedge) { + throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge"); + } } } - toBinary() { - return new Binary(this.id, Binary.SUBTYPE_UUID); + get preference() { + return this.mode; } - static generate() { - const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - return bytes; + static fromString(mode) { + return new ReadPreference(mode); } - static isValid(input) { - if (!input) { - return false; + static fromOptions(options) { + if (!options) + return; + const readPreference = options.readPreference ?? options.session?.transaction.options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + if (readPreference == null) { + return; } - if (typeof input === "string") { - return UUID2.isValidUUIDString(input); + if (typeof readPreference === "string") { + return new ReadPreference(readPreference, readPreferenceTags, { + maxStalenessSeconds: options.maxStalenessSeconds, + hedge: options.hedge + }); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === "object") { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === "string") { + return new ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds, + hedge: options.hedge + }); + } } - if (isUint8Array(input)) { - return input.byteLength === UUID_BYTE_LENGTH; + if (readPreferenceTags) { + readPreference.tags = readPreferenceTags; } - return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16; - } - static createFromHexString(hexString) { - const buffer2 = UUID2.bytesFromString(hexString); - return new UUID2(buffer2); - } - static createFromBase64(base647) { - return new UUID2(ByteUtils.fromBase64(base647)); + return readPreference; } - static bytesFromString(representation) { - if (!UUID2.isValidUUIDString(representation)) { - throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation"); + static translate(options) { + if (options.readPreference == null) + return options; + const r2 = options.readPreference; + if (typeof r2 === "string") { + options.readPreference = new ReadPreference(r2); + } else if (r2 && !(r2 instanceof ReadPreference) && typeof r2 === "object") { + const mode = r2.mode || r2.preference; + if (mode && typeof mode === "string") { + options.readPreference = new ReadPreference(mode, r2.tags, { + maxStalenessSeconds: r2.maxStalenessSeconds + }); + } + } else if (!(r2 instanceof ReadPreference)) { + throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r2}`); } - return ByteUtils.fromHex(representation.replace(/-/g, "")); + return options; } - static isValidUUIDString(representation) { - return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation); + static isValid(mode) { + const VALID_MODES = new Set([ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null + ]); + return VALID_MODES.has(mode); } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - return `new UUID(${inspect(this.toHexString(), options)})`; + isValid(mode) { + return ReadPreference.isValid(typeof mode === "string" ? mode : this.mode); } - } - - class Code extends BSONValue { - get _bsontype() { - return "Code"; + secondaryOk() { + const NEEDS_SECONDARYOK = new Set([ + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST + ]); + return NEEDS_SECONDARYOK.has(this.mode); } - constructor(code, scope) { - super(); - this.code = code.toString(); - this.scope = scope ?? null; + equals(readPreference) { + return readPreference.mode === this.mode; } toJSON() { - if (this.scope != null) { - return { code: this.code, scope: this.scope }; - } - return { code: this.code }; - } - toExtendedJSON() { - if (this.scope) { - return { $code: this.code, $scope: this.scope }; - } - return { $code: this.code }; - } - static fromExtendedJSON(doc3) { - return new Code(doc3.$code, doc3.$scope); + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) + readPreference.tags = this.tags; + if (this.maxStalenessSeconds) + readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + if (this.hedge) + readPreference.hedge = this.hedge; + return readPreference; } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - let parametersString = inspect(this.code, options); - const multiLineFn = parametersString.includes(` -`); - if (this.scope != null) { - parametersString += `,${multiLineFn ? ` -` : " "}${inspect(this.scope, options)}`; + } + exports.ReadPreference = ReadPreference; + ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; + ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; + ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; + ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; + ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; + ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); + ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); + ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); + ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); + ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sdam/common.js +var require_common4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = undefined; + exports._advanceClusterTime = _advanceClusterTime; + exports.STATE_CLOSING = "closing"; + exports.STATE_CLOSED = "closed"; + exports.STATE_CONNECTING = "connecting"; + exports.STATE_CONNECTED = "connected"; + exports.TopologyType = Object.freeze({ + Single: "Single", + ReplicaSetNoPrimary: "ReplicaSetNoPrimary", + ReplicaSetWithPrimary: "ReplicaSetWithPrimary", + Sharded: "Sharded", + Unknown: "Unknown", + LoadBalanced: "LoadBalanced" + }); + exports.ServerType = Object.freeze({ + Standalone: "Standalone", + Mongos: "Mongos", + PossiblePrimary: "PossiblePrimary", + RSPrimary: "RSPrimary", + RSSecondary: "RSSecondary", + RSArbiter: "RSArbiter", + RSOther: "RSOther", + RSGhost: "RSGhost", + Unknown: "Unknown", + LoadBalancer: "LoadBalancer" + }); + function _advanceClusterTime(entity, $clusterTime) { + if (entity.clusterTime == null) { + entity.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { + entity.clusterTime = $clusterTime; } - const endingNewline = multiLineFn && this.scope === null; - return `new Code(${multiLineFn ? ` -` : ""}${parametersString}${endingNewline ? ` -` : ""})`; } } - function isDBRefLike(value) { - return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || ("$db" in value) && typeof value.$db === "string"); - } +}); - class DBRef extends BSONValue { - get _bsontype() { - return "DBRef"; +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sdam/server_selection.js +var require_server_selection = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MIN_SECONDARY_WRITE_WIRE_VERSION = undefined; + exports.writableServerSelector = writableServerSelector; + exports.sameServerSelector = sameServerSelector; + exports.secondaryWritableServerSelector = secondaryWritableServerSelector; + exports.readPreferenceServerSelector = readPreferenceServerSelector; + var error_1 = require_error2(); + var read_preference_1 = require_read_preference(); + var common_1 = require_common4(); + var IDLE_WRITE_PERIOD = 1e4; + var SMALLEST_MAX_STALENESS_SECONDS = 90; + exports.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; + function writableServerSelector() { + return function writableServer(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); + }; + } + function sameServerSelector(description) { + return function sameServerSelector2(topologyDescription, servers) { + if (!description) + return []; + return servers.filter((sd) => { + return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; + }); + }; + } + function secondaryWritableServerSelector(wireVersion, readPreference) { + if (!readPreference || !wireVersion || wireVersion && wireVersion < exports.MIN_SECONDARY_WRITE_WIRE_VERSION) { + return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); } - constructor(collection, oid, db, fields) { - super(); - const parts = collection.split("."); - if (parts.length === 2) { - db = parts.shift(); - collection = parts.shift(); - } - this.collection = collection; - this.oid = oid; - this.db = db; - this.fields = fields || {}; + return readPreferenceServerSelector(readPreference); + } + function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; } - get namespace() { - return this.collection; + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); } - set namespace(value) { - this.collection = value; + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); } - toJSON() { - const o2 = Object.assign({ - $ref: this.collection, - $id: this.oid - }, this.fields); - if (this.db != null) - o2.$db = this.db; - return o2; + if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { + const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = server.lastUpdateTime - server.lastWriteDate - (primary.lastUpdateTime - primary.lastWriteDate) + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); } - toExtendedJSON(options) { - options = options || {}; - let o2 = { - $ref: this.collection, - $id: this.oid - }; - if (options.legacy) { - return o2; + if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { + if (servers.length === 0) { + return servers; } - if (this.db) - o2.$db = this.db; - o2 = Object.assign(o2, this.fields); - return o2; - } - static fromExtendedJSON(doc3) { - const copy = Object.assign({}, doc3); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(doc3.$ref, doc3.$id, doc3.$db, copy); - } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - const args = [ - inspect(this.namespace, options), - inspect(this.oid, options), - ...this.db ? [inspect(this.db, options)] : [], - ...Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : [] - ]; - args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1]; - return `new DBRef(${args.join(", ")})`; + const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); + return servers.reduce((result, server) => { + const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + const staleness = stalenessMS / 1000; + const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; + if (staleness <= maxStalenessSeconds) { + result.push(server); + } + return result; + }, []); } + return servers; } - function removeLeadingZerosAndExplicitPlus(str) { - if (str === "") { - return str; - } - let startIndex = 0; - const isNegative = str[startIndex] === "-"; - const isExplicitlyPositive = str[startIndex] === "+"; - if (isExplicitlyPositive || isNegative) { - startIndex += 1; + function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i2 = 0;i2 < keys.length; ++i2) { + const key = keys[i2]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } } - let foundInsignificantZero = false; - for (;startIndex < str.length && str[startIndex] === "0"; ++startIndex) { - foundInsignificantZero = true; + return true; + } + function tagSetReducer(readPreference, servers) { + if (readPreference.tags == null || Array.isArray(readPreference.tags) && readPreference.tags.length === 0) { + return servers; } - if (!foundInsignificantZero) { - return isExplicitlyPositive ? str.slice(1) : str; + for (let i2 = 0;i2 < readPreference.tags.length; ++i2) { + const tagSet = readPreference.tags[i2]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) + matched.push(server); + return matched; + }, []); + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } } - return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`; + return []; } - function validateStringCharacters(str, radix) { - radix = radix ?? 10; - const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix); - const regex2 = new RegExp(`[^-+${validCharacters}]`, "i"); - return regex2.test(str) ? false : str; + function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce((min, server) => Math.min(server.roundTripTime, min), Infinity); + const high = low + topologyDescription.localThresholdMS; + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) + result.push(server); + return result; + }, []); } - var wasm = undefined; - try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; - } catch {} - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - var INT_CACHE = {}; - var UINT_CACHE = {}; - var MAX_INT64_STRING_LENGTH = 20; - var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; - - class Long extends BSONValue { - get _bsontype() { - return "Long"; - } - get __isLong__() { - return true; - } - constructor(lowOrValue = 0, highOrUnsigned, unsigned) { - super(); - const unsignedBool = typeof highOrUnsigned === "boolean" ? highOrUnsigned : Boolean(unsigned); - const high = typeof highOrUnsigned === "number" ? highOrUnsigned : 0; - const res = typeof lowOrValue === "string" ? Long.fromString(lowOrValue, unsignedBool) : typeof lowOrValue === "bigint" ? Long.fromBigInt(lowOrValue, unsignedBool) : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool }; - this.low = res.low; - this.high = res.high; - this.unsigned = res.unsigned; - } - static fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - static fromInt(value, unsigned) { - let obj, cachedObj, cache2; - if (unsigned) { - value >>>= 0; - if (cache2 = 0 <= value && value < 256) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache2) - UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache2 = -128 <= value && value < 128) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = Long.fromBits(value, value < 0 ? -1 : 0, false); - if (cache2) - INT_CACHE[value] = obj; - return obj; - } + function primaryFilter(server) { + return server.type === common_1.ServerType.RSPrimary; + } + function secondaryFilter(server) { + return server.type === common_1.ServerType.RSSecondary; + } + function nearestFilter(server) { + return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; + } + function knownFilter(server) { + return server.type !== common_1.ServerType.Unknown; + } + function loadBalancerFilter(server) { + return server.type === common_1.ServerType.LoadBalancer; + } + function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new error_1.MongoInvalidArgumentError("Invalid read preference specified"); } - static fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? Long.UZERO : Long.ZERO; - if (unsigned) { - if (value < 0) - return Long.UZERO; - if (value >= TWO_PWR_64_DBL) - return Long.MAX_UNSIGNED_VALUE; - } else { - if (value <= -9223372036854776000) - return Long.MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return Long.MAX_VALUE; + return function readPreferenceServers(topologyDescription, servers, deprioritized = []) { + if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { + return servers.filter(loadBalancerFilter); } - if (value < 0) - return Long.fromNumber(-value, unsigned).neg(); - return Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); - } - static fromBigInt(value, unsigned) { - const FROM_BIGINT_BIT_MASK = BigInt(4294967295); - const FROM_BIGINT_BIT_SHIFT = BigInt(32); - return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number(value >> FROM_BIGINT_BIT_SHIFT & FROM_BIGINT_BIT_MASK), unsigned); - } - static _fromString(str, unsigned, radix) { - if (str.length === 0) - throw new BSONError("empty string"); - if (radix < 2 || 36 < radix) - throw new BSONError("radix"); - let p2; - if ((p2 = str.indexOf("-")) > 0) - throw new BSONError("interior hyphen"); - else if (p2 === 0) { - return Long._fromString(str.substring(1), unsigned, radix).neg(); + if (topologyDescription.type === common_1.TopologyType.Unknown) { + return []; } - const radixToPower = Long.fromNumber(Math.pow(radix, 8)); - let result = Long.ZERO; - for (let i2 = 0;i2 < str.length; i2 += 8) { - const size = Math.min(8, str.length - i2), value = parseInt(str.substring(i2, i2 + size), radix); - if (size < 8) { - const power = Long.fromNumber(Math.pow(radix, size)); - result = result.mul(power).add(Long.fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(Long.fromNumber(value)); - } + if (topologyDescription.type === common_1.TopologyType.Single) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); } - result.unsigned = unsigned; - return result; - } - static fromStringStrict(str, unsignedOrRadix, radix) { - let unsigned = false; - if (typeof unsignedOrRadix === "number") { - radix = unsignedOrRadix, unsignedOrRadix = false; - } else { - unsigned = !!unsignedOrRadix; + if (topologyDescription.type === common_1.TopologyType.Sharded) { + const filtered = servers.filter((server) => { + return !deprioritized.includes(server); + }); + const selectable = filtered.length > 0 ? filtered : deprioritized; + return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter)); } - radix ??= 10; - if (str.trim() !== str) { - throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`); + const mode = readPreference.mode; + if (mode === read_preference_1.ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); } - if (!validateStringCharacters(str, radix)) { - throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`); + if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } } - const cleanedStr = removeLeadingZerosAndExplicitPlus(str); - const result = Long._fromString(cleanedStr, unsigned, radix); - if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) { - throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`); + const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; + const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); + if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { + return servers.filter(primaryFilter); } - return result; + return selectedServers; + }; + } +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/constants.js +var require_constants5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_DELETE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = exports.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = exports.MIN_SUPPORTED_QE_SERVER_VERSION = exports.MIN_SUPPORTED_QE_WIRE_VERSION = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = undefined; + exports.MIN_SUPPORTED_SERVER_VERSION = "4.2"; + exports.MAX_SUPPORTED_SERVER_VERSION = "8.2"; + exports.MIN_SUPPORTED_WIRE_VERSION = 8; + exports.MAX_SUPPORTED_WIRE_VERSION = 27; + exports.MIN_SUPPORTED_QE_WIRE_VERSION = 21; + exports.MIN_SUPPORTED_QE_SERVER_VERSION = "7.0"; + exports.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = 27; + exports.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = "8.2"; + exports.OP_REPLY = 1; + exports.OP_UPDATE = 2001; + exports.OP_INSERT = 2002; + exports.OP_QUERY = 2004; + exports.OP_DELETE = 2006; + exports.OP_COMPRESSED = 2012; + exports.OP_MSG = 2013; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/constants.js +var require_constants6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.END = exports.CHANGE = exports.INIT = exports.MORE = exports.RESPONSE = exports.SERVER_HEARTBEAT_FAILED = exports.SERVER_HEARTBEAT_SUCCEEDED = exports.SERVER_HEARTBEAT_STARTED = exports.COMMAND_FAILED = exports.COMMAND_SUCCEEDED = exports.COMMAND_STARTED = exports.CLUSTER_TIME_RECEIVED = exports.CONNECTION_CHECKED_IN = exports.CONNECTION_CHECKED_OUT = exports.CONNECTION_CHECK_OUT_FAILED = exports.CONNECTION_CHECK_OUT_STARTED = exports.CONNECTION_CLOSED = exports.CONNECTION_READY = exports.CONNECTION_CREATED = exports.CONNECTION_POOL_READY = exports.CONNECTION_POOL_CLEARED = exports.CONNECTION_POOL_CLOSED = exports.CONNECTION_POOL_CREATED = exports.WAITING_FOR_SUITABLE_SERVER = exports.SERVER_SELECTION_SUCCEEDED = exports.SERVER_SELECTION_FAILED = exports.SERVER_SELECTION_STARTED = exports.TOPOLOGY_DESCRIPTION_CHANGED = exports.TOPOLOGY_CLOSED = exports.TOPOLOGY_OPENING = exports.SERVER_DESCRIPTION_CHANGED = exports.SERVER_CLOSED = exports.SERVER_OPENING = exports.DESCRIPTION_RECEIVED = exports.UNPINNED = exports.PINNED = exports.MESSAGE = exports.ENDED = exports.CLOSED = exports.CONNECT = exports.OPEN = exports.CLOSE = exports.TIMEOUT = exports.ERROR = exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = undefined; + exports.kDecoratedKeys = exports.kDecorateResult = exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = undefined; + exports.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; + exports.SYSTEM_INDEX_COLLECTION = "system.indexes"; + exports.SYSTEM_PROFILE_COLLECTION = "system.profile"; + exports.SYSTEM_USER_COLLECTION = "system.users"; + exports.SYSTEM_COMMAND_COLLECTION = "$cmd"; + exports.SYSTEM_JS_COLLECTION = "system.js"; + exports.ERROR = "error"; + exports.TIMEOUT = "timeout"; + exports.CLOSE = "close"; + exports.OPEN = "open"; + exports.CONNECT = "connect"; + exports.CLOSED = "closed"; + exports.ENDED = "ended"; + exports.MESSAGE = "message"; + exports.PINNED = "pinned"; + exports.UNPINNED = "unpinned"; + exports.DESCRIPTION_RECEIVED = "descriptionReceived"; + exports.SERVER_OPENING = "serverOpening"; + exports.SERVER_CLOSED = "serverClosed"; + exports.SERVER_DESCRIPTION_CHANGED = "serverDescriptionChanged"; + exports.TOPOLOGY_OPENING = "topologyOpening"; + exports.TOPOLOGY_CLOSED = "topologyClosed"; + exports.TOPOLOGY_DESCRIPTION_CHANGED = "topologyDescriptionChanged"; + exports.SERVER_SELECTION_STARTED = "serverSelectionStarted"; + exports.SERVER_SELECTION_FAILED = "serverSelectionFailed"; + exports.SERVER_SELECTION_SUCCEEDED = "serverSelectionSucceeded"; + exports.WAITING_FOR_SUITABLE_SERVER = "waitingForSuitableServer"; + exports.CONNECTION_POOL_CREATED = "connectionPoolCreated"; + exports.CONNECTION_POOL_CLOSED = "connectionPoolClosed"; + exports.CONNECTION_POOL_CLEARED = "connectionPoolCleared"; + exports.CONNECTION_POOL_READY = "connectionPoolReady"; + exports.CONNECTION_CREATED = "connectionCreated"; + exports.CONNECTION_READY = "connectionReady"; + exports.CONNECTION_CLOSED = "connectionClosed"; + exports.CONNECTION_CHECK_OUT_STARTED = "connectionCheckOutStarted"; + exports.CONNECTION_CHECK_OUT_FAILED = "connectionCheckOutFailed"; + exports.CONNECTION_CHECKED_OUT = "connectionCheckedOut"; + exports.CONNECTION_CHECKED_IN = "connectionCheckedIn"; + exports.CLUSTER_TIME_RECEIVED = "clusterTimeReceived"; + exports.COMMAND_STARTED = "commandStarted"; + exports.COMMAND_SUCCEEDED = "commandSucceeded"; + exports.COMMAND_FAILED = "commandFailed"; + exports.SERVER_HEARTBEAT_STARTED = "serverHeartbeatStarted"; + exports.SERVER_HEARTBEAT_SUCCEEDED = "serverHeartbeatSucceeded"; + exports.SERVER_HEARTBEAT_FAILED = "serverHeartbeatFailed"; + exports.RESPONSE = "response"; + exports.MORE = "more"; + exports.INIT = "init"; + exports.CHANGE = "change"; + exports.END = "end"; + exports.RESUME_TOKEN_CHANGED = "resumeTokenChanged"; + exports.HEARTBEAT_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED + ]); + exports.CMAP_EVENTS = Object.freeze([ + exports.CONNECTION_POOL_CREATED, + exports.CONNECTION_POOL_READY, + exports.CONNECTION_POOL_CLEARED, + exports.CONNECTION_POOL_CLOSED, + exports.CONNECTION_CREATED, + exports.CONNECTION_READY, + exports.CONNECTION_CLOSED, + exports.CONNECTION_CHECK_OUT_STARTED, + exports.CONNECTION_CHECK_OUT_FAILED, + exports.CONNECTION_CHECKED_OUT, + exports.CONNECTION_CHECKED_IN + ]); + exports.TOPOLOGY_EVENTS = Object.freeze([ + exports.SERVER_OPENING, + exports.SERVER_CLOSED, + exports.SERVER_DESCRIPTION_CHANGED, + exports.TOPOLOGY_OPENING, + exports.TOPOLOGY_CLOSED, + exports.TOPOLOGY_DESCRIPTION_CHANGED, + exports.ERROR, + exports.TIMEOUT, + exports.CLOSE + ]); + exports.APM_EVENTS = Object.freeze([ + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED + ]); + exports.SERVER_RELAY_EVENTS = Object.freeze([ + exports.SERVER_HEARTBEAT_STARTED, + exports.SERVER_HEARTBEAT_SUCCEEDED, + exports.SERVER_HEARTBEAT_FAILED, + exports.COMMAND_STARTED, + exports.COMMAND_SUCCEEDED, + exports.COMMAND_FAILED, + ...exports.CMAP_EVENTS + ]); + exports.LOCAL_SERVER_EVENTS = Object.freeze([ + exports.CONNECT, + exports.DESCRIPTION_RECEIVED, + exports.CLOSED, + exports.ENDED + ]); + exports.MONGO_CLIENT_EVENTS = Object.freeze([ + ...exports.CMAP_EVENTS, + ...exports.APM_EVENTS, + ...exports.TOPOLOGY_EVENTS, + ...exports.HEARTBEAT_EVENTS + ]); + exports.LEGACY_HELLO_COMMAND = "ismaster"; + exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster"; + exports.kDecorateResult = Symbol.for("@@mdb.decorateDecryptionResult"); + exports.kDecoratedKeys = Symbol.for("@@mdb.decryptedKeys"); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/read_concern.js +var require_read_concern = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ReadConcern = exports.ReadConcernLevel = undefined; + exports.ReadConcernLevel = Object.freeze({ + local: "local", + majority: "majority", + linearizable: "linearizable", + available: "available", + snapshot: "snapshot" + }); + + class ReadConcern { + constructor(level) { + this.level = exports.ReadConcernLevel[level] ?? level; } - static fromString(str, unsignedOrRadix, radix) { - let unsigned = false; - if (typeof unsignedOrRadix === "number") { - radix = unsignedOrRadix, unsignedOrRadix = false; - } else { - unsigned = !!unsignedOrRadix; + static fromOptions(options) { + if (options == null) { + return; } - radix ??= 10; - if (str === "NaN" && radix < 24) { - return Long.ZERO; - } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) { - return Long.ZERO; + if (options.readConcern) { + const { readConcern } = options; + if (readConcern instanceof ReadConcern) { + return readConcern; + } else if (typeof readConcern === "string") { + return new ReadConcern(readConcern); + } else if ("level" in readConcern && readConcern.level) { + return new ReadConcern(readConcern.level); + } } - return Long._fromString(str, unsigned, radix); - } - static fromBytes(bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); - } - static fromBytesLE(bytes, unsigned) { - return new Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); + if (options.level) { + return new ReadConcern(options.level); + } + return; } - static fromBytesBE(bytes, unsigned) { - return new Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); + static get MAJORITY() { + return exports.ReadConcernLevel.majority; } - static isLong(value) { - return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true; + static get AVAILABLE() { + return exports.ReadConcernLevel.available; } - static fromValue(val, unsigned) { - if (typeof val === "number") - return Long.fromNumber(val, unsigned); - if (typeof val === "string") - return Long.fromString(val, unsigned); - return Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); + static get LINEARIZABLE() { + return exports.ReadConcernLevel.linearizable; } - add(addend) { - if (!Long.isLong(addend)) - addend = Long.fromValue(addend); - const a48 = this.high >>> 16; - const a32 = this.high & 65535; - const a16 = this.low >>> 16; - const a00 = this.low & 65535; - const b48 = addend.high >>> 16; - const b32 = addend.high & 65535; - const b16 = addend.low >>> 16; - const b00 = addend.low & 65535; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 + b48; - c48 &= 65535; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + static get SNAPSHOT() { + return exports.ReadConcernLevel.snapshot; } - and(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + toJSON() { + return { level: this.level }; } - compare(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.eq(other)) - return 0; - const thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; + } + exports.ReadConcern = ReadConcern; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js +var require_document = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OnDemandDocument = undefined; + var bson_1 = require_bson2(); + var BSONElementOffset = { + type: 0, + nameOffset: 1, + nameLength: 2, + offset: 3, + length: 4 + }; + + class OnDemandDocument { + constructor(bson, offset = 0, isArray3 = false, elements) { + this.cache = Object.create(null); + this.indexFound = Object.create(null); + this.bson = bson; + this.offset = offset; + this.isArray = isArray3; + this.elements = elements ?? (0, bson_1.parseToElementsToArray)(this.bson, offset); } - comp(other) { - return this.compare(other); + isElementName(name, element) { + const nameLength = element[BSONElementOffset.nameLength]; + const nameOffset = element[BSONElementOffset.nameOffset]; + if (name.length !== nameLength) + return false; + const nameEnd = nameOffset + nameLength; + for (let byteIndex = nameOffset, charIndex = 0;charIndex < name.length && byteIndex < nameEnd; charIndex++, byteIndex++) { + if (this.bson[byteIndex] !== name.charCodeAt(charIndex)) + return false; + } + return true; } - divide(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (divisor.isZero()) - throw new BSONError("division by zero"); - if (wasm) { - if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { - return this; + getElement(name) { + const cachedElement = this.cache[name]; + if (cachedElement === false) + return null; + if (cachedElement != null) { + return cachedElement; + } + if (typeof name === "number") { + if (this.isArray) { + if (name < this.elements.length) { + const element = this.elements[name]; + const cachedElement2 = { element, value: undefined }; + this.cache[name] = cachedElement2; + this.indexFound[name] = true; + return cachedElement2; + } else { + return null; + } + } else { + return null; } - const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); } - if (this.isZero()) - return this.unsigned ? Long.UZERO : Long.ZERO; - let approx, rem, res; - if (!this.unsigned) { - if (this.eq(Long.MIN_VALUE)) { - if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) - return Long.MIN_VALUE; - else if (divisor.eq(Long.MIN_VALUE)) - return Long.ONE; - else { - const halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(Long.ZERO)) { - return divisor.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } + for (let index2 = 0;index2 < this.elements.length; index2++) { + const element = this.elements[index2]; + if (!(index2 in this.indexFound) && this.isElementName(name, element)) { + const cachedElement2 = { element, value: undefined }; + this.cache[name] = cachedElement2; + this.indexFound[index2] = true; + return cachedElement2; + } + } + this.cache[name] = false; + return null; + } + toJSValue(element, as) { + const type = element[BSONElementOffset.type]; + const offset = element[BSONElementOffset.offset]; + const length = element[BSONElementOffset.length]; + if (as !== type) { + return null; + } + switch (as) { + case bson_1.BSONType.null: + case bson_1.BSONType.undefined: + return null; + case bson_1.BSONType.double: + return (0, bson_1.getFloat64LE)(this.bson, offset); + case bson_1.BSONType.int: + return (0, bson_1.getInt32LE)(this.bson, offset); + case bson_1.BSONType.long: + return (0, bson_1.getBigInt64LE)(this.bson, offset); + case bson_1.BSONType.bool: + return Boolean(this.bson[offset]); + case bson_1.BSONType.objectId: + return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12)); + case bson_1.BSONType.timestamp: + return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset)); + case bson_1.BSONType.string: + return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false); + case bson_1.BSONType.binData: { + const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset); + const subType = this.bson[offset + 4]; + if (subType === 2) { + const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4); + if (subType2BinarySize < 0) + throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02"); + if (subType2BinarySize > totalBinarySize - 4) + throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size"); + if (subType2BinarySize < totalBinarySize - 4) + throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size"); + return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2); } - } else if (divisor.eq(Long.MIN_VALUE)) - return this.unsigned ? Long.UZERO : Long.ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = Long.ZERO; - } else { - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return Long.UZERO; - if (divisor.gt(this.shru(1))) - return Long.UONE; - res = Long.UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - const log2 = Math.ceil(Math.log(approx) / Math.LN2); - const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - let approxRes = Long.fromNumber(approx); - let approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); + return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType); } - if (approxRes.isZero()) - approxRes = Long.ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); + case bson_1.BSONType.date: + return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset))); + case bson_1.BSONType.object: + return new OnDemandDocument(this.bson, offset); + case bson_1.BSONType.array: + return new OnDemandDocument(this.bson, offset, true); + default: + throw new bson_1.BSONError(`Unsupported BSON type: ${as}`); } - return res; } - div(divisor) { - return this.divide(divisor); + size() { + return this.elements.length; } - equals(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + has(name) { + const cachedElement = this.cache[name]; + if (cachedElement === false) return false; - return this.high === other.high && this.low === other.low; - } - eq(other) { - return this.equals(other); - } - getHighBits() { - return this.high; - } - getHighBitsUnsigned() { - return this.high >>> 0; - } - getLowBits() { - return this.low; - } - getLowBitsUnsigned() { - return this.low >>> 0; + if (cachedElement != null) + return true; + return this.getElement(name) != null; } - getNumBitsAbs() { - if (this.isNegative()) { - return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + get(name, as, required3) { + const element = this.getElement(name); + if (element == null) { + if (required3 === true) { + throw new bson_1.BSONError(`BSON element "${name}" is missing`); + } else { + return null; + } } - const val = this.high !== 0 ? this.high : this.low; - let bit; - for (bit = 31;bit > 0; bit--) - if ((val & 1 << bit) !== 0) - break; - return this.high !== 0 ? bit + 33 : bit + 1; - } - greaterThan(other) { - return this.comp(other) > 0; - } - gt(other) { - return this.greaterThan(other); + if (element.value == null) { + const value = this.toJSValue(element.element, as); + if (value == null) { + if (required3 === true) { + throw new bson_1.BSONError(`BSON element "${name}" is missing`); + } else { + return null; + } + } + element.value = value; + } + return element.value; } - greaterThanOrEqual(other) { - return this.comp(other) >= 0; + getNumber(name, required3) { + const maybeBool = this.get(name, bson_1.BSONType.bool); + const bool = maybeBool == null ? null : maybeBool ? 1 : 0; + const maybeLong = this.get(name, bson_1.BSONType.long); + const long = maybeLong == null ? null : Number(maybeLong); + const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double); + if (required3 === true && result == null) { + throw new bson_1.BSONError(`BSON element "${name}" is missing`); + } + return result; } - gte(other) { - return this.greaterThanOrEqual(other); + toObject(options) { + return (0, bson_1.deserialize)(this.bson, { + ...options, + index: this.offset, + allowObjectSmallerThanBufferSize: true + }); } - ge(other) { - return this.greaterThanOrEqual(other); + toBytes() { + const size = (0, bson_1.getInt32LE)(this.bson, this.offset); + return this.bson.subarray(this.offset, this.offset + size); } - isEven() { - return (this.low & 1) === 0; + } + exports.OnDemandDocument = OnDemandDocument; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/responses.js +var require_responses = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClientBulkWriteCursorResponse = exports.ExplainedCursorResponse = exports.CursorResponse = exports.MongoDBResponse = undefined; + exports.isErrorResponse = isErrorResponse; + var bson_1 = require_bson2(); + var error_1 = require_error2(); + var utils_1 = require_utils5(); + var document_1 = require_document(); + var BSONElementOffset = { + type: 0, + nameOffset: 1, + nameLength: 2, + offset: 3, + length: 4 + }; + function isErrorResponse(bson, elements) { + for (let eIdx = 0;eIdx < elements.length; eIdx++) { + const element = elements[eIdx]; + if (element[BSONElementOffset.nameLength] === 2) { + const nameOffset = element[BSONElementOffset.nameOffset]; + if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) { + const valueOffset = element[BSONElementOffset.offset]; + const valueLength = element[BSONElementOffset.length]; + for (let i2 = valueOffset;i2 < valueOffset + valueLength; i2++) { + if (bson[i2] !== 0) + return false; + } + return true; + } + } } - isNegative() { - return !this.unsigned && this.high < 0; + return true; + } + + class MongoDBResponse extends document_1.OnDemandDocument { + get(name, as, required3) { + try { + return super.get(name, as, required3); + } catch (cause) { + throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); + } } - isOdd() { - return (this.low & 1) === 1; + static is(value) { + return value instanceof MongoDBResponse; } - isPositive() { - return this.unsigned || this.high >= 0; + static make(bson) { + const elements = (0, bson_1.parseToElementsToArray)(bson, 0); + const isError5 = isErrorResponse(bson, elements); + return isError5 ? new MongoDBResponse(bson, 0, false, elements) : new this(bson, 0, false, elements); } - isZero() { - return this.high === 0 && this.low === 0; + get isMaxTimeExpiredError() { + const isTopLevel = this.ok === 0 && this.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; + if (isTopLevel) + return true; + if (this.ok === 0) + return false; + const isWriteConcern = this.get("writeConcernError", bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; + if (isWriteConcern) + return true; + const writeErrors = this.get("writeErrors", bson_1.BSONType.array); + if (writeErrors?.size()) { + for (let i2 = 0;i2 < writeErrors.size(); i2++) { + const isWriteError = writeErrors.get(i2, bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; + if (isWriteError) + return true; + } + } + return false; } - lessThan(other) { - return this.comp(other) < 0; + get recoveryToken() { + return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({ + promoteValues: false, + promoteLongs: false, + promoteBuffers: false, + validation: { utf8: true } + }) ?? null; } - lt(other) { - return this.lessThan(other); + get atClusterTime() { + return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp); } - lessThanOrEqual(other) { - return this.comp(other) <= 0; + get operationTime() { + return this.get("operationTime", bson_1.BSONType.timestamp); } - lte(other) { - return this.lessThanOrEqual(other); + get ok() { + return this.getNumber("ok") ? 1 : 0; } - modulo(divisor) { - if (!Long.isLong(divisor)) - divisor = Long.fromValue(divisor); - if (wasm) { - const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); + get $err() { + return this.get("$err", bson_1.BSONType.string); } - mod(divisor) { - return this.modulo(divisor); + get errmsg() { + return this.get("errmsg", bson_1.BSONType.string); } - rem(divisor) { - return this.modulo(divisor); + get code() { + return this.getNumber("code"); } - multiply(multiplier) { - if (this.isZero()) - return Long.ZERO; - if (!Long.isLong(multiplier)) - multiplier = Long.fromValue(multiplier); - if (wasm) { - const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return Long.fromBits(low, wasm.get_high(), this.unsigned); + get $clusterTime() { + if (!("clusterTime" in this)) { + const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object); + if (clusterTimeDoc == null) { + this.clusterTime = null; + return null; + } + const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true); + const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject(); + this.clusterTime = { clusterTime, signature }; } - if (multiplier.isZero()) - return Long.ZERO; - if (this.eq(Long.MIN_VALUE)) - return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (multiplier.eq(Long.MIN_VALUE)) - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) - return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - const a48 = this.high >>> 16; - const a32 = this.high & 65535; - const a16 = this.low >>> 16; - const a00 = this.low & 65535; - const b48 = multiplier.high >>> 16; - const b32 = multiplier.high & 65535; - const b16 = multiplier.low >>> 16; - const b00 = multiplier.low & 65535; - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 65535; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 65535; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + return this.clusterTime ?? null; } - mul(multiplier) { - return this.multiply(multiplier); + toObject(options) { + const exactBSONOptions = { + ...(0, bson_1.pluckBSONSerializeOptions)(options ?? {}), + validation: (0, bson_1.parseUtf8ValidationOption)(options) + }; + return super.toObject(exactBSONOptions); } - negate() { - if (!this.unsigned && this.eq(Long.MIN_VALUE)) - return Long.MIN_VALUE; - return this.not().add(Long.ONE); + } + exports.MongoDBResponse = MongoDBResponse; + MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0])); + + class CursorResponse extends MongoDBResponse { + constructor() { + super(...arguments); + this._batch = null; + this.iterated = 0; + this._encryptedBatch = null; } - neg() { - return this.negate(); + static get emptyGetMore() { + return new CursorResponse((0, bson_1.serialize)({ ok: 1, cursor: { id: 0n, nextBatch: [] } })); } - not() { - return Long.fromBits(~this.low, ~this.high, this.unsigned); + static is(value) { + return value instanceof CursorResponse || value === CursorResponse.emptyGetMore; } - notEquals(other) { - return !this.equals(other); + get cursor() { + return this.get("cursor", bson_1.BSONType.object, true); } - neq(other) { - return this.notEquals(other); + get id() { + try { + return bson_1.Long.fromBigInt(this.cursor.get("id", bson_1.BSONType.long, true)); + } catch (cause) { + throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); + } } - ne(other) { - return this.notEquals(other); + get ns() { + const namespace = this.cursor.get("ns", bson_1.BSONType.string); + if (namespace != null) + return (0, utils_1.ns)(namespace); + return null; } - or(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + get length() { + return Math.max(this.batchSize - this.iterated, 0); } - shiftLeft(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); + get encryptedBatch() { + if (this.encryptedResponse == null) + return null; + if (this._encryptedBatch != null) + return this._encryptedBatch; + const cursor = this.encryptedResponse?.get("cursor", bson_1.BSONType.object); + if (cursor?.has("firstBatch")) + this._encryptedBatch = cursor.get("firstBatch", bson_1.BSONType.array, true); + else if (cursor?.has("nextBatch")) + this._encryptedBatch = cursor.get("nextBatch", bson_1.BSONType.array, true); else - return Long.fromBits(0, this.low << numBits - 32, this.unsigned); - } - shl(numBits) { - return this.shiftLeft(numBits); + throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); + return this._encryptedBatch; } - shiftRight(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); + get batch() { + if (this._batch != null) + return this._batch; + const cursor = this.cursor; + if (cursor.has("firstBatch")) + this._batch = cursor.get("firstBatch", bson_1.BSONType.array, true); + else if (cursor.has("nextBatch")) + this._batch = cursor.get("nextBatch", bson_1.BSONType.array, true); else - return Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); + throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); + return this._batch; } - shr(numBits) { - return this.shiftRight(numBits); + get batchSize() { + return this.batch?.size(); } - shiftRightUnsigned(numBits) { - if (Long.isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - const high = this.high; - if (numBits < 32) { - const low = this.low; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); - } else if (numBits === 32) - return Long.fromBits(high, 0, this.unsigned); - else - return Long.fromBits(high >>> numBits - 32, 0, this.unsigned); + get postBatchResumeToken() { + return this.cursor.get("postBatchResumeToken", bson_1.BSONType.object)?.toObject({ + promoteValues: false, + promoteLongs: false, + promoteBuffers: false, + validation: { utf8: true } + }) ?? null; + } + shift(options) { + if (this.iterated >= this.batchSize) { + return null; + } + const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null; + const encryptedResult = this.encryptedBatch?.get(this.iterated, bson_1.BSONType.object, true) ?? null; + this.iterated += 1; + if (options?.raw) { + return result.toBytes(); + } else { + const object3 = result.toObject(options); + if (encryptedResult) { + (0, utils_1.decorateDecryptionResult)(object3, encryptedResult.toObject(options), true); + } + return object3; } } - shr_u(numBits) { - return this.shiftRightUnsigned(numBits); + clear() { + this.iterated = this.batchSize; } - shru(numBits) { - return this.shiftRightUnsigned(numBits); + } + exports.CursorResponse = CursorResponse; + + class ExplainedCursorResponse extends CursorResponse { + constructor() { + super(...arguments); + this.isExplain = true; + this._length = 1; } - subtract(subtrahend) { - if (!Long.isLong(subtrahend)) - subtrahend = Long.fromValue(subtrahend); - return this.add(subtrahend.neg()); + get id() { + return bson_1.Long.fromBigInt(0n); } - sub(subtrahend) { - return this.subtract(subtrahend); + get batchSize() { + return 0; } - toInt() { - return this.unsigned ? this.low >>> 0 : this.low; + get ns() { + return null; } - toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + get length() { + return this._length; } - toBigInt() { - return BigInt(this.toString()); + shift(options) { + if (this._length === 0) + return null; + this._length -= 1; + return this.toObject(options); } - toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); + } + exports.ExplainedCursorResponse = ExplainedCursorResponse; + + class ClientBulkWriteCursorResponse extends CursorResponse { + get insertedCount() { + return this.get("nInserted", bson_1.BSONType.int, true); } - toBytesLE() { - const hi = this.high, lo = this.low; - return [ - lo & 255, - lo >>> 8 & 255, - lo >>> 16 & 255, - lo >>> 24, - hi & 255, - hi >>> 8 & 255, - hi >>> 16 & 255, - hi >>> 24 - ]; + get upsertedCount() { + return this.get("nUpserted", bson_1.BSONType.int, true); } - toBytesBE() { - const hi = this.high, lo = this.low; - return [ - hi >>> 24, - hi >>> 16 & 255, - hi >>> 8 & 255, - hi & 255, - lo >>> 24, - lo >>> 16 & 255, - lo >>> 8 & 255, - lo & 255 - ]; + get matchedCount() { + return this.get("nMatched", bson_1.BSONType.int, true); } - toSigned() { - if (!this.unsigned) - return this; - return Long.fromBits(this.low, this.high, false); + get modifiedCount() { + return this.get("nModified", bson_1.BSONType.int, true); } - toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw new BSONError("radix"); - if (this.isZero()) - return "0"; - if (this.isNegative()) { - if (this.eq(Long.MIN_VALUE)) { - const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else - return "-" + this.neg().toString(radix); - } - const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); - let rem = this; - let result = ""; - while (true) { - const remDiv = rem.div(radixToPower); - const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0; - let digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) { - return digits + result; + get deletedCount() { + return this.get("nDeleted", bson_1.BSONType.int, true); + } + get writeConcernError() { + return this.get("writeConcernError", bson_1.BSONType.object, false); + } + } + exports.ClientBulkWriteCursorResponse = ClientBulkWriteCursorResponse; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/write_concern.js +var require_write_concern = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WriteConcern = exports.WRITE_CONCERN_KEYS = undefined; + exports.throwIfWriteConcernError = throwIfWriteConcernError; + var responses_1 = require_responses(); + var error_1 = require_error2(); + exports.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"]; + + class WriteConcern { + constructor(w, wtimeoutMS, journal, fsync) { + if (w != null) { + if (!Number.isNaN(Number(w))) { + this.w = Number(w); } else { - while (digits.length < 6) - digits = "0" + digits; - result = "" + digits + result; + this.w = w; } } + if (wtimeoutMS != null) { + this.wtimeoutMS = this.wtimeout = wtimeoutMS; + } + if (journal != null) { + this.journal = this.j = journal; + } + if (fsync != null) { + this.journal = this.j = fsync ? true : false; + } } - toUnsigned() { - if (this.unsigned) - return this; - return Long.fromBits(this.low, this.high, true); - } - xor(other) { - if (!Long.isLong(other)) - other = Long.fromValue(other); - return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + static apply(command, writeConcern) { + const wc = {}; + if (writeConcern.w != null) + wc.w = writeConcern.w; + if (writeConcern.wtimeoutMS != null) + wc.wtimeout = writeConcern.wtimeoutMS; + if (writeConcern.journal != null) + wc.j = writeConcern.j; + command.writeConcern = wc; + return command; } - eqz() { - return this.isZero(); + static fromOptions(options, inherit) { + if (options == null) + return; + inherit = inherit ?? {}; + let opts; + if (typeof options === "string" || typeof options === "number") { + opts = { w: options }; + } else if (options instanceof WriteConcern) { + opts = options; + } else { + opts = options.writeConcern; + } + const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; + const mergedOpts = { ...parentOpts, ...opts }; + const { w = undefined, wtimeout = undefined, j: j2 = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = mergedOpts; + if (w != null || wtimeout != null || wtimeoutMS != null || j2 != null || journal != null || fsync != null) { + return new WriteConcern(w, wtimeout ?? wtimeoutMS, j2 ?? journal, fsync); + } + return; } - le(other) { - return this.lessThanOrEqual(other); + } + exports.WriteConcern = WriteConcern; + function throwIfWriteConcernError(response) { + if (typeof response === "object" && response != null) { + const writeConcernError = responses_1.MongoDBResponse.is(response) && response.has("writeConcernError") ? response.toObject() : !responses_1.MongoDBResponse.is(response) && ("writeConcernError" in response) ? response : null; + if (writeConcernError != null) { + throw new error_1.MongoWriteConcernError(writeConcernError); + } } - toExtendedJSON(options) { - if (options && options.relaxed) - return this.toNumber(); - return { $numberLong: this.toString() }; + } +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/utils.js +var require_utils5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.kDispose = exports.randomBytes = exports.COSMOS_DB_MSG = exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ByteUtils = undefined; + exports.isUint8Array = isUint8Array; + exports.hostMatchesWildcards = hostMatchesWildcards; + exports.normalizeHintField = normalizeHintField; + exports.isObject = isObject4; + exports.mergeOptions = mergeOptions; + exports.filterOptions = filterOptions; + exports.applyRetryableWrites = applyRetryableWrites; + exports.isPromiseLike = isPromiseLike3; + exports.decorateWithCollation = decorateWithCollation; + exports.decorateWithReadConcern = decorateWithReadConcern; + exports.getTopology = getTopology; + exports.ns = ns3; + exports.makeCounter = makeCounter; + exports.uuidV4 = uuidV4; + exports.maxWireVersion = maxWireVersion; + exports.arrayStrictEqual = arrayStrictEqual; + exports.errorStrictEqual = errorStrictEqual; + exports.makeStateMachine = makeStateMachine; + exports.now = now; + exports.calculateDurationInMs = calculateDurationInMs; + exports.hasAtomicOperators = hasAtomicOperators; + exports.resolveTimeoutOptions = resolveTimeoutOptions; + exports.resolveOptions = resolveOptions; + exports.isSuperset = isSuperset; + exports.isHello = isHello; + exports.setDifference = setDifference; + exports.isRecord = isRecord4; + exports.emitWarning = emitWarning; + exports.emitWarningOnce = emitWarningOnce; + exports.enumToString = enumToString; + exports.supportsRetryableWrites = supportsRetryableWrites; + exports.shuffle = shuffle; + exports.commandSupportsReadConcern = commandSupportsReadConcern; + exports.compareObjectId = compareObjectId; + exports.parseInteger = parseInteger; + exports.parseUnsignedInteger = parseUnsignedInteger; + exports.checkParentDomainMatch = checkParentDomainMatch; + exports.get = get; + exports.request = request; + exports.isHostMatch = isHostMatch; + exports.promiseWithResolvers = promiseWithResolvers2; + exports.squashError = squashError; + exports.once = once; + exports.maybeAddIdToDocuments = maybeAddIdToDocuments; + exports.fileIsAccessible = fileIsAccessible; + exports.csotMin = csotMin; + exports.noop = noop2; + exports.decorateDecryptionResult = decorateDecryptionResult; + exports.addAbortListener = addAbortListener; + exports.abortable = abortable; + var crypto3 = __require("crypto"); + var fs_1 = __require("fs"); + var http = __require("http"); + var timers_1 = __require("timers"); + var url3 = __require("url"); + var url_1 = __require("url"); + var util_1 = __require("util"); + var bson_1 = require_bson2(); + var constants_1 = require_constants5(); + var constants_2 = require_constants6(); + var error_1 = require_error2(); + var read_concern_1 = require_read_concern(); + var read_preference_1 = require_read_preference(); + var common_1 = require_common4(); + var write_concern_1 = require_write_concern(); + exports.ByteUtils = { + toLocalBufferType(buffer) { + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + equals(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + compare(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + toBase64(uint8array) { + return exports.ByteUtils.toLocalBufferType(uint8array).toString("base64"); } - static fromExtendedJSON(doc3, options) { - const { useBigInt64 = false, relaxed = true } = { ...options }; - if (doc3.$numberLong.length > MAX_INT64_STRING_LENGTH) { - throw new BSONError("$numberLong string is too long"); - } - if (!DECIMAL_REG_EX.test(doc3.$numberLong)) { - throw new BSONError(`$numberLong string "${doc3.$numberLong}" is in an invalid format`); + }; + function isUint8Array(value) { + return value != null && typeof value === "object" && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Uint8Array"; + } + function hostMatchesWildcards(host, wildcards) { + for (const wildcard of wildcards) { + if (host === wildcard || wildcard.startsWith("*.") && host?.endsWith(wildcard.substring(2, wildcard.length)) || wildcard.startsWith("*/") && host?.endsWith(wildcard.substring(2, wildcard.length))) { + return true; } - if (useBigInt64) { - const bigIntResult = BigInt(doc3.$numberLong); - return BigInt.asIntN(64, bigIntResult); + } + return false; + } + function normalizeHintField(hint) { + let finalHint = undefined; + if (typeof hint === "string") { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + hint.forEach((param) => { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === "object") { + finalHint = {}; + for (const name in hint) { + finalHint[name] = hint[name]; } - const longResult = Long.fromString(doc3.$numberLong); - if (relaxed) { - return longResult.toNumber(); + } + return finalHint; + } + var TO_STRING = (object3) => Object.prototype.toString.call(object3); + function isObject4(arg) { + return TO_STRING(arg) === "[object Object]"; + } + function mergeOptions(target, source) { + return { ...target, ...source }; + } + function filterOptions(options, names) { + const filterOptions2 = {}; + for (const name in options) { + if (names.includes(name)) { + filterOptions2[name] = options[name]; } - return longResult; } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - const longVal = inspect(this.toString(), options); - const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : ""; - return `new Long(${longVal}${unsignedVal})`; + return filterOptions2; + } + function applyRetryableWrites(target, db) { + if (db && db.s.options?.retryWrites) { + target.retryWrites = true; } + return target; } - Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); - Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 0, true); - Long.ZERO = Long.fromInt(0); - Long.UZERO = Long.fromInt(0, true); - Long.ONE = Long.fromInt(1); - Long.UONE = Long.fromInt(1, true); - Long.NEG_ONE = Long.fromInt(-1); - Long.MAX_VALUE = Long.fromBits(4294967295 | 0, 2147483647 | 0, false); - Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false); - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - var NAN_BUFFER = ByteUtils.fromNumberArray([ - 124, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ].reverse()); - var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ - 248, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ].reverse()); - var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ - 120, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ].reverse()); - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - var COMBINATION_MASK = 31; - var EXPONENT_MASK = 16383; - var COMBINATION_INFINITY = 30; - var COMBINATION_NAN = 31; - function isDigit(value) { - return !isNaN(parseInt(value, 10)); + function isPromiseLike3(value) { + return value != null && typeof value === "object" && "then" in value && typeof value.then === "function"; } - function divideu128(value) { - const DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - let _rem = Long.fromNumber(0); - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - for (let i2 = 0;i2 <= 3; i2++) { - _rem = _rem.shiftLeft(32); - _rem = _rem.add(new Long(value.parts[i2], 0)); - value.parts[i2] = _rem.div(DIVISOR).low; - _rem = _rem.modulo(DIVISOR); + function decorateWithCollation(command, options) { + if (options.collation && typeof options.collation === "object") { + command.collation = options.collation; } - return { quotient: value, rem: _rem }; } - function multiply64x2(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + const readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern }); } - const leftHigh = left.shiftRightUnsigned(32); - const leftLow = new Long(left.getLowBits(), 0); - const rightHigh = right.shiftRightUnsigned(32); - const rightLow = new Long(right.getLowBits(), 0); - let productHigh = leftHigh.multiply(rightHigh); - let productMid = leftHigh.multiply(rightLow); - const productMid2 = leftLow.multiply(rightHigh); - let productLow = leftLow.multiply(rightLow); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - return { high: productHigh, low: productLow }; } - function lessThan(left, right) { - const uhleft = left.high >>> 0; - const uhright = right.high >>> 0; - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - const ulleft = left.low >>> 0; - const ulright = right.low >>> 0; - if (ulleft < ulright) - return true; + function getTopology(provider) { + if ("topology" in provider && provider.topology) { + return provider.topology; + } else if ("client" in provider && provider.client.topology) { + return provider.client.topology; } - return false; + throw new error_1.MongoNotConnectedError("MongoClient must be connected to perform this operation"); } - function invalidErr(string7, message) { - throw new BSONError(`"${string7}" is not a valid Decimal128 string - ${message}`); + function ns3(ns4) { + return MongoDBNamespace.fromString(ns4); } - class Decimal128 extends BSONValue { - get _bsontype() { - return "Decimal128"; + class MongoDBNamespace { + constructor(db, collection) { + this.db = db; + this.collection = collection === "" ? undefined : collection; } - constructor(bytes) { - super(); - if (typeof bytes === "string") { - this.bytes = Decimal128.fromString(bytes).bytes; - } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) { - if (bytes.byteLength !== 16) { - throw new BSONError("Decimal128 must take a Buffer of 16 bytes"); - } - this.bytes = bytes; - } else { - throw new BSONError("Decimal128 must take a Buffer or string"); + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBCollectionNamespace(this.db, collection); + } + static fromString(namespace) { + if (typeof namespace !== "string" || namespace === "") { + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); } + const [db, ...collectionParts] = namespace.split("."); + const collection = collectionParts.join("."); + return new MongoDBNamespace(db, collection === "" ? undefined : collection); } - static fromString(representation) { - return Decimal128._fromString(representation, { allowRounding: false }); + } + exports.MongoDBNamespace = MongoDBNamespace; + + class MongoDBCollectionNamespace extends MongoDBNamespace { + constructor(db, collection) { + super(db, collection); + this.collection = collection; } - static fromStringWithRounding(representation) { - return Decimal128._fromString(representation, { allowRounding: true }); + static fromString(namespace) { + return super.fromString(namespace); } - static _fromString(representation, options) { - let isNegative = false; - let sawSign = false; - let sawRadix = false; - let foundNonZero = false; - let significantDigits = 0; - let nDigitsRead = 0; - let nDigits = 0; - let radixPosition = 0; - let firstNonZero = 0; - const digits = [0]; - let nDigitsStored = 0; - let digitsInsert = 0; - let lastDigit = 0; - let exponent = 0; - let significandHigh = new Long(0, 0); - let significandLow = new Long(0, 0); - let biasedExponent = 0; - let index2 = 0; - if (representation.length >= 7000) { - throw new BSONError("" + representation + " not a valid Decimal128 string"); + } + exports.MongoDBCollectionNamespace = MongoDBCollectionNamespace; + function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } + } + function uuidV4() { + const result = crypto3.randomBytes(16); + result[6] = result[6] & 15 | 64; + result[8] = result[8] & 63 | 128; + return result; + } + function maxWireVersion(handshakeAware) { + if (handshakeAware) { + if (handshakeAware.hello) { + return handshakeAware.hello.maxWireVersion; } - const stringMatch = representation.match(PARSE_STRING_REGEXP); - const infMatch = representation.match(PARSE_INF_REGEXP); - const nanMatch = representation.match(PARSE_NAN_REGEXP); - if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) { - throw new BSONError("" + representation + " not a valid Decimal128 string"); + if (handshakeAware.serverApi?.version) { + return constants_1.MAX_SUPPORTED_WIRE_VERSION; } - if (stringMatch) { - const unsignedNumber = stringMatch[2]; - const e = stringMatch[4]; - const expSign = stringMatch[5]; - const expNumber = stringMatch[6]; - if (e && expNumber === undefined) - invalidErr(representation, "missing exponent power"); - if (e && unsignedNumber === undefined) - invalidErr(representation, "missing exponent base"); - if (e === undefined && (expSign || expNumber)) { - invalidErr(representation, "missing e before exponent"); + if (handshakeAware.loadBalanced) { + return constants_1.MAX_SUPPORTED_WIRE_VERSION; + } + if ("lastHello" in handshakeAware && typeof handshakeAware.lastHello === "function") { + const lastHello = handshakeAware.lastHello(); + if (lastHello) { + return lastHello.maxWireVersion; } } - if (representation[index2] === "+" || representation[index2] === "-") { - sawSign = true; - isNegative = representation[index2++] === "-"; + if (handshakeAware.description && "maxWireVersion" in handshakeAware.description && handshakeAware.description.maxWireVersion != null) { + return handshakeAware.description.maxWireVersion; } - if (!isDigit(representation[index2]) && representation[index2] !== ".") { - if (representation[index2] === "i" || representation[index2] === "I") { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } else if (representation[index2] === "N") { - return new Decimal128(NAN_BUFFER); - } + } + return 0; + } + function arrayStrictEqual(arr3, arr22) { + if (!Array.isArray(arr3) || !Array.isArray(arr22)) { + return false; + } + return arr3.length === arr22.length && arr3.every((elt, idx) => elt === arr22[idx]); + } + function errorStrictEqual(lhs, rhs) { + if (lhs === rhs) { + return true; + } + if (!lhs || !rhs) { + return lhs === rhs; + } + if (lhs == null && rhs != null || lhs != null && rhs == null) { + return false; + } + if (lhs.constructor.name !== rhs.constructor.name) { + return false; + } + if (lhs.message !== rhs.message) { + return false; + } + return true; + } + function makeStateMachine(stateTable) { + return function stateTransition(target, newState) { + const legalStates = stateTable[target.s.state]; + if (legalStates && legalStates.indexOf(newState) < 0) { + throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); } - while (isDigit(representation[index2]) || representation[index2] === ".") { - if (representation[index2] === ".") { - if (sawRadix) - invalidErr(representation, "contains multiple periods"); - sawRadix = true; - index2 = index2 + 1; - continue; - } - if (nDigitsStored < MAX_DIGITS) { - if (representation[index2] !== "0" || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - foundNonZero = true; - digits[digitsInsert++] = parseInt(representation[index2], 10); - nDigitsStored = nDigitsStored + 1; - } + target.emit("stateChanged", target.s.state, newState); + target.s.state = newState; + }; + } + function now() { + const hrtime = process.hrtime(); + return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1e6); + } + function calculateDurationInMs(started) { + if (typeof started !== "number") { + return -1; + } + const elapsed2 = now() - started; + return elapsed2 < 0 ? 0 : elapsed2; + } + function hasAtomicOperators(doc3, options) { + if (Array.isArray(doc3)) { + for (const document2 of doc3) { + if (hasAtomicOperators(document2)) { + return true; } - if (foundNonZero) - nDigits = nDigits + 1; - if (sawRadix) - radixPosition = radixPosition + 1; - nDigitsRead = nDigitsRead + 1; - index2 = index2 + 1; - } - if (sawRadix && !nDigitsRead) - throw new BSONError("" + representation + " not a valid Decimal128 string"); - if (representation[index2] === "e" || representation[index2] === "E") { - const match2 = representation.substr(++index2).match(EXPONENT_REGEX); - if (!match2 || !match2[2]) - return new Decimal128(NAN_BUFFER); - exponent = parseInt(match2[0], 10); - index2 = index2 + match2[0].length; } - if (representation[index2]) - return new Decimal128(NAN_BUFFER); - if (!nDigitsStored) { - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - if (significantDigits !== 1) { - while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") { - significantDigits = significantDigits - 1; - } + return false; + } + const keys = Object.keys(doc3); + if (options?.ignoreUndefined) { + let allUndefined = true; + for (const key of keys) { + if (doc3[key] !== undefined) { + allUndefined = false; + break; } } - if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; + if (allUndefined) { + throw new error_1.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided."); } - while (exponent > EXPONENT_MAX) { - lastDigit = lastDigit + 1; - if (lastDigit >= MAX_DIGITS) { - if (significantDigits === 0) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, "overflow"); - } - exponent = exponent - 1; + } + return keys.length > 0 && keys[0][0] === "$"; + } + function resolveTimeoutOptions(client2, options) { + const { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS } = client2.s.options; + return { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS, ...options }; + } + function resolveOptions(parent, options) { + const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); + const timeoutMS = options?.timeoutMS ?? parent?.timeoutMS; + const session = options?.session; + if (!session?.inTransaction()) { + const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; } - if (options.allowRounding) { - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - if (lastDigit === 0 && significantDigits < nDigitsStored) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - if (nDigitsStored < nDigits) { - nDigits = nDigits - 1; - } else { - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - const digitsString = digits.join(""); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } - invalidErr(representation, "overflow"); - } - } - if (lastDigit + 1 < significantDigits) { - let endOfString = nDigitsRead; - if (sawRadix) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - if (sawSign) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - let roundBit = 0; - if (roundDigit >= 5) { - roundBit = 1; - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0; - for (let i2 = firstNonZero + lastDigit + 2;i2 < endOfString; i2++) { - if (parseInt(representation[i2], 10)) { - roundBit = 1; - break; - } - } - } - } - if (roundBit) { - let dIdx = lastDigit; - for (;dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); - } - } - } else { - break; - } - } - } - } - } else { - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - if (lastDigit === 0) { - if (significantDigits === 0) { - exponent = EXPONENT_MIN; - break; - } - invalidErr(representation, "exponent underflow"); - } - if (nDigitsStored < nDigits) { - if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) { - invalidErr(representation, "inexact rounding"); - } - nDigits = nDigits - 1; - } else { - if (digits[lastDigit] !== 0) { - invalidErr(representation, "inexact rounding"); + let writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + if (timeoutMS != null) { + writeConcern = write_concern_1.WriteConcern.fromOptions({ + writeConcern: { + ...writeConcern, + wtimeout: undefined, + wtimeoutMS: undefined } - lastDigit = lastDigit - 1; - } - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - invalidErr(representation, "overflow"); - } - } - if (lastDigit + 1 < significantDigits) { - if (sawRadix) { - firstNonZero = firstNonZero + 1; - } - if (sawSign) { - firstNonZero = firstNonZero + 1; - } - const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10); - if (roundDigit !== 0) { - invalidErr(representation, "inexact rounding"); - } - } - } - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit < 17) { - let dIdx = 0; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - for (;dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - let dIdx = 0; - significandHigh = Long.fromNumber(digits[dIdx++]); - for (;dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - significandLow = Long.fromNumber(digits[dIdx++]); - for (;dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + }); } + result.writeConcern = writeConcern; } - const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000")); - significand.low = significand.low.add(significandLow); - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); + } + result.timeoutMS = timeoutMS; + const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference; + if (readPreference) { + result.readPreference = readPreference; + } + const isConvenientTransaction = session?.explicit && session?.timeoutContext != null; + if (isConvenientTransaction && options?.timeoutMS != null) { + throw new error_1.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting"); + } + return result; + } + function isSuperset(set3, subset) { + set3 = Array.isArray(set3) ? new Set(set3) : set3; + subset = Array.isArray(subset) ? new Set(subset) : subset; + for (const elem of subset) { + if (!set3.has(elem)) { + return false; } - biasedExponent = exponent + EXPONENT_BIAS; - const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { - dec.high = dec.high.or(Long.fromNumber(3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(140737488355327))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(562949953421311))); + } + return true; + } + function isHello(doc3) { + return doc3[constants_2.LEGACY_HELLO_COMMAND] || doc3.hello ? true : false; + } + function setDifference(setA, setB) { + const difference = new Set(setA); + for (const elem of setB) { + difference.delete(elem); + } + return difference; + } + var HAS_OWN = (object3, prop) => Object.prototype.hasOwnProperty.call(object3, prop); + function isRecord4(value, requiredKeys = undefined) { + if (!isObject4(value)) { + return false; + } + const ctor = value.constructor; + if (ctor && ctor.prototype) { + if (!isObject4(ctor.prototype)) { + return false; } - dec.low = significand.low; - if (isNegative) { - dec.high = dec.high.or(Long.fromString("9223372036854775808")); + if (!HAS_OWN(ctor.prototype, "isPrototypeOf")) { + return false; } - const buffer2 = ByteUtils.allocateUnsafe(16); - index2 = 0; - buffer2[index2++] = dec.low.low & 255; - buffer2[index2++] = dec.low.low >> 8 & 255; - buffer2[index2++] = dec.low.low >> 16 & 255; - buffer2[index2++] = dec.low.low >> 24 & 255; - buffer2[index2++] = dec.low.high & 255; - buffer2[index2++] = dec.low.high >> 8 & 255; - buffer2[index2++] = dec.low.high >> 16 & 255; - buffer2[index2++] = dec.low.high >> 24 & 255; - buffer2[index2++] = dec.high.low & 255; - buffer2[index2++] = dec.high.low >> 8 & 255; - buffer2[index2++] = dec.high.low >> 16 & 255; - buffer2[index2++] = dec.high.low >> 24 & 255; - buffer2[index2++] = dec.high.high & 255; - buffer2[index2++] = dec.high.high >> 8 & 255; - buffer2[index2++] = dec.high.high >> 16 & 255; - buffer2[index2++] = dec.high.high >> 24 & 255; - return new Decimal128(buffer2); } - toString() { - let biased_exponent; - let significand_digits = 0; - const significand = new Array(36); - for (let i2 = 0;i2 < significand.length; i2++) - significand[i2] = 0; - let index2 = 0; - let is_zero = false; - let significand_msb; - let significand128 = { parts: [0, 0, 0, 0] }; - let j2, k2; - const string7 = []; - index2 = 0; - const buffer2 = this.bytes; - const low = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; - const midl = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; - const midh = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; - const high = buffer2[index2++] | buffer2[index2++] << 8 | buffer2[index2++] << 16 | buffer2[index2++] << 24; - index2 = 0; - const dec = { - low: new Long(low, midl), - high: new Long(midh, high) + if (requiredKeys) { + const keys = Object.keys(value); + return isSuperset(keys, requiredKeys); + } + return true; + } + + class List { + get length() { + return this.count; + } + get [Symbol.toStringTag]() { + return "List"; + } + constructor() { + this.count = 0; + this.head = { + next: null, + prev: null, + value: null }; - if (dec.high.lessThan(Long.ZERO)) { - string7.push("-"); + this.head.next = this.head; + this.head.prev = this.head; + } + toArray() { + return Array.from(this); + } + toString() { + return `head <=> ${this.toArray().join(" <=> ")} <=> head`; + } + *[Symbol.iterator]() { + for (const node of this.nodes()) { + yield node.value; } - const combination = high >> 26 & COMBINATION_MASK; - if (combination >> 3 === 3) { - if (combination === COMBINATION_INFINITY) { - return string7.join("") + "Infinity"; - } else if (combination === COMBINATION_NAN) { - return "NaN"; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 8 + (high >> 14 & 1); - } - } else { - significand_msb = high >> 14 & 7; - biased_exponent = high >> 17 & EXPONENT_MASK; + } + *nodes() { + let ptr = this.head.next; + while (ptr !== this.head) { + const { next } = ptr; + yield ptr; + ptr = next; } - const exponent = biased_exponent - EXPONENT_BIAS; - significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k2 = 3;k2 >= 0; k2--) { - let least_digits = 0; - const result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low; - if (!least_digits) - continue; - for (j2 = 8;j2 >= 0; j2--) { - significand[k2 * 9 + j2] = least_digits % 10; - least_digits = Math.floor(least_digits / 10); - } - } + } + push(value) { + this.count += 1; + const newNode = { + next: this.head, + prev: this.head.prev, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + pushMany(iterable) { + for (const value of iterable) { + this.push(value); } - if (is_zero) { - significand_digits = 1; - significand[index2] = 0; - } else { - significand_digits = 36; - while (!significand[index2]) { - significand_digits = significand_digits - 1; - index2 = index2 + 1; - } + } + unshift(value) { + this.count += 1; + const newNode = { + next: this.head.next, + prev: this.head, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + remove(node) { + if (node === this.head || this.length === 0) { + return null; } - const scientific_exponent = significand_digits - 1 + exponent; - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - if (significand_digits > 34) { - string7.push(`${0}`); - if (exponent > 0) - string7.push(`E+${exponent}`); - else if (exponent < 0) - string7.push(`E${exponent}`); - return string7.join(""); - } - string7.push(`${significand[index2++]}`); - significand_digits = significand_digits - 1; - if (significand_digits) { - string7.push("."); - } - for (let i2 = 0;i2 < significand_digits; i2++) { - string7.push(`${significand[index2++]}`); - } - string7.push("E"); - if (scientific_exponent > 0) { - string7.push(`+${scientific_exponent}`); - } else { - string7.push(`${scientific_exponent}`); - } - } else { - if (exponent >= 0) { - for (let i2 = 0;i2 < significand_digits; i2++) { - string7.push(`${significand[index2++]}`); - } - } else { - let radix_position = significand_digits + exponent; - if (radix_position > 0) { - for (let i2 = 0;i2 < radix_position; i2++) { - string7.push(`${significand[index2++]}`); - } - } else { - string7.push("0"); - } - string7.push("."); - while (radix_position++ < 0) { - string7.push("0"); - } - for (let i2 = 0;i2 < significand_digits - Math.max(radix_position - 1, 0); i2++) { - string7.push(`${significand[index2++]}`); - } + this.count -= 1; + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + return node.value; + } + shift() { + return this.remove(this.head.next); + } + pop() { + return this.remove(this.head.prev); + } + prune(filter) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); } } - return string7.join(""); - } - toJSON() { - return { $numberDecimal: this.toString() }; } - toExtendedJSON() { - return { $numberDecimal: this.toString() }; + clear() { + this.count = 0; + this.head.next = this.head; + this.head.prev = this.head; } - static fromExtendedJSON(doc3) { - return Decimal128.fromString(doc3.$numberDecimal); + first() { + return this.head.next.value; } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - const d128string = inspect(this.toString(), options); - return `new Decimal128(${d128string})`; + last() { + return this.head.prev.value; } } + exports.List = List; - class Double extends BSONValue { - get _bsontype() { - return "Double"; + class BufferPool { + constructor() { + this.buffers = new List; + this.totalByteLength = 0; } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); - } - this.value = +value; + get length() { + return this.totalByteLength; } - static fromString(value) { - const coercedValue = Number(value); - if (value === "NaN") - return new Double(NaN); - if (value === "Infinity") - return new Double(Infinity); - if (value === "-Infinity") - return new Double(-Infinity); - if (!Number.isFinite(coercedValue)) { - throw new BSONError(`Input: ${value} is not representable as a Double`); + append(buffer) { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + getInt32() { + if (this.totalByteLength < 4) { + return null; } - if (value.trim() !== value) { - throw new BSONError(`Input: '${value}' contains whitespace`); + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); } - if (value === "") { - throw new BSONError(`Input is an empty string`); + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + return value; + } + read(size) { + if (typeof size !== "number" || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); } - if (/[^-0-9.+eE]/.test(value)) { - throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`); + if (size > this.totalByteLength) { + return Buffer.alloc(0); } - return new Double(coercedValue); + const result = Buffer.allocUnsafe(size); + for (let bytesRead = 0;bytesRead < size; ) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + result.set(bytes, bytesRead); + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + return result; } - valueOf() { - return this.value; + } + exports.BufferPool = BufferPool; + + class HostAddress { + constructor(hostString) { + this.host = undefined; + this.port = undefined; + this.socketPath = undefined; + this.isIPv6 = false; + const escapedHost = hostString.split(" ").join("%20"); + if (escapedHost.endsWith(".sock")) { + this.socketPath = decodeURIComponent(escapedHost); + return; + } + const urlString = `iLoveJS://${escapedHost}`; + let url4; + try { + url4 = new url_1.URL(urlString); + } catch (urlError) { + const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + const hostname4 = url4.hostname; + const port = url4.port; + let normalized = decodeURIComponent(hostname4).toLowerCase(); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + this.isIPv6 = true; + normalized = normalized.substring(1, hostname4.length - 1); + } + this.host = normalized.toLowerCase(); + if (typeof port === "number") { + this.port = port; + } else if (typeof port === "string" && port !== "") { + this.port = Number.parseInt(port, 10); + } else { + this.port = 27017; + } + if (this.port === 0) { + throw new error_1.MongoParseError("Invalid port (zero) with hostname"); + } + Object.freeze(this); } - toJSON() { - return this.value; + [Symbol.for("nodejs.util.inspect.custom")]() { + return this.inspect(); } - toString(radix) { - return this.value.toString(radix); + inspect() { + return `new HostAddress('${this.toString()}')`; } - toExtendedJSON(options) { - if (options && (options.legacy || options.relaxed && isFinite(this.value))) { - return this.value; - } - if (Object.is(Math.sign(this.value), -0)) { - return { $numberDouble: "-0.0" }; + toString() { + if (typeof this.host === "string") { + if (this.isIPv6) { + return `[${this.host}]:${this.port}`; + } + return `${this.host}:${this.port}`; } - return { - $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() - }; + return `${this.socketPath}`; } - static fromExtendedJSON(doc3, options) { - const doubleValue = parseFloat(doc3.$numberDouble); - return options && options.relaxed ? doubleValue : new Double(doubleValue); + static fromString(s) { + return new HostAddress(s); } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - return `new Double(${inspect(this.value, options)})`; + static fromHostPort(host, port) { + if (host.includes(":")) { + host = `[${host}]`; + } + return HostAddress.fromString(`${host}:${port}`); } - } - - class Int32 extends BSONValue { - get _bsontype() { - return "Int32"; + static fromSrvRecord({ name, port }) { + return HostAddress.fromHostPort(name, port); } - constructor(value) { - super(); - if (value instanceof Number) { - value = value.valueOf(); + toHostPort() { + if (this.socketPath) { + return { host: this.socketPath, port: 0 }; } - this.value = +value | 0; + const host = this.host ?? ""; + const port = this.port ?? 0; + return { host, port }; } - static fromString(value) { - const cleanedValue = removeLeadingZerosAndExplicitPlus(value); - const coercedValue = Number(value); - if (BSON_INT32_MAX < coercedValue) { - throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`); - } else if (BSON_INT32_MIN > coercedValue) { - throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`); - } else if (!Number.isSafeInteger(coercedValue)) { - throw new BSONError(`Input: '${value}' is not a safe integer`); - } else if (coercedValue.toString() !== cleanedValue) { - throw new BSONError(`Input: '${value}' is not a valid Int32 string`); - } - return new Int32(coercedValue); + } + exports.HostAddress = HostAddress; + exports.DEFAULT_PK_FACTORY = { + createPk() { + return new bson_1.ObjectId; } - valueOf() { - return this.value; + }; + exports.MONGODB_WARNING_CODE = "MONGODB DRIVER"; + function emitWarning(message) { + return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); + } + var emittedWarnings = new Set; + function emitWarningOnce(message) { + if (!emittedWarnings.has(message)) { + emittedWarnings.add(message); + return emitWarning(message); } - toString(radix) { - return this.value.toString(radix); + } + function enumToString(en) { + return Object.values(en).join(", "); + } + function supportsRetryableWrites(server) { + if (!server) { + return false; } - toJSON() { - return this.value; + if (server.loadBalanced) { + return true; } - toExtendedJSON(options) { - if (options && (options.relaxed || options.legacy)) - return this.value; - return { $numberInt: this.value.toString() }; + if (server.description.logicalSessionTimeoutMinutes != null) { + if (server.description.type !== common_1.ServerType.Standalone) { + return true; + } } - static fromExtendedJSON(doc3, options) { - return options && options.relaxed ? parseInt(doc3.$numberInt, 10) : new Int32(doc3.$numberInt); + return false; + } + function shuffle(sequence, limit2 = 0) { + const items = Array.from(sequence); + if (limit2 > items.length) { + throw new error_1.MongoRuntimeError("Limit must be less than the number of items"); } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - return `new Int32(${inspect(this.value, options)})`; + let remainingItemsToShuffle = items.length; + const lowerBound2 = limit2 % items.length === 0 ? 1 : items.length - limit2; + while (remainingItemsToShuffle > lowerBound2) { + const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); + remainingItemsToShuffle -= 1; + const swapHold = items[remainingItemsToShuffle]; + items[remainingItemsToShuffle] = items[randomIndex]; + items[randomIndex] = swapHold; } + return limit2 % items.length === 0 ? items : items.slice(lowerBound2); } - - class MaxKey extends BSONValue { - get _bsontype() { - return "MaxKey"; + function commandSupportsReadConcern(command) { + if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + return true; } - toExtendedJSON() { - return { $maxKey: 1 }; + return false; + } + function compareObjectId(oid1, oid2) { + if (oid1 == null && oid2 == null) { + return 0; } - static fromExtendedJSON() { - return new MaxKey; + if (oid1 == null) { + return -1; } - inspect() { - return "new MaxKey()"; + if (oid2 == null) { + return 1; } + return exports.ByteUtils.compare(oid1.id, oid2.id); } - - class MinKey extends BSONValue { - get _bsontype() { - return "MinKey"; - } - toExtendedJSON() { - return { $minKey: 1 }; + function parseInteger(value) { + if (typeof value === "number") + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + return Number.isNaN(parsedValue) ? null : parsedValue; + } + function parseUnsignedInteger(value) { + const parsedInt = parseInteger(value); + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; + } + function checkParentDomainMatch(address, srvHost) { + const normalizedAddress = address.endsWith(".") ? address.slice(0, address.length - 1) : address; + const normalizedSrvHost = srvHost.endsWith(".") ? srvHost.slice(0, srvHost.length - 1) : srvHost; + const allCharacterBeforeFirstDot = /^.*?\./; + const srvIsLessThanThreeParts = normalizedSrvHost.split(".").length < 3; + const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, "")}`; + let srvHostDomain = srvIsLessThanThreeParts ? normalizedSrvHost : `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`; + if (!srvHostDomain.startsWith(".")) { + srvHostDomain = "." + srvHostDomain; } - static fromExtendedJSON() { - return new MinKey; + if (srvIsLessThanThreeParts && normalizedAddress.split(".").length <= normalizedSrvHost.split(".").length) { + throw new error_1.MongoAPIError("Server record does not have at least one more domain level than parent URI"); } - inspect() { - return "new MinKey()"; + if (!addressDomain.endsWith(srvHostDomain)) { + throw new error_1.MongoAPIError("Server record does not share hostname with parent URI"); } } - var PROCESS_UNIQUE = null; - var __idCache = new WeakMap; - - class ObjectId extends BSONValue { - get _bsontype() { - return "ObjectId"; - } - constructor(inputId) { - super(); - let workingId; - if (typeof inputId === "object" && inputId && "id" in inputId) { - if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) { - throw new BSONError("Argument passed in must have an id that is of type string or Buffer"); - } - if ("toHexString" in inputId && typeof inputId.toHexString === "function") { - workingId = ByteUtils.fromHex(inputId.toHexString()); - } else { - workingId = inputId.id; - } - } else { - workingId = inputId; - } - if (workingId == null || typeof workingId === "number") { - this.buffer = ObjectId.generate(typeof workingId === "number" ? workingId : undefined); - } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { - this.buffer = ByteUtils.toLocalBufferType(workingId); - } else if (typeof workingId === "string") { - if (ObjectId.validateHexString(workingId)) { - this.buffer = ByteUtils.fromHex(workingId); - if (ObjectId.cacheHexString) { - __idCache.set(this, workingId); + function get(url4, options = {}) { + return new Promise((resolve2, reject) => { + let timeoutId; + const request2 = http.get(url4, options, (response) => { + response.setEncoding("utf8"); + let body = ""; + response.on("data", (chunk) => body += chunk); + response.on("end", () => { + (0, timers_1.clearTimeout)(timeoutId); + resolve2({ status: response.statusCode, body }); + }); + }).on("error", (error91) => { + (0, timers_1.clearTimeout)(timeoutId); + reject(error91); + }).end(); + timeoutId = (0, timers_1.setTimeout)(() => { + request2.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`)); + }, 1e4); + }); + } + async function request(uri2, options = {}) { + return await new Promise((resolve2, reject) => { + const requestOptions = { + method: "GET", + timeout: 1e4, + json: true, + ...url3.parse(uri2), + ...options + }; + const req = http.request(requestOptions, (res) => { + res.setEncoding("utf8"); + let data = ""; + res.on("data", (d) => { + data += d; + }); + res.once("end", () => { + if (options.json === false) { + resolve2(data); + return; } - } else { - throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer"); - } - } else { - throw new BSONError("Argument passed in does not match the accepted types"); - } + try { + const parsed = JSON.parse(data); + resolve2(parsed); + } catch { + reject(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); + } + }); + }); + req.once("timeout", () => req.destroy(new error_1.MongoNetworkTimeoutError(`Network request to ${uri2} timed out after ${options.timeout} ms`))); + req.once("error", (error91) => reject(error91)); + req.end(); + }); + } + exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/; + exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/; + exports.DOCUMENT_DB_MSG = "You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb"; + exports.COSMOS_DB_MSG = "You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb"; + function isHostMatch(match2, host) { + return host && match2.test(host.toLowerCase()) ? true : false; + } + function promiseWithResolvers2() { + let resolve2; + let reject; + const promise3 = new Promise(function withResolversExecutor(promiseResolve, promiseReject) { + resolve2 = promiseResolve; + reject = promiseReject; + }); + return { promise: promise3, resolve: resolve2, reject }; + } + function squashError(_error) { + return; + } + exports.randomBytes = (0, util_1.promisify)(crypto3.randomBytes); + async function once(ee2, name, options) { + options?.signal?.throwIfAborted(); + const { promise: promise3, resolve: resolve2, reject } = promiseWithResolvers2(); + const onEvent = (data) => resolve2(data); + const onError3 = (error91) => reject(error91); + const abortListener = addAbortListener(options?.signal, function() { + reject(this.reason); + }); + ee2.once(name, onEvent).once("error", onError3); + try { + return await promise3; + } finally { + ee2.off(name, onEvent); + ee2.off("error", onError3); + abortListener?.[exports.kDispose](); } - get id() { - return this.buffer; + } + function maybeAddIdToDocuments(collection, document2, options) { + const forceServerObjectId = options.forceServerObjectId ?? collection.db.options?.forceServerObjectId ?? false; + if (forceServerObjectId) { + return document2; } - set id(value) { - this.buffer = value; - if (ObjectId.cacheHexString) { - __idCache.set(this, ByteUtils.toHex(value)); - } + if (document2._id == null) { + document2._id = collection.s.pkFactory.createPk(); } - static validateHexString(string7) { - if (string7?.length !== 24) - return false; - for (let i2 = 0;i2 < 24; i2++) { - const char = string7.charCodeAt(i2); - if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) { - continue; - } - return false; - } + return document2; + } + async function fileIsAccessible(fileName, mode) { + try { + await fs_1.promises.access(fileName, mode); return true; + } catch { + return false; } - toHexString() { - if (ObjectId.cacheHexString) { - const __id = __idCache.get(this); - if (__id) - return __id; + } + function csotMin(duration1, duration22) { + if (duration1 === 0) + return duration22; + if (duration22 === 0) + return duration1; + return Math.min(duration1, duration22); + } + function noop2() { + return; + } + function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) { + if (isTopLevelDecorateCall) { + if (Buffer.isBuffer(original)) { + original = (0, bson_1.deserialize)(original); } - const hexString = ByteUtils.toHex(this.id); - if (ObjectId.cacheHexString) { - __idCache.set(this, hexString); + if (Buffer.isBuffer(decrypted)) { + throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object"); } - return hexString; } - static getInc() { - return ObjectId.index = (ObjectId.index + 1) % 16777215; - } - static generate(time6) { - if (typeof time6 !== "number") { - time6 = Math.floor(Date.now() / 1000); - } - const inc = ObjectId.getInc(); - const buffer2 = ByteUtils.allocateUnsafe(12); - NumberUtils.setInt32BE(buffer2, 0, time6); - if (PROCESS_UNIQUE === null) { - PROCESS_UNIQUE = ByteUtils.randomBytes(5); + if (!decrypted || typeof decrypted !== "object") + return; + for (const k2 of Object.keys(decrypted)) { + const originalValue = original[k2]; + if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) { + if (!decrypted[constants_2.kDecoratedKeys]) { + Object.defineProperty(decrypted, constants_2.kDecoratedKeys, { + value: [], + configurable: true, + enumerable: false, + writable: false + }); + } + decrypted[constants_2.kDecoratedKeys].push(k2); + continue; } - buffer2[4] = PROCESS_UNIQUE[0]; - buffer2[5] = PROCESS_UNIQUE[1]; - buffer2[6] = PROCESS_UNIQUE[2]; - buffer2[7] = PROCESS_UNIQUE[3]; - buffer2[8] = PROCESS_UNIQUE[4]; - buffer2[11] = inc & 255; - buffer2[10] = inc >> 8 & 255; - buffer2[9] = inc >> 16 & 255; - return buffer2; - } - toString(encoding) { - if (encoding === "base64") - return ByteUtils.toBase64(this.id); - if (encoding === "hex") - return this.toHexString(); - return this.toHexString(); - } - toJSON() { - return this.toHexString(); + decorateDecryptionResult(decrypted[k2], originalValue, false); } - static is(variable) { - return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId"; + } + exports.kDispose = Symbol.dispose ?? Symbol("dispose"); + function addAbortListener(signal, listener) { + if (signal == null) + return; + signal.addEventListener("abort", listener, { once: true }); + return { [exports.kDispose]: () => signal.removeEventListener("abort", listener) }; + } + async function abortable(promise3, { signal }) { + if (signal == null) { + return await promise3; } - equals(otherId) { - if (otherId === undefined || otherId === null) { - return false; - } - if (ObjectId.is(otherId)) { - return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer); - } - if (typeof otherId === "string") { - return otherId.toLowerCase() === this.toHexString(); - } - if (typeof otherId === "object" && typeof otherId.toHexString === "function") { - const otherIdString = otherId.toHexString(); - const thisIdString = this.toHexString(); - return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString; - } - return false; + const { promise: aborted3, reject } = promiseWithResolvers2(); + const abortListener = signal.aborted ? reject(signal.reason) : addAbortListener(signal, function() { + reject(this.reason); + }); + try { + return await Promise.race([promise3, aborted3]); + } finally { + abortListener?.[exports.kDispose](); } - getTimestamp() { - const timestamp = new Date; - const time6 = NumberUtils.getUint32BE(this.buffer, 0); - timestamp.setTime(Math.floor(time6) * 1000); - return timestamp; + } +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/timeout.js +var require_timeout = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LegacyTimeoutContext = exports.CSOTTimeoutContext = exports.TimeoutContext = exports.Timeout = exports.TimeoutError = undefined; + var timers_1 = __require("timers"); + var error_1 = require_error2(); + var utils_1 = require_utils5(); + + class TimeoutError2 extends Error { + get name() { + return "TimeoutError"; } - static createPk() { - return new ObjectId; + constructor(message, options) { + super(message, options); + this.duration = options.duration; } - serializeInto(uint8array, index2) { - uint8array[index2] = this.buffer[0]; - uint8array[index2 + 1] = this.buffer[1]; - uint8array[index2 + 2] = this.buffer[2]; - uint8array[index2 + 3] = this.buffer[3]; - uint8array[index2 + 4] = this.buffer[4]; - uint8array[index2 + 5] = this.buffer[5]; - uint8array[index2 + 6] = this.buffer[6]; - uint8array[index2 + 7] = this.buffer[7]; - uint8array[index2 + 8] = this.buffer[8]; - uint8array[index2 + 9] = this.buffer[9]; - uint8array[index2 + 10] = this.buffer[10]; - uint8array[index2 + 11] = this.buffer[11]; - return 12; + static is(error91) { + return error91 != null && typeof error91 === "object" && "name" in error91 && error91.name === "TimeoutError"; } - static createFromTime(time6) { - const buffer2 = ByteUtils.allocate(12); - for (let i2 = 11;i2 >= 4; i2--) - buffer2[i2] = 0; - NumberUtils.setInt32BE(buffer2, 0, time6); - return new ObjectId(buffer2); + } + exports.TimeoutError = TimeoutError2; + + class Timeout extends Promise { + get remainingTime() { + if (this.timedOut) + return 0; + if (this.duration === 0) + return Infinity; + return this.start + this.duration - Math.trunc(performance.now()); } - static createFromHexString(hexString) { - if (hexString?.length !== 24) { - throw new BSONError("hex string must be 24 characters"); - } - return new ObjectId(ByteUtils.fromHex(hexString)); + get timeElapsed() { + return Math.trunc(performance.now()) - this.start; } - static createFromBase64(base647) { - if (base647?.length !== 16) { - throw new BSONError("base64 string must be 16 characters"); + constructor(executor = () => null, options) { + const duration5 = options?.duration ?? 0; + const unref = !!options?.unref; + const rejection = options?.rejection; + if (duration5 < 0) { + throw new error_1.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration"); } - return new ObjectId(ByteUtils.fromBase64(base647)); - } - static isValid(id) { - if (id == null) - return false; - if (typeof id === "string") - return ObjectId.validateHexString(id); - try { - new ObjectId(id); - return true; - } catch { - return false; + let reject; + super((_2, promiseReject) => { + reject = promiseReject; + executor(utils_1.noop, promiseReject); + }); + this.ended = null; + this.timedOut = false; + this.cleared = false; + this.duration = duration5; + this.start = Math.trunc(performance.now()); + if (rejection == null && this.duration > 0) { + this.id = (0, timers_1.setTimeout)(() => { + this.ended = Math.trunc(performance.now()); + this.timedOut = true; + reject(new TimeoutError2(`Expired after ${duration5}ms`, { duration: duration5 })); + }, this.duration); + if (typeof this.id.unref === "function" && unref) { + this.id.unref(); + } + } else if (rejection != null) { + this.ended = Math.trunc(performance.now()); + this.timedOut = true; + reject(rejection); } } - toExtendedJSON() { - if (this.toHexString) - return { $oid: this.toHexString() }; - return { $oid: this.toString("hex") }; - } - static fromExtendedJSON(doc3) { - return new ObjectId(doc3.$oid); - } - isCached() { - return ObjectId.cacheHexString && __idCache.has(this); - } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - return `new ObjectId(${inspect(this.toHexString(), options)})`; + clear() { + (0, timers_1.clearTimeout)(this.id); + this.id = undefined; + this.timedOut = false; + this.cleared = true; } - } - ObjectId.index = Math.floor(Math.random() * 16777215); - function internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined) { - let totalLength = 4 + 1; - if (Array.isArray(object3)) { - for (let i2 = 0;i2 < object3.length; i2++) { - totalLength += calculateElement(i2.toString(), object3[i2], serializeFunctions, true, ignoreUndefined); - } - } else { - if (typeof object3?.toBSON === "function") { - object3 = object3.toBSON(); - } - for (const key of Object.keys(object3)) { - totalLength += calculateElement(key, object3[key], serializeFunctions, false, ignoreUndefined); + throwIfExpired() { + if (this.timedOut) { + this.then(undefined, utils_1.squashError); + throw new TimeoutError2("Timed out", { duration: this.duration }); } } - return totalLength; - } - function calculateElement(name, value, serializeFunctions = false, isArray3 = false, ignoreUndefined = false) { - if (typeof value?.toBSON === "function") { - value = value.toBSON(); + static expires(duration5, unref) { + return new Timeout(undefined, { duration: duration5, unref }); } - switch (typeof value) { - case "string": - return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; - case "number": - if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); - } else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - } else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } - case "undefined": - if (isArray3 || !ignoreUndefined) - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - return 0; - case "boolean": - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); - case "object": - if (value != null && typeof value._bsontype === "string" && value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError; - } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; - } else if (value._bsontype === "ObjectId") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength; - } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - } else if (value._bsontype === "Decimal128") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); - } else if (value._bsontype === "Code") { - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1 + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1; - } - } else if (value._bsontype === "Binary") { - const binary = value; - if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1); - } - } else if (value._bsontype === "Symbol") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1; - } else if (value._bsontype === "DBRef") { - const ordered_values = Object.assign({ - $ref: value.collection, - $id: value.oid - }, value.fields); - if (value.db != null) { - ordered_values["$db"] = value.db; - } - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || isRegExp(value)) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value._bsontype === "BSONRegExp") { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1; - } else { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case "function": - if (serializeFunctions) { - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1; - } - return 0; - case "bigint": - return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); - case "symbol": - return 0; - default: - throw new BSONError(`Unrecognized JS type: ${typeof value}`); + static reject(rejection) { + return new Timeout(undefined, { duration: 0, unref: true, rejection }); } } - function alphabetize(str) { - return str.split("").sort().join(""); + exports.Timeout = Timeout; + function isLegacyTimeoutContextOptions(v) { + return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "waitQueueTimeoutMS" in v && typeof v.waitQueueTimeoutMS === "number"; + } + function isCSOTTimeoutContextOptions(v) { + return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "timeoutMS" in v && typeof v.timeoutMS === "number"; } - class BSONRegExp extends BSONValue { - get _bsontype() { - return "BSONRegExp"; + class TimeoutContext { + static create(options) { + if (options.session?.timeoutContext != null) + return options.session?.timeoutContext; + if (isCSOTTimeoutContextOptions(options)) + return new CSOTTimeoutContext(options); + else if (isLegacyTimeoutContextOptions(options)) + return new LegacyTimeoutContext(options); + else + throw new error_1.MongoRuntimeError("Unrecognized options"); } - constructor(pattern, options) { + } + exports.TimeoutContext = TimeoutContext; + + class CSOTTimeoutContext extends TimeoutContext { + constructor(options) { super(); - this.pattern = pattern; - this.options = alphabetize(options ?? ""); - if (this.pattern.indexOf("\x00") !== -1) { - throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`); - } - if (this.options.indexOf("\x00") !== -1) { - throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`); - } - for (let i2 = 0;i2 < this.options.length; i2++) { - if (!(this.options[i2] === "i" || this.options[i2] === "m" || this.options[i2] === "x" || this.options[i2] === "l" || this.options[i2] === "s" || this.options[i2] === "u")) { - throw new BSONError(`The regular expression option [${this.options[i2]}] is not supported`); - } - } + this.minRoundTripTime = 0; + this.start = Math.trunc(performance.now()); + this.timeoutMS = options.timeoutMS; + this.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; + this.socketTimeoutMS = options.socketTimeoutMS; + this.clearServerSelectionTimeout = false; } - static parseOptions(options) { - return options ? options.split("").sort().join("") : ""; + get maxTimeMS() { + return this.remainingTimeMS - this.minRoundTripTime; } - toExtendedJSON(options) { - options = options || {}; - if (options.legacy) { - return { $regex: this.pattern, $options: this.options }; - } - return { $regularExpression: { pattern: this.pattern, options: this.options } }; + get remainingTimeMS() { + const timePassed = Math.trunc(performance.now()) - this.start; + return this.timeoutMS <= 0 ? Infinity : this.timeoutMS - timePassed; } - static fromExtendedJSON(doc3) { - if ("$regex" in doc3) { - if (typeof doc3.$regex !== "string") { - if (doc3.$regex._bsontype === "BSONRegExp") { - return doc3; - } + csotEnabled() { + return true; + } + get serverSelectionTimeout() { + if (typeof this._serverSelectionTimeout !== "object" || this._serverSelectionTimeout?.cleared) { + const { remainingTimeMS, serverSelectionTimeoutMS } = this; + if (remainingTimeMS <= 0) + return Timeout.reject(new error_1.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`)); + const usingServerSelectionTimeoutMS = serverSelectionTimeoutMS !== 0 && (0, utils_1.csotMin)(remainingTimeMS, serverSelectionTimeoutMS) === serverSelectionTimeoutMS; + if (usingServerSelectionTimeoutMS) { + this._serverSelectionTimeout = Timeout.expires(serverSelectionTimeoutMS); } else { - return new BSONRegExp(doc3.$regex, BSONRegExp.parseOptions(doc3.$options)); + if (remainingTimeMS > 0 && Number.isFinite(remainingTimeMS)) { + this._serverSelectionTimeout = Timeout.expires(remainingTimeMS); + } else { + this._serverSelectionTimeout = null; + } } } - if ("$regularExpression" in doc3) { - return new BSONRegExp(doc3.$regularExpression.pattern, BSONRegExp.parseOptions(doc3.$regularExpression.options)); + return this._serverSelectionTimeout; + } + get connectionCheckoutTimeout() { + if (typeof this._connectionCheckoutTimeout !== "object" || this._connectionCheckoutTimeout?.cleared) { + if (typeof this._serverSelectionTimeout === "object") { + this._connectionCheckoutTimeout = this._serverSelectionTimeout; + } else { + throw new error_1.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira"); + } } - throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc3)}`); + return this._connectionCheckoutTimeout; } - inspect(depth, options, inspect) { - const stylize = getStylizeFunction(options) ?? ((v) => v); - inspect ??= defaultInspect; - const pattern = stylize(inspect(this.pattern), "regexp"); - const flags = stylize(inspect(this.options), "regexp"); - return `new BSONRegExp(${pattern}, ${flags})`; + get timeoutForSocketWrite() { + const { remainingTimeMS } = this; + if (!Number.isFinite(remainingTimeMS)) + return null; + if (remainingTimeMS > 0) + return Timeout.expires(remainingTimeMS); + return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket write")); } - } - - class BSONSymbol extends BSONValue { - get _bsontype() { - return "BSONSymbol"; + get timeoutForSocketRead() { + const { remainingTimeMS } = this; + if (!Number.isFinite(remainingTimeMS)) + return null; + if (remainingTimeMS > 0) + return Timeout.expires(remainingTimeMS); + return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket read")); } - constructor(value) { - super(); - this.value = value; + refresh() { + this.start = Math.trunc(performance.now()); + this.minRoundTripTime = 0; + this._serverSelectionTimeout?.clear(); + this._connectionCheckoutTimeout?.clear(); } - valueOf() { - return this.value; + clear() { + this._serverSelectionTimeout?.clear(); + this._connectionCheckoutTimeout?.clear(); } - toString() { - return this.value; + getRemainingTimeMSOrThrow(message) { + const { remainingTimeMS } = this; + if (remainingTimeMS <= 0) + throw new error_1.MongoOperationTimeoutError(message ?? `Expired after ${this.timeoutMS}ms`); + return remainingTimeMS; } - toJSON() { - return this.value; + clone() { + const timeoutContext = new CSOTTimeoutContext({ + timeoutMS: this.timeoutMS, + serverSelectionTimeoutMS: this.serverSelectionTimeoutMS + }); + timeoutContext.start = this.start; + return timeoutContext; } - toExtendedJSON() { - return { $symbol: this.value }; + refreshed() { + return new CSOTTimeoutContext(this); } - static fromExtendedJSON(doc3) { - return new BSONSymbol(doc3.$symbol); + addMaxTimeMSToCommand(command, options) { + if (options.omitMaxTimeMS) + return; + const maxTimeMS = this.remainingTimeMS - this.minRoundTripTime; + if (maxTimeMS > 0 && Number.isFinite(maxTimeMS)) + command.maxTimeMS = maxTimeMS; } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - return `new BSONSymbol(${inspect(this.value, options)})`; + getSocketTimeoutMS() { + return 0; } } - var LongWithoutOverridesClass = Long; + exports.CSOTTimeoutContext = CSOTTimeoutContext; - class Timestamp extends LongWithoutOverridesClass { - get _bsontype() { - return "Timestamp"; - } - get i() { - return this.low >>> 0; + class LegacyTimeoutContext extends TimeoutContext { + constructor(options) { + super(); + this.options = options; + this.clearServerSelectionTimeout = true; } - get t() { - return this.high >>> 0; + csotEnabled() { + return false; } - constructor(low) { - if (low == null) { - super(0, 0, true); - } else if (typeof low === "bigint") { - super(low, true); - } else if (Long.isLong(low)) { - super(low.low, low.high, true); - } else if (typeof low === "object" && "t" in low && "i" in low) { - if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) { - throw new BSONError("Timestamp constructed from { t, i } must provide t as a number"); - } - if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) { - throw new BSONError("Timestamp constructed from { t, i } must provide i as a number"); - } - const t2 = Number(low.t); - const i2 = Number(low.i); - if (t2 < 0 || Number.isNaN(t2)) { - throw new BSONError("Timestamp constructed from { t, i } must provide a positive t"); - } - if (i2 < 0 || Number.isNaN(i2)) { - throw new BSONError("Timestamp constructed from { t, i } must provide a positive i"); - } - if (t2 > 4294967295) { - throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max"); - } - if (i2 > 4294967295) { - throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max"); - } - super(i2, t2, true); - } else { - throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }"); - } + get serverSelectionTimeout() { + if (this.options.serverSelectionTimeoutMS != null && this.options.serverSelectionTimeoutMS > 0) + return Timeout.expires(this.options.serverSelectionTimeoutMS); + return null; } - toJSON() { - return { - $timestamp: this.toString() - }; + get connectionCheckoutTimeout() { + if (this.options.waitQueueTimeoutMS != null && this.options.waitQueueTimeoutMS > 0) + return Timeout.expires(this.options.waitQueueTimeoutMS); + return null; } - static fromInt(value) { - return new Timestamp(Long.fromInt(value, true)); + get timeoutForSocketWrite() { + return null; } - static fromNumber(value) { - return new Timestamp(Long.fromNumber(value, true)); + get timeoutForSocketRead() { + return null; } - static fromBits(lowBits, highBits) { - return new Timestamp({ i: lowBits, t: highBits }); + refresh() { + return; } - static fromString(str, optRadix) { - return new Timestamp(Long.fromString(str, true, optRadix)); + clear() { + return; } - toExtendedJSON() { - return { $timestamp: { t: this.t, i: this.i } }; + get maxTimeMS() { + return null; } - static fromExtendedJSON(doc3) { - const i2 = Long.isLong(doc3.$timestamp.i) ? doc3.$timestamp.i.getLowBitsUnsigned() : doc3.$timestamp.i; - const t2 = Long.isLong(doc3.$timestamp.t) ? doc3.$timestamp.t.getLowBitsUnsigned() : doc3.$timestamp.t; - return new Timestamp({ t: t2, i: i2 }); + refreshed() { + return new LegacyTimeoutContext(this.options); } - inspect(depth, options, inspect) { - inspect ??= defaultInspect; - const t2 = inspect(this.t, options); - const i2 = inspect(this.i, options); - return `new Timestamp({ t: ${t2}, i: ${i2} })`; + addMaxTimeMSToCommand(_command, _options) {} + getSocketTimeoutMS() { + return this.options.socketTimeoutMS; } } - Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; - var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); - var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); - function internalDeserialize(buffer2, options, isArray3) { - options = options == null ? {} : options; - const index2 = options && options.index ? options.index : 0; - const size = NumberUtils.getInt32LE(buffer2, index2); - if (size < 5) { - throw new BSONError(`bson size must be >= 5, is ${size}`); - } - if (options.allowObjectSmallerThanBufferSize && buffer2.length < size) { - throw new BSONError(`buffer length ${buffer2.length} must be >= bson size ${size}`); - } - if (!options.allowObjectSmallerThanBufferSize && buffer2.length !== size) { - throw new BSONError(`buffer length ${buffer2.length} must === bson size ${size}`); - } - if (size + index2 > buffer2.byteLength) { - throw new BSONError(`(bson size ${size} + options.index ${index2} must be <= buffer length ${buffer2.byteLength})`); + exports.LegacyTimeoutContext = LegacyTimeoutContext; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/explain.js +var require_explain = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Explain = exports.ExplainVerbosity = undefined; + exports.validateExplainTimeoutOptions = validateExplainTimeoutOptions; + exports.decorateWithExplain = decorateWithExplain; + var error_1 = require_error2(); + exports.ExplainVerbosity = Object.freeze({ + queryPlanner: "queryPlanner", + queryPlannerExtended: "queryPlannerExtended", + executionStats: "executionStats", + allPlansExecution: "allPlansExecution" + }); + + class Explain { + constructor(verbosity, maxTimeMS) { + if (typeof verbosity === "boolean") { + this.verbosity = verbosity ? exports.ExplainVerbosity.allPlansExecution : exports.ExplainVerbosity.queryPlanner; + } else { + this.verbosity = verbosity; + } + this.maxTimeMS = maxTimeMS; } - if (buffer2[index2 + size - 1] !== 0) { - throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + static fromOptions({ explain } = {}) { + if (explain == null) + return; + if (typeof explain === "boolean" || typeof explain === "string") { + return new Explain(explain); + } + const { verbosity, maxTimeMS } = explain; + return new Explain(verbosity, maxTimeMS); } - return deserializeObject(buffer2, index2, options, isArray3); } - var allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; - function deserializeObject(buffer2, index2, options, isArray3 = false) { - const fieldsAsRaw = options["fieldsAsRaw"] == null ? null : options["fieldsAsRaw"]; - const raw2 = options["raw"] == null ? false : options["raw"]; - const bsonRegExp = typeof options["bsonRegExp"] === "boolean" ? options["bsonRegExp"] : false; - const promoteBuffers = options.promoteBuffers ?? false; - const promoteLongs = options.promoteLongs ?? true; - const promoteValues = options.promoteValues ?? true; - const useBigInt64 = options.useBigInt64 ?? false; - if (useBigInt64 && !promoteValues) { - throw new BSONError("Must either request bigint or Long for int64 deserialization"); - } - if (useBigInt64 && !promoteLongs) { - throw new BSONError("Must either request bigint or Long for int64 deserialization"); - } - const validation = options.validation == null ? { utf8: true } : options.validation; - let globalUTFValidation = true; - let validationSetting; - let utf8KeysSet; - const utf8ValidatedKeys = validation.utf8; - if (typeof utf8ValidatedKeys === "boolean") { - validationSetting = utf8ValidatedKeys; - } else { - globalUTFValidation = false; - const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function(key) { - return utf8ValidatedKeys[key]; - }); - if (utf8ValidationValues.length === 0) { - throw new BSONError("UTF-8 validation setting cannot be empty"); - } - if (typeof utf8ValidationValues[0] !== "boolean") { - throw new BSONError("Invalid UTF-8 validation option, must specify boolean values"); - } - validationSetting = utf8ValidationValues[0]; - if (!utf8ValidationValues.every((item) => item === validationSetting)) { - throw new BSONError("Invalid UTF-8 validation option - keys must be all true or all false"); - } + exports.Explain = Explain; + function validateExplainTimeoutOptions(options, explain) { + const { maxTimeMS, timeoutMS } = options; + if (timeoutMS != null && (maxTimeMS != null || explain?.maxTimeMS != null)) { + throw new error_1.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands."); } - if (!globalUTFValidation) { - utf8KeysSet = new Set; - for (const key of Object.keys(utf8ValidatedKeys)) { - utf8KeysSet.add(key); - } + } + function decorateWithExplain(command, explain) { + const { verbosity, maxTimeMS } = explain; + const baseCommand = { explain: command, verbosity }; + if (typeof maxTimeMS === "number") { + baseCommand.maxTimeMS = maxTimeMS; } - const startIndex = index2; - if (buffer2.length < 5) - throw new BSONError("corrupt bson message < 5 bytes long"); - const size = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (size < 5 || size > buffer2.length) - throw new BSONError("corrupt bson message"); - const object3 = isArray3 ? [] : {}; - let arrayIndex = 0; - let isPossibleDBRef = isArray3 ? false : null; - while (true) { - const elementType = buffer2[index2++]; - if (elementType === 0) - break; - let i2 = index2; - while (buffer2[i2] !== 0 && i2 < buffer2.length) { - i2++; - } - if (i2 >= buffer2.byteLength) - throw new BSONError("Bad BSON Document: illegal CString"); - const name = isArray3 ? arrayIndex++ : ByteUtils.toUTF8(buffer2, index2, i2, false); - let shouldValidateKey = true; - if (globalUTFValidation || utf8KeysSet?.has(name)) { - shouldValidateKey = validationSetting; - } else { - shouldValidateKey = !validationSetting; - } - if (isPossibleDBRef !== false && name[0] === "$") { - isPossibleDBRef = allowedDBRefKeys.test(name); - } - let value; - index2 = i2 + 1; - if (elementType === BSON_DATA_STRING) { - const stringSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { - throw new BSONError("bad string length in bson"); - } - value = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); - index2 = index2 + stringSize; - } else if (elementType === BSON_DATA_OID) { - const oid = ByteUtils.allocateUnsafe(12); - for (let i3 = 0;i3 < 12; i3++) - oid[i3] = buffer2[index2 + i3]; - value = new ObjectId(oid); - index2 = index2 + 12; - } else if (elementType === BSON_DATA_INT && promoteValues === false) { - value = new Int32(NumberUtils.getInt32LE(buffer2, index2)); - index2 += 4; - } else if (elementType === BSON_DATA_INT) { - value = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - } else if (elementType === BSON_DATA_NUMBER) { - value = NumberUtils.getFloat64LE(buffer2, index2); - index2 += 8; - if (promoteValues === false) - value = new Double(value); - } else if (elementType === BSON_DATA_DATE) { - const lowBits = NumberUtils.getInt32LE(buffer2, index2); - const highBits = NumberUtils.getInt32LE(buffer2, index2 + 4); - index2 += 8; - value = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON_DATA_BOOLEAN) { - if (buffer2[index2] !== 0 && buffer2[index2] !== 1) - throw new BSONError("illegal boolean type value"); - value = buffer2[index2++] === 1; - } else if (elementType === BSON_DATA_OBJECT) { - const _index = index2; - const objectSize = NumberUtils.getInt32LE(buffer2, index2); - if (objectSize <= 0 || objectSize > buffer2.length - index2) - throw new BSONError("bad embedded document length in bson"); - if (raw2) { - value = buffer2.subarray(index2, index2 + objectSize); - } else { - let objectOptions = options; - if (!globalUTFValidation) { - objectOptions = { ...options, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer2, _index, objectOptions, false); - } - index2 = index2 + objectSize; - } else if (elementType === BSON_DATA_ARRAY) { - const _index = index2; - const objectSize = NumberUtils.getInt32LE(buffer2, index2); - let arrayOptions = options; - const stopIndex = index2 + objectSize; - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = { ...options, raw: true }; - } - if (!globalUTFValidation) { - arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } }; - } - value = deserializeObject(buffer2, _index, arrayOptions, true); - index2 = index2 + objectSize; - if (buffer2[index2 - 1] !== 0) - throw new BSONError("invalid array terminator byte"); - if (index2 !== stopIndex) - throw new BSONError("corrupted array bson"); - } else if (elementType === BSON_DATA_UNDEFINED) { - value = undefined; - } else if (elementType === BSON_DATA_NULL) { - value = null; - } else if (elementType === BSON_DATA_LONG) { - if (useBigInt64) { - value = NumberUtils.getBigInt64LE(buffer2, index2); - index2 += 8; - } else { - const lowBits = NumberUtils.getInt32LE(buffer2, index2); - const highBits = NumberUtils.getInt32LE(buffer2, index2 + 4); - index2 += 8; - const long = new Long(lowBits, highBits); - if (promoteLongs && promoteValues === true) { - value = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - value = long; - } - } - } else if (elementType === BSON_DATA_DECIMAL128) { - const bytes = ByteUtils.allocateUnsafe(16); - for (let i3 = 0;i3 < 16; i3++) - bytes[i3] = buffer2[index2 + i3]; - index2 = index2 + 16; - value = new Decimal128(bytes); - } else if (elementType === BSON_DATA_BINARY) { - let binarySize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - const totalBinarySize = binarySize; - const subType = buffer2[index2++]; - if (binarySize < 0) - throw new BSONError("Negative binary type element size found"); - if (binarySize > buffer2.byteLength) - throw new BSONError("Binary type size larger than document size"); - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (binarySize < 0) - throw new BSONError("Negative binary type element size found for subtype 0x02"); - if (binarySize > totalBinarySize - 4) - throw new BSONError("Binary type with subtype 0x02 contains too long binary size"); - if (binarySize < totalBinarySize - 4) - throw new BSONError("Binary type with subtype 0x02 contains too short binary size"); - } - if (promoteBuffers && promoteValues) { - value = ByteUtils.toLocalBufferType(buffer2.subarray(index2, index2 + binarySize)); - } else { - value = new Binary(buffer2.subarray(index2, index2 + binarySize), subType); - if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID2.isValid(value)) { - value = value.toUUID(); - } - } - index2 = index2 + binarySize; - } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { - i2 = index2; - while (buffer2[i2] !== 0 && i2 < buffer2.length) { - i2++; - } - if (i2 >= buffer2.length) - throw new BSONError("Bad BSON Document: illegal CString"); - const source = ByteUtils.toUTF8(buffer2, index2, i2, false); - index2 = i2 + 1; - i2 = index2; - while (buffer2[i2] !== 0 && i2 < buffer2.length) { - i2++; - } - if (i2 >= buffer2.length) - throw new BSONError("Bad BSON Document: illegal CString"); - const regExpOptions = ByteUtils.toUTF8(buffer2, index2, i2, false); - index2 = i2 + 1; - const optionsArray = new Array(regExpOptions.length); - for (i2 = 0;i2 < regExpOptions.length; i2++) { - switch (regExpOptions[i2]) { - case "m": - optionsArray[i2] = "m"; - break; - case "s": - optionsArray[i2] = "g"; - break; - case "i": - optionsArray[i2] = "i"; - break; - } - } - value = new RegExp(source, optionsArray.join("")); - } else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) { - i2 = index2; - while (buffer2[i2] !== 0 && i2 < buffer2.length) { - i2++; - } - if (i2 >= buffer2.length) - throw new BSONError("Bad BSON Document: illegal CString"); - const source = ByteUtils.toUTF8(buffer2, index2, i2, false); - index2 = i2 + 1; - i2 = index2; - while (buffer2[i2] !== 0 && i2 < buffer2.length) { - i2++; - } - if (i2 >= buffer2.length) - throw new BSONError("Bad BSON Document: illegal CString"); - const regExpOptions = ByteUtils.toUTF8(buffer2, index2, i2, false); - index2 = i2 + 1; - value = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON_DATA_SYMBOL) { - const stringSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { - throw new BSONError("bad string length in bson"); - } - const symbol3 = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); - value = promoteValues ? symbol3 : new BSONSymbol(symbol3); - index2 = index2 + stringSize; - } else if (elementType === BSON_DATA_TIMESTAMP) { - value = new Timestamp({ - i: NumberUtils.getUint32LE(buffer2, index2), - t: NumberUtils.getUint32LE(buffer2, index2 + 4) - }); - index2 += 8; - } else if (elementType === BSON_DATA_MIN_KEY) { - value = new MinKey; - } else if (elementType === BSON_DATA_MAX_KEY) { - value = new MaxKey; - } else if (elementType === BSON_DATA_CODE) { - const stringSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { - throw new BSONError("bad string length in bson"); - } - const functionString = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); - value = new Code(functionString); - index2 = index2 + stringSize; - } else if (elementType === BSON_DATA_CODE_W_SCOPE) { - const totalSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (totalSize < 4 + 4 + 4 + 1) { - throw new BSONError("code_w_scope total size shorter minimum expected length"); - } - const stringSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) { - throw new BSONError("bad string length in bson"); - } - const functionString = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); - index2 = index2 + stringSize; - const _index = index2; - const objectSize = NumberUtils.getInt32LE(buffer2, index2); - const scopeObject = deserializeObject(buffer2, _index, options, false); - index2 = index2 + objectSize; - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new BSONError("code_w_scope total size is too short, truncating scope"); - } - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new BSONError("code_w_scope total size is too long, clips outer document"); - } - value = new Code(functionString, scopeObject); - } else if (elementType === BSON_DATA_DBPOINTER) { - const stringSize = NumberUtils.getInt32LE(buffer2, index2); - index2 += 4; - if (stringSize <= 0 || stringSize > buffer2.length - index2 || buffer2[index2 + stringSize - 1] !== 0) - throw new BSONError("bad string length in bson"); - const namespace = ByteUtils.toUTF8(buffer2, index2, index2 + stringSize - 1, shouldValidateKey); - index2 = index2 + stringSize; - const oidBuffer = ByteUtils.allocateUnsafe(12); - for (let i3 = 0;i3 < 12; i3++) - oidBuffer[i3] = buffer2[index2 + i3]; - const oid = new ObjectId(oidBuffer); - index2 = index2 + 12; - value = new DBRef(namespace, oid); - } else { - throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`); - } - if (name === "__proto__") { - Object.defineProperty(object3, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } else { - object3[name] = value; + return baseCommand; + } +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/operation.js +var require_operation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AbstractOperation = exports.Aspect = undefined; + exports.defineAspects = defineAspects; + var bson_1 = require_bson2(); + var read_preference_1 = require_read_preference(); + exports.Aspect = { + READ_OPERATION: Symbol("READ_OPERATION"), + WRITE_OPERATION: Symbol("WRITE_OPERATION"), + RETRYABLE: Symbol("RETRYABLE"), + EXPLAINABLE: Symbol("EXPLAINABLE"), + SKIP_COLLATION: Symbol("SKIP_COLLATION"), + CURSOR_CREATING: Symbol("CURSOR_CREATING"), + MUST_SELECT_SAME_SERVER: Symbol("MUST_SELECT_SAME_SERVER"), + COMMAND_BATCHING: Symbol("COMMAND_BATCHING"), + SUPPORTS_RAW_DATA: Symbol("SUPPORTS_RAW_DATA") + }; + + class AbstractOperation { + constructor(options = {}) { + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) ? read_preference_1.ReadPreference.primary : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary; + this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); + this._session = options.session != null ? options.session : undefined; + this.options = options; + this.bypassPinningCheck = !!options.bypassPinningCheck; + } + hasAspect(aspect) { + const ctor = this.constructor; + if (ctor.aspects == null) { + return false; } + return ctor.aspects.has(aspect); } - if (size !== index2 - startIndex) { - if (isArray3) - throw new BSONError("corrupt array bson"); - throw new BSONError("corrupt object bson"); + get session() { + return this._session; } - if (!isPossibleDBRef) - return object3; - if (isDBRefLike(object3)) { - const copy = Object.assign({}, object3); - delete copy.$ref; - delete copy.$id; - delete copy.$db; - return new DBRef(object3.$ref, object3.$id, object3.$db, copy); + set session(session) { + this._session = session; } - return object3; - } - var regexp = /\x00/; - var ignoreKeys = new Set(["$db", "$ref", "$id", "$clusterTime"]); - function serializeString(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_STRING; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes + 1; - buffer2[index2 - 1] = 0; - const size = ByteUtils.encodeUTF8Into(buffer2, value, index2 + 4); - NumberUtils.setInt32LE(buffer2, index2, size + 1); - index2 = index2 + 4 + size; - buffer2[index2++] = 0; - return index2; - } - function serializeNumber(buffer2, key, value, index2) { - const isNegativeZero = Object.is(value, -0); - const type = !isNegativeZero && Number.isSafeInteger(value) && value <= BSON_INT32_MAX && value >= BSON_INT32_MIN ? BSON_DATA_INT : BSON_DATA_NUMBER; - buffer2[index2++] = type; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - if (type === BSON_DATA_INT) { - index2 += NumberUtils.setInt32LE(buffer2, index2, value); - } else { - index2 += NumberUtils.setFloat64LE(buffer2, index2, value); + clearSession() { + this._session = undefined; } - return index2; - } - function serializeBigInt(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_LONG; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 += numberOfWrittenBytes; - buffer2[index2++] = 0; - index2 += NumberUtils.setBigInt64LE(buffer2, index2, value); - return index2; - } - function serializeNull(buffer2, key, _2, index2) { - buffer2[index2++] = BSON_DATA_NULL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - return index2; - } - function serializeBoolean(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_BOOLEAN; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - buffer2[index2++] = value ? 1 : 0; - return index2; - } - function serializeDate(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_DATE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const dateInMilis = Long.fromNumber(value.getTime()); - const lowBits = dateInMilis.getLowBits(); - const highBits = dateInMilis.getHighBits(); - index2 += NumberUtils.setInt32LE(buffer2, index2, lowBits); - index2 += NumberUtils.setInt32LE(buffer2, index2, highBits); - return index2; - } - function serializeRegExp(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw new BSONError("value " + value.source + " must not contain null bytes"); + resetBatch() { + return true; } - index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, value.source, index2); - buffer2[index2++] = 0; - if (value.ignoreCase) - buffer2[index2++] = 105; - if (value.global) - buffer2[index2++] = 115; - if (value.multiline) - buffer2[index2++] = 109; - buffer2[index2++] = 0; - return index2; - } - function serializeBSONRegExp(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_REGEXP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - if (value.pattern.match(regexp) != null) { - throw new BSONError("pattern " + value.pattern + " must not contain null bytes"); + get canRetryRead() { + return this.hasAspect(exports.Aspect.RETRYABLE) && this.hasAspect(exports.Aspect.READ_OPERATION); } - index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, value.pattern, index2); - buffer2[index2++] = 0; - const sortedOptions = value.options.split("").sort().join(""); - index2 = index2 + ByteUtils.encodeUTF8Into(buffer2, sortedOptions, index2); - buffer2[index2++] = 0; - return index2; - } - function serializeMinMax(buffer2, key, value, index2) { - if (value === null) { - buffer2[index2++] = BSON_DATA_NULL; - } else if (value._bsontype === "MinKey") { - buffer2[index2++] = BSON_DATA_MIN_KEY; - } else { - buffer2[index2++] = BSON_DATA_MAX_KEY; + get canRetryWrite() { + return this.hasAspect(exports.Aspect.RETRYABLE) && this.hasAspect(exports.Aspect.WRITE_OPERATION); } - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - return index2; - } - function serializeObjectId(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_OID; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - index2 += value.serializeInto(buffer2, index2); - return index2; - } - function serializeBuffer(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const size = value.length; - index2 += NumberUtils.setInt32LE(buffer2, index2, size); - buffer2[index2++] = BSON_BINARY_SUBTYPE_DEFAULT; - if (size <= 16) { - for (let i2 = 0;i2 < size; i2++) - buffer2[index2 + i2] = value[i2]; - } else { - buffer2.set(value, index2); + handleOk(response) { + return response.toObject(this.bsonOptions); } - index2 = index2 + size; - return index2; - } - function serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4) { - if (path4.has(value)) { - throw new BSONError("Cannot convert circular structure to BSON"); + handleError(error91) { + throw error91; } - path4.add(value); - buffer2[index2++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const endIndex = serializeInto(buffer2, value, checkKeys, index2, depth + 1, serializeFunctions, ignoreUndefined, path4); - path4.delete(value); - return endIndex; - } - function serializeDecimal128(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_DECIMAL128; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - for (let i2 = 0;i2 < 16; i2++) - buffer2[index2 + i2] = value.bytes[i2]; - return index2 + 16; - } - function serializeLong(buffer2, key, value, index2) { - buffer2[index2++] = value._bsontype === "Long" ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const lowBits = value.getLowBits(); - const highBits = value.getHighBits(); - index2 += NumberUtils.setInt32LE(buffer2, index2, lowBits); - index2 += NumberUtils.setInt32LE(buffer2, index2, highBits); - return index2; - } - function serializeInt32(buffer2, key, value, index2) { - value = value.valueOf(); - buffer2[index2++] = BSON_DATA_INT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - index2 += NumberUtils.setInt32LE(buffer2, index2, value); - return index2; - } - function serializeDouble(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_NUMBER; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - index2 += NumberUtils.setFloat64LE(buffer2, index2, value.value); - return index2; - } - function serializeFunction(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const functionString = value.toString(); - const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; - NumberUtils.setInt32LE(buffer2, index2, size); - index2 = index2 + 4 + size - 1; - buffer2[index2++] = 0; - return index2; } - function serializeCode(buffer2, key, value, index2, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path4) { - if (value.scope && typeof value.scope === "object") { - buffer2[index2++] = BSON_DATA_CODE_W_SCOPE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - let startIndex = index2; - const functionString = value.code; - index2 = index2 + 4; - const codeSize = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; - NumberUtils.setInt32LE(buffer2, index2, codeSize); - buffer2[index2 + 4 + codeSize - 1] = 0; - index2 = index2 + codeSize + 4; - const endIndex = serializeInto(buffer2, value.scope, checkKeys, index2, depth + 1, serializeFunctions, ignoreUndefined, path4); - index2 = endIndex - 1; - const totalSize = endIndex - startIndex; - startIndex += NumberUtils.setInt32LE(buffer2, startIndex, totalSize); - buffer2[index2++] = 0; - } else { - buffer2[index2++] = BSON_DATA_CODE; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const functionString = value.code.toString(); - const size = ByteUtils.encodeUTF8Into(buffer2, functionString, index2 + 4) + 1; - NumberUtils.setInt32LE(buffer2, index2, size); - index2 = index2 + 4 + size - 1; - buffer2[index2++] = 0; + exports.AbstractOperation = AbstractOperation; + function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; } - return index2; + aspects = new Set(aspects); + Object.defineProperty(operation, "aspects", { + value: aspects, + writable: false + }); + return aspects; } - function serializeBinary(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_BINARY; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const data = value.buffer; - let size = value.position; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) - size = size + 4; - index2 += NumberUtils.setInt32LE(buffer2, index2, size); - buffer2[index2++] = value.sub_type; - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - index2 += NumberUtils.setInt32LE(buffer2, index2, size); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/command.js +var require_command = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CommandOperation = undefined; + var constants_1 = require_constants5(); + var error_1 = require_error2(); + var explain_1 = require_explain(); + var read_concern_1 = require_read_concern(); + var utils_1 = require_utils5(); + var write_concern_1 = require_write_concern(); + var operation_1 = require_operation(); + + class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + super(options); + this.options = options ?? {}; + const dbNameOverride = options?.dbName || options?.authdb; + if (dbNameOverride) { + this.ns = new utils_1.MongoDBNamespace(dbNameOverride, "$cmd"); + } else { + this.ns = parent ? parent.s.namespace.withCollection("$cmd") : new utils_1.MongoDBNamespace("admin", "$cmd"); + } + this.readConcern = read_concern_1.ReadConcern.fromOptions(options); + this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + if (this.explain) + (0, explain_1.validateExplainTimeoutOptions)(this.options, this.explain); + } else if (options?.explain != null) { + throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + } } - if (value.sub_type === Binary.SUBTYPE_VECTOR) { - validateBinaryVector(value); + get canRetryWrite() { + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + return this.explain == null; + } + return super.canRetryWrite; } - if (size <= 16) { - for (let i2 = 0;i2 < size; i2++) - buffer2[index2 + i2] = data[i2]; - } else { - buffer2.set(data, index2); + buildOptions(timeoutContext) { + return { + ...this.options, + ...this.bsonOptions, + timeoutContext, + readPreference: this.readPreference, + session: this.session + }; } - index2 = index2 + value.position; - return index2; - } - function serializeSymbol(buffer2, key, value, index2) { - buffer2[index2++] = BSON_DATA_SYMBOL; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - const size = ByteUtils.encodeUTF8Into(buffer2, value.value, index2 + 4) + 1; - NumberUtils.setInt32LE(buffer2, index2, size); - index2 = index2 + 4 + size - 1; - buffer2[index2++] = 0; - return index2; - } - function serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4) { - buffer2[index2++] = BSON_DATA_OBJECT; - const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer2, key, index2); - index2 = index2 + numberOfWrittenBytes; - buffer2[index2++] = 0; - let startIndex = index2; - let output = { - $ref: value.collection || value.namespace, - $id: value.oid - }; - if (value.db != null) { - output.$db = value.db; + buildCommand(connection, session) { + const command = this.buildCommandDocument(connection, session); + const inTransaction = this.session && this.session.inTransaction(); + if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(command) && !inTransaction) { + Object.assign(command, { readConcern: this.readConcern }); + } + if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + write_concern_1.WriteConcern.apply(command, this.writeConcern); + } + if (this.options.collation && typeof this.options.collation === "object" && !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { + Object.assign(command, { collation: this.options.collation }); + } + if (typeof this.options.maxTimeMS === "number") { + command.maxTimeMS = this.options.maxTimeMS; + } + if (this.options.rawData != null && this.hasAspect(operation_1.Aspect.SUPPORTS_RAW_DATA) && (0, utils_1.maxWireVersion)(connection) >= constants_1.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION) { + command.rawData = this.options.rawData; + } + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { + return (0, explain_1.decorateWithExplain)(command, this.explain); + } + return command; } - output = Object.assign(output, value.fields); - const endIndex = serializeInto(buffer2, output, false, index2, depth + 1, serializeFunctions, true, path4); - const size = endIndex - startIndex; - startIndex += NumberUtils.setInt32LE(buffer2, index2, size); - return endIndex; } - function serializeInto(buffer2, object3, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path4) { - if (path4 == null) { - if (object3 == null) { - buffer2[0] = 5; - buffer2[1] = 0; - buffer2[2] = 0; - buffer2[3] = 0; - buffer2[4] = 0; - return 5; + exports.CommandOperation = CommandOperation; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/aggregate.js +var require_aggregate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = undefined; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var write_concern_1 = require_write_concern(); + var command_1 = require_command(); + var operation_1 = require_operation(); + exports.DB_AGGREGATE_COLLECTION = 1; + + class AggregateOperation extends command_1.CommandOperation { + constructor(ns3, pipeline, options) { + super(undefined, { ...options, dbName: ns3.db }); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; + this.options = { ...options }; + this.target = ns3.collection || exports.DB_AGGREGATE_COLLECTION; + this.pipeline = pipeline; + this.hasWriteStage = false; + if (typeof options?.out === "string") { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } } - if (Array.isArray(object3)) { - throw new BSONError("serialize does not support an array as the root input"); + if (!this.hasWriteStage) { + delete this.options.writeConcern; } - if (typeof object3 !== "object") { - throw new BSONError("serialize does not support non-object as the root input"); - } else if ("_bsontype" in object3 && typeof object3._bsontype === "string") { - throw new BSONError(`BSON types cannot be serialized as a document`); - } else if (isDate(object3) || isRegExp(object3) || isUint8Array(object3) || isAnyArrayBuffer(object3)) { - throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); } - path4 = new Set; + if (options?.cursor != null && typeof options.cursor !== "object") { + throw new error_1.MongoInvalidArgumentError("Cursor options must be an object"); + } + this.SERVER_COMMAND_RESPONSE_TYPE = this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse; } - path4.add(object3); - let index2 = startingIndex + 4; - if (Array.isArray(object3)) { - for (let i2 = 0;i2 < object3.length; i2++) { - const key = `${i2}`; - let value = object3[i2]; - if (typeof value?.toBSON === "function") { - value = value.toBSON(); - } - const type = typeof value; - if (value === undefined) { - index2 = serializeNull(buffer2, key, value, index2); - } else if (value === null) { - index2 = serializeNull(buffer2, key, value, index2); - } else if (type === "string") { - index2 = serializeString(buffer2, key, value, index2); - } else if (type === "number") { - index2 = serializeNumber(buffer2, key, value, index2); - } else if (type === "bigint") { - index2 = serializeBigInt(buffer2, key, value, index2); - } else if (type === "boolean") { - index2 = serializeBoolean(buffer2, key, value, index2); - } else if (type === "object" && value._bsontype == null) { - if (value instanceof Date || isDate(value)) { - index2 = serializeDate(buffer2, key, value, index2); - } else if (value instanceof Uint8Array || isUint8Array(value)) { - index2 = serializeBuffer(buffer2, key, value, index2); - } else if (value instanceof RegExp || isRegExp(value)) { - index2 = serializeRegExp(buffer2, key, value, index2); - } else { - index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } - } else if (type === "object") { - if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError; - } else if (value._bsontype === "ObjectId") { - index2 = serializeObjectId(buffer2, key, value, index2); - } else if (value._bsontype === "Decimal128") { - index2 = serializeDecimal128(buffer2, key, value, index2); - } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { - index2 = serializeLong(buffer2, key, value, index2); - } else if (value._bsontype === "Double") { - index2 = serializeDouble(buffer2, key, value, index2); - } else if (value._bsontype === "Code") { - index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } else if (value._bsontype === "Binary") { - index2 = serializeBinary(buffer2, key, value, index2); - } else if (value._bsontype === "BSONSymbol") { - index2 = serializeSymbol(buffer2, key, value, index2); - } else if (value._bsontype === "DBRef") { - index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); - } else if (value._bsontype === "BSONRegExp") { - index2 = serializeBSONRegExp(buffer2, key, value, index2); - } else if (value._bsontype === "Int32") { - index2 = serializeInt32(buffer2, key, value, index2); - } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { - index2 = serializeMinMax(buffer2, key, value, index2); - } else if (typeof value._bsontype !== "undefined") { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } else if (type === "function" && serializeFunctions) { - index2 = serializeFunction(buffer2, key, value, index2); + get commandName() { + return "aggregate"; + } + get canRetryRead() { + return !this.hasWriteStage; + } + addToPipeline(stage) { + this.pipeline.push(stage); + } + buildCommandDocument() { + const options = this.options; + const command = { aggregate: this.target, pipeline: this.pipeline }; + if (this.hasWriteStage && this.writeConcern) { + write_concern_1.WriteConcern.apply(command, this.writeConcern); + } + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + if (typeof options.allowDiskUse === "boolean") { + command.allowDiskUse = options.allowDiskUse; + } + if (options.hint) { + command.hint = options.hint; + } + if (options.let) { + command.let = options.let; + } + if (options.comment !== undefined) { + command.comment = options.comment; + } + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + return command; + } + handleOk(response) { + return response; + } + } + exports.AggregateOperation = AggregateOperation; + (0, operation_1.defineAspects)(AggregateOperation, [ + operation_1.Aspect.READ_OPERATION, + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.CURSOR_CREATING, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/execute_operation.js +var require_execute_operation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.executeOperation = executeOperation; + exports.autoConnect = autoConnect; + var error_1 = require_error2(); + var read_preference_1 = require_read_preference(); + var server_selection_1 = require_server_selection(); + var timeout_1 = require_timeout(); + var utils_1 = require_utils5(); + var aggregate_1 = require_aggregate(); + var operation_1 = require_operation(); + var MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; + var MMAPv1_RETRY_WRITES_ERROR_MESSAGE = "This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string."; + async function executeOperation(client2, operation, timeoutContext) { + if (!(operation instanceof operation_1.AbstractOperation)) { + throw new error_1.MongoRuntimeError("This method requires a valid operation instance"); + } + const topology = client2.topology == null ? await (0, utils_1.abortable)(autoConnect(client2), operation.options) : client2.topology; + let session = operation.session; + let owner; + if (session == null) { + owner = Symbol(); + session = client2.startSession({ owner, explicit: false }); + } else if (session.hasEnded) { + throw new error_1.MongoExpiredSessionError("Use of expired sessions is not permitted"); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw new error_1.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later"); + } else if (session.client !== client2) { + throw new error_1.MongoInvalidArgumentError("ClientSession must be from the same MongoClient"); + } + operation.session ??= session; + const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary) && (hasReadAspect || operation.commandName === "runCommand")) { + throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); + } + if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { + session.unpin(); + } + timeoutContext ??= timeout_1.TimeoutContext.create({ + session, + serverSelectionTimeoutMS: client2.s.options.serverSelectionTimeoutMS, + waitQueueTimeoutMS: client2.s.options.waitQueueTimeoutMS, + timeoutMS: operation.options.timeoutMS + }); + try { + return await tryOperation(operation, { + topology, + timeoutContext, + session, + readPreference + }); + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession(); + } + } + } + async function autoConnect(client2) { + if (client2.topology == null) { + if (client2.s.hasBeenClosed) { + throw new error_1.MongoNotConnectedError("Client must be connected before running operations"); + } + client2.s.options.__skipPingOnConnect = true; + try { + await client2.connect(); + if (client2.topology == null) { + throw new error_1.MongoRuntimeError("client.connect did not create a topology but also did not throw"); } + return client2.topology; + } finally { + delete client2.s.options.__skipPingOnConnect; } - } else if (object3 instanceof Map || isMap(object3)) { - const iterator = object3.entries(); - let done = false; - while (!done) { - const entry = iterator.next(); - done = !!entry.done; - if (done) - continue; - const key = entry.value ? entry.value[0] : undefined; - let value = entry.value ? entry.value[1] : undefined; - if (typeof value?.toBSON === "function") { - value = value.toBSON(); + } + return client2.topology; + } + async function tryOperation(operation, { topology, timeoutContext, session, readPreference }) { + let selector; + if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) { + selector = (0, server_selection_1.sameServerSelector)(operation.server?.description); + } else if (operation instanceof aggregate_1.AggregateOperation && operation.hasWriteStage) { + selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } else { + selector = readPreference; + } + let server = await topology.selectServer(selector, { + session, + operationName: operation.commandName, + timeoutContext, + signal: operation.options.signal + }); + const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); + const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); + const inTransaction = session?.inTransaction() ?? false; + const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; + const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite; + const willRetry = operation.hasAspect(operation_1.Aspect.RETRYABLE) && session != null && (hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite); + if (hasWriteAspect && willRetryWrite && session != null) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + const maxTries = willRetry ? timeoutContext.csotEnabled() ? Infinity : 2 : 1; + let previousOperationError; + let previousServer; + for (let tries = 0;tries < maxTries; tries++) { + if (previousOperationError) { + if (hasWriteAspect && previousOperationError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + throw new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: previousOperationError + }); } - const type = typeof value; - if (typeof key === "string" && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError("key " + key + " must not contain null bytes"); - } - if (checkKeys) { - if (key[0] === "$") { - throw new BSONError("key " + key + " must not start with '$'"); - } else if (key.includes(".")) { - throw new BSONError("key " + key + " must not contain '.'"); - } - } + if (operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING) && !operation.canRetryWrite) { + throw previousOperationError; } - if (value === undefined) { - if (ignoreUndefined === false) - index2 = serializeNull(buffer2, key, value, index2); - } else if (value === null) { - index2 = serializeNull(buffer2, key, value, index2); - } else if (type === "string") { - index2 = serializeString(buffer2, key, value, index2); - } else if (type === "number") { - index2 = serializeNumber(buffer2, key, value, index2); - } else if (type === "bigint") { - index2 = serializeBigInt(buffer2, key, value, index2); - } else if (type === "boolean") { - index2 = serializeBoolean(buffer2, key, value, index2); - } else if (type === "object" && value._bsontype == null) { - if (value instanceof Date || isDate(value)) { - index2 = serializeDate(buffer2, key, value, index2); - } else if (value instanceof Uint8Array || isUint8Array(value)) { - index2 = serializeBuffer(buffer2, key, value, index2); - } else if (value instanceof RegExp || isRegExp(value)) { - index2 = serializeRegExp(buffer2, key, value, index2); - } else { - index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } - } else if (type === "object") { - if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError; - } else if (value._bsontype === "ObjectId") { - index2 = serializeObjectId(buffer2, key, value, index2); - } else if (value._bsontype === "Decimal128") { - index2 = serializeDecimal128(buffer2, key, value, index2); - } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { - index2 = serializeLong(buffer2, key, value, index2); - } else if (value._bsontype === "Double") { - index2 = serializeDouble(buffer2, key, value, index2); - } else if (value._bsontype === "Code") { - index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } else if (value._bsontype === "Binary") { - index2 = serializeBinary(buffer2, key, value, index2); - } else if (value._bsontype === "BSONSymbol") { - index2 = serializeSymbol(buffer2, key, value, index2); - } else if (value._bsontype === "DBRef") { - index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); - } else if (value._bsontype === "BSONRegExp") { - index2 = serializeBSONRegExp(buffer2, key, value, index2); - } else if (value._bsontype === "Int32") { - index2 = serializeInt32(buffer2, key, value, index2); - } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { - index2 = serializeMinMax(buffer2, key, value, index2); - } else if (typeof value._bsontype !== "undefined") { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } else if (type === "function" && serializeFunctions) { - index2 = serializeFunction(buffer2, key, value, index2); + if (hasWriteAspect && !(0, error_1.isRetryableWriteError)(previousOperationError)) + throw previousOperationError; + if (hasReadAspect && !(0, error_1.isRetryableReadError)(previousOperationError)) { + throw previousOperationError; } - } - } else { - if (typeof object3?.toBSON === "function") { - object3 = object3.toBSON(); - if (object3 != null && typeof object3 !== "object") { - throw new BSONError("toBSON function did not return an object"); + if (previousOperationError instanceof error_1.MongoNetworkError && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING) && session != null && session.isPinned && !session.inTransaction()) { + session.unpin({ force: true, forceClear: true }); + } + server = await topology.selectServer(selector, { + session, + operationName: operation.commandName, + previousServer, + signal: operation.options.signal + }); + if (hasWriteAspect && !(0, utils_1.supportsRetryableWrites)(server)) { + throw new error_1.MongoUnexpectedServerResponseError("Selected server does not support retryable writes"); } } - for (const key of Object.keys(object3)) { - let value = object3[key]; - if (typeof value?.toBSON === "function") { - value = value.toBSON(); + operation.server = server; + try { + if (tries > 0 && operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING)) { + operation.resetBatch(); } - const type = typeof value; - if (typeof key === "string" && !ignoreKeys.has(key)) { - if (key.match(regexp) != null) { - throw new BSONError("key " + key + " must not contain null bytes"); - } - if (checkKeys) { - if (key[0] === "$") { - throw new BSONError("key " + key + " must not start with '$'"); - } else if (key.includes(".")) { - throw new BSONError("key " + key + " must not contain '.'"); - } - } + try { + const result = await server.command(operation, timeoutContext); + return operation.handleOk(result); + } catch (error91) { + return operation.handleError(error91); } - if (value === undefined) { - if (ignoreUndefined === false) - index2 = serializeNull(buffer2, key, value, index2); - } else if (value === null) { - index2 = serializeNull(buffer2, key, value, index2); - } else if (type === "string") { - index2 = serializeString(buffer2, key, value, index2); - } else if (type === "number") { - index2 = serializeNumber(buffer2, key, value, index2); - } else if (type === "bigint") { - index2 = serializeBigInt(buffer2, key, value, index2); - } else if (type === "boolean") { - index2 = serializeBoolean(buffer2, key, value, index2); - } else if (type === "object" && value._bsontype == null) { - if (value instanceof Date || isDate(value)) { - index2 = serializeDate(buffer2, key, value, index2); - } else if (value instanceof Uint8Array || isUint8Array(value)) { - index2 = serializeBuffer(buffer2, key, value, index2); - } else if (value instanceof RegExp || isRegExp(value)) { - index2 = serializeRegExp(buffer2, key, value, index2); - } else { - index2 = serializeObject(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } - } else if (type === "object") { - if (value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError; - } else if (value._bsontype === "ObjectId") { - index2 = serializeObjectId(buffer2, key, value, index2); - } else if (value._bsontype === "Decimal128") { - index2 = serializeDecimal128(buffer2, key, value, index2); - } else if (value._bsontype === "Long" || value._bsontype === "Timestamp") { - index2 = serializeLong(buffer2, key, value, index2); - } else if (value._bsontype === "Double") { - index2 = serializeDouble(buffer2, key, value, index2); - } else if (value._bsontype === "Code") { - index2 = serializeCode(buffer2, key, value, index2, checkKeys, depth, serializeFunctions, ignoreUndefined, path4); - } else if (value._bsontype === "Binary") { - index2 = serializeBinary(buffer2, key, value, index2); - } else if (value._bsontype === "BSONSymbol") { - index2 = serializeSymbol(buffer2, key, value, index2); - } else if (value._bsontype === "DBRef") { - index2 = serializeDBRef(buffer2, key, value, index2, depth, serializeFunctions, path4); - } else if (value._bsontype === "BSONRegExp") { - index2 = serializeBSONRegExp(buffer2, key, value, index2); - } else if (value._bsontype === "Int32") { - index2 = serializeInt32(buffer2, key, value, index2); - } else if (value._bsontype === "MinKey" || value._bsontype === "MaxKey") { - index2 = serializeMinMax(buffer2, key, value, index2); - } else if (typeof value._bsontype !== "undefined") { - throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); - } - } else if (type === "function" && serializeFunctions) { - index2 = serializeFunction(buffer2, key, value, index2); + } catch (operationError) { + if (!(operationError instanceof error_1.MongoError)) + throw operationError; + if (previousOperationError != null && operationError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { + throw previousOperationError; } + previousServer = server.description; + previousOperationError = operationError; + timeoutContext.clear(); } } - path4.delete(object3); - buffer2[index2++] = 0; - const size = index2 - startingIndex; - startingIndex += NumberUtils.setInt32LE(buffer2, startingIndex, size); - return index2; - } - function isBSONType(value) { - return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string"; + throw previousOperationError ?? new error_1.MongoRuntimeError("Tried to propagate retryability error, but no error was found."); } - var keysToCodecs = { - $oid: ObjectId, - $binary: Binary, - $uuid: Binary, - $symbol: BSONSymbol, - $numberInt: Int32, - $numberDecimal: Decimal128, - $numberDouble: Double, - $numberLong: Long, - $minKey: MinKey, - $maxKey: MaxKey, - $regex: BSONRegExp, - $regularExpression: BSONRegExp, - $timestamp: Timestamp - }; - function deserializeValue(value, options = {}) { - if (typeof value === "number") { - const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; - const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; - if (options.relaxed || options.legacy) { - return value; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/list_databases.js +var require_list_databases = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListDatabasesOperation = undefined; + var responses_1 = require_responses(); + var utils_1 = require_utils5(); + var command_1 = require_command(); + var operation_1 = require_operation(); + + class ListDatabasesOperation extends command_1.CommandOperation { + constructor(db, options) { + super(db, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = options ?? {}; + this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); + } + get commandName() { + return "listDatabases"; + } + buildCommandDocument(connection, _session) { + const cmd = { listDatabases: 1 }; + if (typeof this.options.nameOnly === "boolean") { + cmd.nameOnly = this.options.nameOnly; } - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (in32BitRange) { - return new Int32(value); - } - if (in64BitRange) { - if (options.useBigInt64) { - return BigInt(value); - } - return Long.fromNumber(value); - } + if (this.options.filter) { + cmd.filter = this.options.filter; } - return new Double(value); + if (typeof this.options.authorizedDatabases === "boolean") { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + if ((0, utils_1.maxWireVersion)(connection) >= 9 && this.options.comment !== undefined) { + cmd.comment = this.options.comment; + } + return cmd; } - if (value == null || typeof value !== "object") - return value; - if (value.$undefined) - return null; - const keys = Object.keys(value).filter((k2) => k2.startsWith("$") && value[k2] != null); - for (let i2 = 0;i2 < keys.length; i2++) { - const c3 = keysToCodecs[keys[i2]]; - if (c3) - return c3.fromExtendedJSON(value, options); + } + exports.ListDatabasesOperation = ListDatabasesOperation; + (0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/remove_user.js +var require_remove_user = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RemoveUserOperation = undefined; + var responses_1 = require_responses(); + var command_1 = require_command(); + var operation_1 = require_operation(); + + class RemoveUserOperation extends command_1.CommandOperation { + constructor(db, username, options) { + super(db, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = options; + this.username = username; } - if (value.$date != null) { - const d = value.$date; - const date10 = new Date; - if (options.legacy) { - if (typeof d === "number") - date10.setTime(d); - else if (typeof d === "string") - date10.setTime(Date.parse(d)); - else if (typeof d === "bigint") - date10.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } else { - if (typeof d === "string") - date10.setTime(Date.parse(d)); - else if (Long.isLong(d)) - date10.setTime(d.toNumber()); - else if (typeof d === "number" && options.relaxed) - date10.setTime(d); - else if (typeof d === "bigint") - date10.setTime(Number(d)); - else - throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`); - } - return date10; + get commandName() { + return "dropUser"; + } + buildCommandDocument(_connection) { + return { dropUser: this.username }; + } + handleOk(_response) { + return true; + } + } + exports.RemoveUserOperation = RemoveUserOperation; + (0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/run_command.js +var require_run_command = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RunCursorCommandOperation = exports.RunCommandOperation = undefined; + var responses_1 = require_responses(); + var operation_1 = require_operation(); + + class RunCommandOperation extends operation_1.AbstractOperation { + constructor(namespace, command, options) { + super(options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.command = command; + this.options = options; + this.ns = namespace.withCollection("$cmd"); } - if (value.$code != null) { - const copy = Object.assign({}, value); - if (value.$scope) { - copy.$scope = deserializeValue(value.$scope); - } - return Code.fromExtendedJSON(value); + get commandName() { + return "runCommand"; } - if (isDBRefLike(value) || value.$dbPointer) { - const v = value.$ref ? value : value.$dbPointer; - if (v instanceof DBRef) - return v; - const dollarKeys = Object.keys(v).filter((k2) => k2.startsWith("$")); - let valid = true; - dollarKeys.forEach((k2) => { - if (["$ref", "$id", "$db"].indexOf(k2) === -1) - valid = false; - }); - if (valid) - return DBRef.fromExtendedJSON(v); + buildCommand(_connection, _session) { + return this.command; + } + buildOptions(timeoutContext) { + return { + ...this.options, + session: this.session, + timeoutContext, + signal: this.options.signal, + readPreference: this.options.readPreference + }; } - return value; } - function serializeArray(array3, options) { - return array3.map((v, index2) => { - options.seenObjects.push({ propertyName: `index ${index2}`, obj: null }); - try { - return serializeValue(v, options); - } finally { - options.seenObjects.pop(); - } - }); + exports.RunCommandOperation = RunCommandOperation; + + class RunCursorCommandOperation extends RunCommandOperation { + constructor() { + super(...arguments); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; + } + handleOk(response) { + return response; + } } - function getISOString(date10) { - const isoStr = date10.toISOString(); - return date10.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z"; + exports.RunCursorCommandOperation = RunCursorCommandOperation; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/validate_collection.js +var require_validate_collection = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValidateCollectionOperation = undefined; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var command_1 = require_command(); + + class ValidateCollectionOperation extends command_1.CommandOperation { + constructor(admin, collectionName, options) { + super(admin.s.db, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = options; + this.collectionName = collectionName; + } + get commandName() { + return "validate"; + } + buildCommandDocument(_connection, _session) { + return { + validate: this.collectionName, + ...Object.fromEntries(Object.entries(this.options).filter((entry) => entry[0] !== "session")) + }; + } + handleOk(response) { + const result = super.handleOk(response); + if (result.result != null && typeof result.result !== "string") + throw new error_1.MongoUnexpectedServerResponseError("Error with validation data"); + if (result.result != null && result.result.match(/exception|corrupt/) != null) + throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`); + if (result.valid != null && !result.valid) + throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`); + return response; + } } - function serializeValue(value, options) { - if (value instanceof Map || isMap(value)) { - const obj = Object.create(null); - for (const [k2, v] of value) { - if (typeof k2 !== "string") { - throw new BSONError("Can only serialize maps with string keys"); - } - obj[k2] = v; - } - return serializeValue(obj, options); + exports.ValidateCollectionOperation = ValidateCollectionOperation; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/admin.js +var require_admin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Admin = undefined; + var bson_1 = require_bson2(); + var execute_operation_1 = require_execute_operation(); + var list_databases_1 = require_list_databases(); + var remove_user_1 = require_remove_user(); + var run_command_1 = require_run_command(); + var validate_collection_1 = require_validate_collection(); + var utils_1 = require_utils5(); + + class Admin { + constructor(db) { + this.s = { db }; } - if ((typeof value === "object" || typeof value === "function") && value !== null) { - const index2 = options.seenObjects.findIndex((entry) => entry.obj === value); - if (index2 !== -1) { - const props = options.seenObjects.map((entry) => entry.propertyName); - const leadingPart = props.slice(0, index2).map((prop) => `${prop} -> `).join(""); - const alreadySeen = props[index2]; - const circularPart = " -> " + props.slice(index2 + 1, props.length - 1).map((prop) => `${prop} -> `).join(""); - const current = props[props.length - 1]; - const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2); - const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1); - throw new BSONError(`Converting circular structure to EJSON: -` + ` ${leadingPart}${alreadySeen}${circularPart}${current} -` + ` ${leadingSpace}\\${dashes}/`); - } - options.seenObjects[options.seenObjects.length - 1].obj = value; + async command(command, options) { + return await (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, { + ...(0, bson_1.resolveBSONOptions)(options), + session: options?.session, + readPreference: options?.readPreference, + timeoutMS: options?.timeoutMS ?? this.s.db.timeoutMS + })); } - if (Array.isArray(value)) - return serializeArray(value, options); - if (value === undefined) - return null; - if (value instanceof Date || isDate(value)) { - const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000; - if (options.legacy) { - return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) }; - } - return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } }; + async buildInfo(options) { + return await this.command({ buildinfo: 1 }, options); } - if (typeof value === "number" && (!options.relaxed || !isFinite(value))) { - if (Number.isInteger(value) && !Object.is(value, -0)) { - if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { - return { $numberInt: value.toString() }; - } - if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { - return { $numberLong: value.toString() }; - } - } - return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() }; + async serverInfo(options) { + return await this.command({ buildinfo: 1 }, options); } - if (typeof value === "bigint") { - if (!options.relaxed) { - return { $numberLong: BigInt.asIntN(64, value).toString() }; - } - return Number(BigInt.asIntN(64, value)); + async serverStatus(options) { + return await this.command({ serverStatus: 1 }, options); } - if (value instanceof RegExp || isRegExp(value)) { - let flags = value.flags; - if (flags === undefined) { - const match2 = value.toString().match(/[gimuy]*$/); - if (match2) { - flags = match2[0]; - } - } - const rx = new BSONRegExp(value.source, flags); - return rx.toExtendedJSON(options); + async ping(options) { + return await this.command({ ping: 1 }, options); + } + async removeUser(username, options) { + return await (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options })); + } + async validateCollection(collectionName, options = {}) { + return await (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); + } + async listDatabases(options) { + return await (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, { timeoutMS: this.s.db.timeoutMS, ...options })); + } + async replSetGetStatus(options) { + return await this.command({ replSetGetStatus: 1 }, options); } - if (value != null && typeof value === "object") - return serializeDocument(value, options); - return value; } - var BSON_TYPE_MAPPINGS = { - Binary: (o2) => new Binary(o2.value(), o2.sub_type), - Code: (o2) => new Code(o2.code, o2.scope), - DBRef: (o2) => new DBRef(o2.collection || o2.namespace, o2.oid, o2.db, o2.fields), - Decimal128: (o2) => new Decimal128(o2.bytes), - Double: (o2) => new Double(o2.value), - Int32: (o2) => new Int32(o2.value), - Long: (o2) => Long.fromBits(o2.low != null ? o2.low : o2.low_, o2.low != null ? o2.high : o2.high_, o2.low != null ? o2.unsigned : o2.unsigned_), - MaxKey: () => new MaxKey, - MinKey: () => new MinKey, - ObjectId: (o2) => new ObjectId(o2), - BSONRegExp: (o2) => new BSONRegExp(o2.pattern, o2.options), - BSONSymbol: (o2) => new BSONSymbol(o2.value), - Timestamp: (o2) => Timestamp.fromBits(o2.low, o2.high) - }; - function serializeDocument(doc3, options) { - if (doc3 == null || typeof doc3 !== "object") - throw new BSONError("not an object instance"); - const bsontype = doc3._bsontype; - if (typeof bsontype === "undefined") { - const _doc = {}; - for (const name of Object.keys(doc3)) { - options.seenObjects.push({ propertyName: name, obj: null }); - try { - const value = serializeValue(doc3[name], options); - if (name === "__proto__") { - Object.defineProperty(_doc, name, { - value, - writable: true, - enumerable: true, - configurable: true - }); - } else { - _doc[name] = value; - } - } finally { - options.seenObjects.pop(); - } + exports.Admin = Admin; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/delete.js +var require_delete = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = undefined; + exports.makeDeleteStatement = makeDeleteStatement; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var utils_1 = require_utils5(); + var command_1 = require_command(); + var operation_1 = require_operation(); + + class DeleteOperation extends command_1.CommandOperation { + constructor(ns3, statements, options) { + super(undefined, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = options; + this.ns = ns3; + this.statements = statements; + } + get commandName() { + return "delete"; + } + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; } - return _doc; - } else if (doc3 != null && typeof doc3 === "object" && typeof doc3._bsontype === "string" && doc3[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) { - throw new BSONVersionError; - } else if (isBSONType(doc3)) { - let outDoc = doc3; - if (typeof outDoc.toExtendedJSON !== "function") { - const mapper = BSON_TYPE_MAPPINGS[doc3._bsontype]; - if (!mapper) { - throw new BSONError("Unrecognized or invalid _bsontype: " + doc3._bsontype); - } - outDoc = mapper(outDoc); + return this.statements.every((op) => op.limit != null ? op.limit > 0 : true); + } + buildCommandDocument(connection, _session) { + const options = this.options; + const ordered = typeof options.ordered === "boolean" ? options.ordered : true; + const command = { + delete: this.ns.collection, + deletes: this.statements, + ordered + }; + if (options.let) { + command.let = options.let; } - if (bsontype === "Code" && outDoc.scope) { - outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options)); - } else if (bsontype === "DBRef" && outDoc.oid) { - outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options)); + if (options.comment !== undefined) { + command.comment = options.comment; } - return outDoc.toExtendedJSON(options); - } else { - throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype); - } - } - function parse15(text, options) { - const ejsonOptions = { - useBigInt64: options?.useBigInt64 ?? false, - relaxed: options?.relaxed ?? true, - legacy: options?.legacy ?? false - }; - return JSON.parse(text, (key, value) => { - if (key.indexOf("\x00") !== -1) { - throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`); + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite && (0, utils_1.maxWireVersion)(connection) < 9) { + if (this.statements.find((o2) => o2.hint)) { + throw new error_1.MongoCompatibilityError(`hint for the delete command is only supported on MongoDB 4.4+`); + } } - return deserializeValue(value, ejsonOptions); - }); + return command; + } } - function stringify5(value, replacer, space, options) { - if (space != null && typeof space === "object") { - options = space; - space = 0; + exports.DeleteOperation = DeleteOperation; + + class DeleteOneOperation extends DeleteOperation { + constructor(ns3, filter, options) { + super(ns3, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); } - if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) { - options = replacer; - replacer = undefined; - space = 0; + handleOk(response) { + const res = super.handleOk(response); + if (this.explain) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; } - const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { - seenObjects: [{ propertyName: "(root)", obj: null }] - }); - const doc3 = serializeValue(value, serializeOptions); - return JSON.stringify(doc3, replacer, space); - } - function EJSONserialize(value, options) { - options = options || {}; - return JSON.parse(stringify5(value, options)); - } - function EJSONdeserialize(ejson, options) { - options = options || {}; - return parse15(JSON.stringify(ejson), options); } - var EJSON = Object.create(null); - EJSON.parse = parse15; - EJSON.stringify = stringify5; - EJSON.serialize = EJSONserialize; - EJSON.deserialize = EJSONdeserialize; - Object.freeze(EJSON); - var BSONElementType = { - double: 1, - string: 2, - object: 3, - array: 4, - binData: 5, - undefined: 6, - objectId: 7, - bool: 8, - date: 9, - null: 10, - regex: 11, - dbPointer: 12, - javascript: 13, - symbol: 14, - javascriptWithScope: 15, - int: 16, - timestamp: 17, - long: 18, - decimal: 19, - minKey: 255, - maxKey: 127 - }; - function getSize(source, offset) { - try { - return NumberUtils.getNonnegativeInt32LE(source, offset); - } catch (cause) { - throw new BSONOffsetError("BSON size cannot be negative", offset, { cause }); + exports.DeleteOneOperation = DeleteOneOperation; + + class DeleteManyOperation extends DeleteOperation { + constructor(ns3, filter, options) { + super(ns3, [makeDeleteStatement(filter, options)], options); } - } - function findNull(bytes, offset) { - let nullTerminatorOffset = offset; - for (;bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++) - ; - if (nullTerminatorOffset === bytes.length - 1) { - throw new BSONOffsetError("Null terminator not found", offset); + handleOk(response) { + const res = super.handleOk(response); + if (this.explain) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + deletedCount: res.n + }; } - return nullTerminatorOffset; } - function parseToElements(bytes, startOffset = 0) { - startOffset ??= 0; - if (bytes.length < 5) { - throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset); + exports.DeleteManyOperation = DeleteManyOperation; + function makeDeleteStatement(filter, options) { + const op = { + q: filter, + limit: typeof options.limit === "number" ? options.limit : 0 + }; + if (options.collation) { + op.collation = options.collation; } - const documentSize = getSize(bytes, startOffset); - if (documentSize > bytes.length - startOffset) { - throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset); + if (options.hint) { + op.hint = options.hint; } - if (bytes[startOffset + documentSize - 1] !== 0) { - throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize); + return op; + } + (0, operation_1.defineAspects)(DeleteOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(DeleteOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(DeleteManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/insert.js +var require_insert = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InsertOneOperation = exports.InsertOperation = undefined; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var utils_1 = require_utils5(); + var command_1 = require_command(); + var operation_1 = require_operation(); + + class InsertOperation extends command_1.CommandOperation { + constructor(ns3, documents, options) { + super(undefined, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns3; + this.documents = documents; } - const elements = []; - let offset = startOffset + 4; - while (offset <= documentSize + startOffset) { - const type = bytes[offset]; - offset += 1; - if (type === 0) { - if (offset - startOffset !== documentSize) { - throw new BSONOffsetError(`Invalid 0x00 type byte`, offset); - } - break; + get commandName() { + return "insert"; + } + buildCommandDocument(_connection, _session) { + const options = this.options ?? {}; + const ordered = typeof options.ordered === "boolean" ? options.ordered : true; + const command = { + insert: this.ns.collection, + documents: this.documents, + ordered + }; + if (typeof options.bypassDocumentValidation === "boolean") { + command.bypassDocumentValidation = options.bypassDocumentValidation; } - const nameOffset = offset; - const nameLength = findNull(bytes, offset) - nameOffset; - offset += nameLength + 1; - let length; - if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) { - length = 8; - } else if (type === BSONElementType.int) { - length = 4; - } else if (type === BSONElementType.objectId) { - length = 12; - } else if (type === BSONElementType.decimal) { - length = 16; - } else if (type === BSONElementType.bool) { - length = 1; - } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) { - length = 0; - } else if (type === BSONElementType.regex) { - length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset; - } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) { - length = getSize(bytes, offset); - } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) { - length = getSize(bytes, offset) + 4; - if (type === BSONElementType.binData) { - length += 1; - } - if (type === BSONElementType.dbPointer) { - length += 12; - } - } else { - throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset); + if (options.comment !== undefined) { + command.comment = options.comment; } - if (length > documentSize) { - throw new BSONOffsetError("value reports length larger than document", offset); + return command; + } + } + exports.InsertOperation = InsertOperation; + + class InsertOneOperation extends InsertOperation { + constructor(collection, doc3, options) { + super(collection.s.namespace, [(0, utils_1.maybeAddIdToDocuments)(collection, doc3, options)], options); + } + handleOk(response) { + const res = super.handleOk(response); + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) { + throw new error_1.MongoServerError(res.writeErrors[0]); } - elements.push([type, nameOffset, nameLength, offset, length]); - offset += length; + return { + acknowledged: this.writeConcern?.w !== 0, + insertedId: this.documents[0]._id + }; } - return elements; } - var onDemand = Object.create(null); - onDemand.parseToElements = parseToElements; - onDemand.ByteUtils = ByteUtils; - onDemand.NumberUtils = NumberUtils; - Object.freeze(onDemand); - var MAXSIZE = 1024 * 1024 * 17; - var buffer = ByteUtils.allocate(MAXSIZE); - function setInternalBufferSize(size) { - if (buffer.length < size) { - buffer = ByteUtils.allocate(size); + exports.InsertOneOperation = InsertOneOperation; + (0, operation_1.defineAspects)(InsertOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(InsertOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sort.js +var require_sort = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatSort = formatSort; + var error_1 = require_error2(); + function prepareDirection(direction = 1) { + const value = `${direction}`.toLowerCase(); + if (isMeta(direction)) + return direction; + switch (value) { + case "ascending": + case "asc": + case "1": + return 1; + case "descending": + case "desc": + case "-1": + return -1; + default: + throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); } } - function serialize2(object3, options = {}) { - const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; - const minInternalBufferSize = typeof options.minInternalBufferSize === "number" ? options.minInternalBufferSize : MAXSIZE; - if (buffer.length < minInternalBufferSize) { - buffer = ByteUtils.allocate(minInternalBufferSize); + function isMeta(t2) { + return typeof t2 === "object" && t2 != null && "$meta" in t2 && typeof t2.$meta === "string"; + } + function isPair(t2) { + if (Array.isArray(t2) && t2.length === 2) { + try { + prepareDirection(t2[1]); + return true; + } catch { + return false; + } } - const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - const finishedBuffer = ByteUtils.allocateUnsafe(serializationIndex); - finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); - return finishedBuffer; + return false; } - function serializeWithBufferAndIndex(object3, finalBuffer, options = {}) { - const checkKeys = typeof options.checkKeys === "boolean" ? options.checkKeys : false; - const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; - const startIndex = typeof options.index === "number" ? options.index : 0; - const serializationIndex = serializeInto(buffer, object3, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); - finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); - return startIndex + serializationIndex - 1; + function isDeep(t2) { + return Array.isArray(t2) && Array.isArray(t2[0]); } - function deserialize(buffer2, options = {}) { - return internalDeserialize(ByteUtils.toLocalBufferType(buffer2), options); + function isMap(t2) { + return t2 instanceof Map && t2.size > 0; } - function calculateObjectSize(object3, options = {}) { - options = options || {}; - const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false; - const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true; - return internalCalculateObjectSize(object3, serializeFunctions, ignoreUndefined); + function isReadonlyArray2(value) { + return Array.isArray(value); } - function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); - const bufferData = ByteUtils.toLocalBufferType(data); - let index2 = startIndex; - for (let i2 = 0;i2 < numberOfDocuments; i2++) { - const size = NumberUtils.getInt32LE(bufferData, index2); - internalOptions.index = index2; - documents[docStartIndex + i2] = internalDeserialize(bufferData, internalOptions); - index2 = index2 + size; - } - return index2; + function pairToMap(v) { + return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); } - var bson = /* @__PURE__ */ Object.freeze({ - __proto__: null, - BSONError, - BSONOffsetError, - BSONRegExp, - BSONRuntimeError, - BSONSymbol, - BSONType, - BSONValue, - BSONVersionError, - Binary, - Code, - DBRef, - Decimal128, - Double, - EJSON, - Int32, - Long, - MaxKey, - MinKey, - ObjectId, - Timestamp, - UUID: UUID2, - calculateObjectSize, - deserialize, - deserializeStream, - onDemand, - serialize: serialize2, - serializeWithBufferAndIndex, - setInternalBufferSize - }); - exports.BSON = bson; - exports.BSONError = BSONError; - exports.BSONOffsetError = BSONOffsetError; - exports.BSONRegExp = BSONRegExp; - exports.BSONRuntimeError = BSONRuntimeError; - exports.BSONSymbol = BSONSymbol; - exports.BSONType = BSONType; - exports.BSONValue = BSONValue; - exports.BSONVersionError = BSONVersionError; - exports.Binary = Binary; - exports.Code = Code; - exports.DBRef = DBRef; - exports.Decimal128 = Decimal128; - exports.Double = Double; - exports.EJSON = EJSON; - exports.Int32 = Int32; - exports.Long = Long; - exports.MaxKey = MaxKey; - exports.MinKey = MinKey; - exports.ObjectId = ObjectId; - exports.Timestamp = Timestamp; - exports.UUID = UUID2; - exports.calculateObjectSize = calculateObjectSize; - exports.deserialize = deserialize; - exports.deserializeStream = deserializeStream; - exports.onDemand = onDemand; - exports.serialize = serialize2; - exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; - exports.setInternalBufferSize = setInternalBufferSize; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bson.js -var require_bson2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.toUTF8 = exports.getBigInt64LE = exports.getFloat64LE = exports.getInt32LE = exports.UUID = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.EJSON = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSONError = exports.BSON = exports.Binary = undefined; - exports.parseToElementsToArray = parseToElementsToArray; - exports.pluckBSONSerializeOptions = pluckBSONSerializeOptions; - exports.resolveBSONOptions = resolveBSONOptions; - exports.parseUtf8ValidationOption = parseUtf8ValidationOption; - var bson_1 = require_bson(); - var bson_2 = require_bson(); - Object.defineProperty(exports, "Binary", { enumerable: true, get: function() { - return bson_2.Binary; - } }); - Object.defineProperty(exports, "BSON", { enumerable: true, get: function() { - return bson_2.BSON; - } }); - Object.defineProperty(exports, "BSONError", { enumerable: true, get: function() { - return bson_2.BSONError; - } }); - Object.defineProperty(exports, "BSONRegExp", { enumerable: true, get: function() { - return bson_2.BSONRegExp; - } }); - Object.defineProperty(exports, "BSONSymbol", { enumerable: true, get: function() { - return bson_2.BSONSymbol; - } }); - Object.defineProperty(exports, "BSONType", { enumerable: true, get: function() { - return bson_2.BSONType; - } }); - Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function() { - return bson_2.calculateObjectSize; - } }); - Object.defineProperty(exports, "Code", { enumerable: true, get: function() { - return bson_2.Code; - } }); - Object.defineProperty(exports, "DBRef", { enumerable: true, get: function() { - return bson_2.DBRef; - } }); - Object.defineProperty(exports, "Decimal128", { enumerable: true, get: function() { - return bson_2.Decimal128; - } }); - Object.defineProperty(exports, "deserialize", { enumerable: true, get: function() { - return bson_2.deserialize; - } }); - Object.defineProperty(exports, "Double", { enumerable: true, get: function() { - return bson_2.Double; - } }); - Object.defineProperty(exports, "EJSON", { enumerable: true, get: function() { - return bson_2.EJSON; - } }); - Object.defineProperty(exports, "Int32", { enumerable: true, get: function() { - return bson_2.Int32; - } }); - Object.defineProperty(exports, "Long", { enumerable: true, get: function() { - return bson_2.Long; - } }); - Object.defineProperty(exports, "MaxKey", { enumerable: true, get: function() { - return bson_2.MaxKey; - } }); - Object.defineProperty(exports, "MinKey", { enumerable: true, get: function() { - return bson_2.MinKey; - } }); - Object.defineProperty(exports, "ObjectId", { enumerable: true, get: function() { - return bson_2.ObjectId; - } }); - Object.defineProperty(exports, "serialize", { enumerable: true, get: function() { - return bson_2.serialize; - } }); - Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function() { - return bson_2.Timestamp; - } }); - Object.defineProperty(exports, "UUID", { enumerable: true, get: function() { - return bson_2.UUID; - } }); - function parseToElementsToArray(bytes, offset) { - const res = bson_1.BSON.onDemand.parseToElements(bytes, offset); - return Array.isArray(res) ? res : [...res]; + function deepToMap(t2) { + const sortEntries = t2.map(([k2, v]) => [`${k2}`, prepareDirection(v)]); + return new Map(sortEntries); } - exports.getInt32LE = bson_1.BSON.onDemand.NumberUtils.getInt32LE; - exports.getFloat64LE = bson_1.BSON.onDemand.NumberUtils.getFloat64LE; - exports.getBigInt64LE = bson_1.BSON.onDemand.NumberUtils.getBigInt64LE; - exports.toUTF8 = bson_1.BSON.onDemand.ByteUtils.toUTF8; - function pluckBSONSerializeOptions(options) { - const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw: raw2, enableUtf8Validation } = options; - return { - fieldsAsRaw, - useBigInt64, - promoteValues, - promoteBuffers, - promoteLongs, - serializeFunctions, - ignoreUndefined, - bsonRegExp, - raw: raw2, - enableUtf8Validation - }; + function stringsToMap(t2) { + const sortEntries = t2.map((key) => [`${key}`, 1]); + return new Map(sortEntries); } - function resolveBSONOptions(options, parent) { - const parentOptions = parent?.bsonOptions; - return { - raw: options?.raw ?? parentOptions?.raw ?? false, - useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? false, - promoteLongs: options?.promoteLongs ?? parentOptions?.promoteLongs ?? true, - promoteValues: options?.promoteValues ?? parentOptions?.promoteValues ?? true, - promoteBuffers: options?.promoteBuffers ?? parentOptions?.promoteBuffers ?? false, - ignoreUndefined: options?.ignoreUndefined ?? parentOptions?.ignoreUndefined ?? false, - bsonRegExp: options?.bsonRegExp ?? parentOptions?.bsonRegExp ?? false, - serializeFunctions: options?.serializeFunctions ?? parentOptions?.serializeFunctions ?? false, - fieldsAsRaw: options?.fieldsAsRaw ?? parentOptions?.fieldsAsRaw ?? {}, - enableUtf8Validation: options?.enableUtf8Validation ?? parentOptions?.enableUtf8Validation ?? true - }; + function objectToMap(t2) { + const sortEntries = Object.entries(t2).map(([k2, v]) => [ + `${k2}`, + prepareDirection(v) + ]); + return new Map(sortEntries); } - function parseUtf8ValidationOption(options) { - const enableUtf8Validation = options?.enableUtf8Validation; - if (enableUtf8Validation === false) { - return { utf8: false }; + function mapToMap(t2) { + const sortEntries = Array.from(t2).map(([k2, v]) => [ + `${k2}`, + prepareDirection(v) + ]); + return new Map(sortEntries); + } + function formatSort(sort, direction) { + if (sort == null) + return; + if (typeof sort === "string") + return new Map([[sort, prepareDirection(direction)]]); + if (typeof sort !== "object") { + throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); } - return { utf8: { writeErrors: false } }; + if (!isReadonlyArray2(sort)) { + if (isMap(sort)) + return mapToMap(sort); + if (Object.keys(sort).length) + return objectToMap(sort); + return; + } + if (!sort.length) + return; + if (isDeep(sort)) + return deepToMap(sort); + if (isPair(sort)) + return pairToMap(sort); + return stringsToMap(sort); } }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/error.js -var require_error2 = __commonJS((exports) => { +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/update.js +var require_update = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.MongoWriteConcernError = exports.MongoServerSelectionError = exports.MongoSystemError = exports.MongoMissingDependencyError = exports.MongoMissingCredentialsError = exports.MongoCompatibilityError = exports.MongoInvalidArgumentError = exports.MongoParseError = exports.MongoNetworkTimeoutError = exports.MongoNetworkError = exports.MongoClientClosedError = exports.MongoTopologyClosedError = exports.MongoCursorExhaustedError = exports.MongoServerClosedError = exports.MongoCursorInUseError = exports.MongoOperationTimeoutError = exports.MongoUnexpectedServerResponseError = exports.MongoGridFSChunkError = exports.MongoGridFSStreamError = exports.MongoTailableCursorError = exports.MongoChangeStreamError = exports.MongoClientBulkWriteExecutionError = exports.MongoClientBulkWriteCursorError = exports.MongoClientBulkWriteError = exports.MongoGCPError = exports.MongoAzureError = exports.MongoOIDCError = exports.MongoAWSError = exports.MongoKerberosError = exports.MongoExpiredSessionError = exports.MongoTransactionError = exports.MongoNotConnectedError = exports.MongoDecompressionError = exports.MongoBatchReExecutionError = exports.MongoStalePrimaryError = exports.MongoRuntimeError = exports.MongoAPIError = exports.MongoDriverError = exports.MongoServerError = exports.MongoError = exports.MongoErrorLabel = exports.GET_MORE_RESUMABLE_CODES = exports.MONGODB_ERROR_CODES = exports.NODE_IS_RECOVERING_ERROR_MESSAGE = exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = undefined; - exports.needsRetryableWriteLabel = needsRetryableWriteLabel; - exports.isRetryableWriteError = isRetryableWriteError; - exports.isRetryableReadError = isRetryableReadError; - exports.isNodeShuttingDownError = isNodeShuttingDownError; - exports.isSDAMUnrecoverableError = isSDAMUnrecoverableError; - exports.isNetworkTimeoutError = isNetworkTimeoutError; - exports.isResumableError = isResumableError; - exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE = new RegExp("not master", "i"); - exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE = new RegExp("not master or secondary", "i"); - exports.NODE_IS_RECOVERING_ERROR_MESSAGE = new RegExp("node is recovering", "i"); - exports.MONGODB_ERROR_CODES = Object.freeze({ - HostUnreachable: 6, - HostNotFound: 7, - AuthenticationFailed: 18, - NetworkTimeout: 89, - ShutdownInProgress: 91, - PrimarySteppedDown: 189, - ExceededTimeLimit: 262, - SocketException: 9001, - NotWritablePrimary: 10107, - InterruptedAtShutdown: 11600, - InterruptedDueToReplStateChange: 11602, - NotPrimaryNoSecondaryOk: 13435, - NotPrimaryOrSecondary: 13436, - StaleShardVersion: 63, - StaleEpoch: 150, - StaleConfig: 13388, - RetryChangeStream: 234, - FailedToSatisfyReadPreference: 133, - CursorNotFound: 43, - LegacyNotPrimary: 10058, - WriteConcernTimeout: 64, - NamespaceNotFound: 26, - IllegalOperation: 20, - MaxTimeMSExpired: 50, - UnknownReplWriteConcern: 79, - UnsatisfiableWriteConcern: 100, - Reauthenticate: 391, - ReadConcernMajorityNotAvailableYet: 134 - }); - exports.GET_MORE_RESUMABLE_CODES = new Set([ - exports.MONGODB_ERROR_CODES.HostUnreachable, - exports.MONGODB_ERROR_CODES.HostNotFound, - exports.MONGODB_ERROR_CODES.NetworkTimeout, - exports.MONGODB_ERROR_CODES.ShutdownInProgress, - exports.MONGODB_ERROR_CODES.PrimarySteppedDown, - exports.MONGODB_ERROR_CODES.ExceededTimeLimit, - exports.MONGODB_ERROR_CODES.SocketException, - exports.MONGODB_ERROR_CODES.NotWritablePrimary, - exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, - exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, - exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, - exports.MONGODB_ERROR_CODES.StaleShardVersion, - exports.MONGODB_ERROR_CODES.StaleEpoch, - exports.MONGODB_ERROR_CODES.StaleConfig, - exports.MONGODB_ERROR_CODES.RetryChangeStream, - exports.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference, - exports.MONGODB_ERROR_CODES.CursorNotFound - ]); - exports.MongoErrorLabel = Object.freeze({ - RetryableWriteError: "RetryableWriteError", - TransientTransactionError: "TransientTransactionError", - UnknownTransactionCommitResult: "UnknownTransactionCommitResult", - ResumableChangeStreamError: "ResumableChangeStreamError", - HandshakeError: "HandshakeError", - ResetPool: "ResetPool", - PoolRequstedRetry: "PoolRequstedRetry", - InterruptInUseConnections: "InterruptInUseConnections", - NoWritesPerformed: "NoWritesPerformed" - }); - function isAggregateError(e) { - return e != null && typeof e === "object" && "errors" in e && Array.isArray(e.errors); - } + exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = undefined; + exports.makeUpdateStatement = makeUpdateStatement; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var sort_1 = require_sort(); + var utils_1 = require_utils5(); + var command_1 = require_command(); + var operation_1 = require_operation(); - class MongoError extends Error { - get errorLabels() { - return Array.from(this.errorLabelSet); + class UpdateOperation extends command_1.CommandOperation { + constructor(ns3, statements, options) { + super(undefined, options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.options = options; + this.ns = ns3; + this.statements = statements; } - constructor(message, options) { - super(message, options); - this.errorLabelSet = new Set; + get commandName() { + return "update"; } - static buildErrorMessage(e) { - if (typeof e === "string") { - return e; - } - if (isAggregateError(e) && e.message.length === 0) { - return e.errors.length === 0 ? "AggregateError has an empty errors array. Please check the `cause` property for more information." : e.errors.map(({ message }) => message).join(", "); + get canRetryWrite() { + if (super.canRetryWrite === false) { + return false; } - return e != null && typeof e === "object" && "message" in e && typeof e.message === "string" ? e.message : "empty error message"; - } - get name() { - return "MongoError"; - } - get errmsg() { - return this.message; - } - hasErrorLabel(label) { - return this.errorLabelSet.has(label); - } - addErrorLabel(label) { - this.errorLabelSet.add(label); + return this.statements.every((op) => op.multi == null || op.multi === false); } - } - exports.MongoError = MongoError; - - class MongoServerError extends MongoError { - constructor(message) { - super(message.message || message.errmsg || message.$err || "n/a"); - if (message.errorLabels) { - for (const label of message.errorLabels) - this.addErrorLabel(label); + buildCommandDocument(_connection, _session) { + const options = this.options; + const command = { + update: this.ns.collection, + updates: this.statements, + ordered: options.ordered ?? true + }; + if (typeof options.bypassDocumentValidation === "boolean") { + command.bypassDocumentValidation = options.bypassDocumentValidation; } - this.errorResponse = message; - for (const name in message) { - if (name !== "errorLabels" && name !== "errmsg" && name !== "message" && name !== "errorResponse") { - this[name] = message[name]; - } + if (options.let) { + command.let = options.let; + } + if (options.comment !== undefined) { + command.comment = options.comment; } - } - get name() { - return "MongoServerError"; + return command; } } - exports.MongoServerError = MongoServerError; + exports.UpdateOperation = UpdateOperation; - class MongoDriverError extends MongoError { - constructor(message, options) { - super(message, options); + class UpdateOneOperation extends UpdateOperation { + constructor(ns3, filter, update, options) { + super(ns3, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); + if (!(0, utils_1.hasAtomicOperators)(update, options)) { + throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } } - get name() { - return "MongoDriverError"; + handleOk(response) { + const res = super.handleOk(response); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; } } - exports.MongoDriverError = MongoDriverError; + exports.UpdateOneOperation = UpdateOneOperation; - class MongoAPIError extends MongoDriverError { - constructor(message, options) { - super(message, options); + class UpdateManyOperation extends UpdateOperation { + constructor(ns3, filter, update, options) { + super(ns3, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); + if (!(0, utils_1.hasAtomicOperators)(update, options)) { + throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } } - get name() { - return "MongoAPIError"; + handleOk(response) { + const res = super.handleOk(response); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; } } - exports.MongoAPIError = MongoAPIError; + exports.UpdateManyOperation = UpdateManyOperation; - class MongoRuntimeError extends MongoDriverError { - constructor(message, options) { - super(message, options); + class ReplaceOneOperation extends UpdateOperation { + constructor(ns3, filter, replacement, options) { + super(ns3, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators"); + } } - get name() { - return "MongoRuntimeError"; + handleOk(response) { + const res = super.handleOk(response); + if (this.explain != null) + return res; + if (res.code) + throw new error_1.MongoServerError(res); + if (res.writeErrors) + throw new error_1.MongoServerError(res.writeErrors[0]); + return { + acknowledged: this.writeConcern?.w !== 0, + modifiedCount: res.nModified ?? res.n, + upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, + upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, + matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n + }; } } - exports.MongoRuntimeError = MongoRuntimeError; - - class MongoStalePrimaryError extends MongoRuntimeError { - constructor(message, options) { - super(message, options); + exports.ReplaceOneOperation = ReplaceOneOperation; + function makeUpdateStatement(filter, update, options) { + if (filter == null || typeof filter !== "object") { + throw new error_1.MongoInvalidArgumentError("Selector must be a valid JavaScript object"); } - get name() { - return "MongoStalePrimaryError"; + if (update == null || typeof update !== "object") { + throw new error_1.MongoInvalidArgumentError("Document must be a valid JavaScript object"); } - } - exports.MongoStalePrimaryError = MongoStalePrimaryError; - - class MongoBatchReExecutionError extends MongoAPIError { - constructor(message = "This batch has already been executed, create new batch to execute") { - super(message); + const op = { q: filter, u: update }; + if (typeof options.upsert === "boolean") { + op.upsert = options.upsert; } - get name() { - return "MongoBatchReExecutionError"; + if (options.multi) { + op.multi = options.multi; } - } - exports.MongoBatchReExecutionError = MongoBatchReExecutionError; - - class MongoDecompressionError extends MongoRuntimeError { - constructor(message) { - super(message); + if (options.hint) { + op.hint = options.hint; } - get name() { - return "MongoDecompressionError"; + if (options.arrayFilters) { + op.arrayFilters = options.arrayFilters; } - } - exports.MongoDecompressionError = MongoDecompressionError; - - class MongoNotConnectedError extends MongoAPIError { - constructor(message) { - super(message); + if (options.collation) { + op.collation = options.collation; } - get name() { - return "MongoNotConnectedError"; + if (!options.multi && options.sort != null) { + op.sort = (0, sort_1.formatSort)(options.sort); } + return op; } - exports.MongoNotConnectedError = MongoNotConnectedError; + (0, operation_1.defineAspects)(UpdateOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(UpdateOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(UpdateManyOperation, [ + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.EXPLAINABLE, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); + (0, operation_1.defineAspects)(ReplaceOneOperation, [ + operation_1.Aspect.RETRYABLE, + operation_1.Aspect.WRITE_OPERATION, + operation_1.Aspect.SKIP_COLLATION, + operation_1.Aspect.SUPPORTS_RAW_DATA + ]); +}); - class MongoTransactionError extends MongoAPIError { - constructor(message) { - super(message); - } - get name() { - return "MongoTransactionError"; - } - } - exports.MongoTransactionError = MongoTransactionError; +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/common.js +var require_common5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BulkOperationBase = exports.FindOperators = exports.MongoBulkWriteError = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = undefined; + exports.mergeBatchResults = mergeBatchResults; + var bson_1 = require_bson2(); + var error_1 = require_error2(); + var delete_1 = require_delete(); + var execute_operation_1 = require_execute_operation(); + var insert_1 = require_insert(); + var update_1 = require_update(); + var timeout_1 = require_timeout(); + var utils_1 = require_utils5(); + var write_concern_1 = require_write_concern(); + exports.BatchType = Object.freeze({ + INSERT: 1, + UPDATE: 2, + DELETE: 3 + }); - class MongoExpiredSessionError extends MongoAPIError { - constructor(message = "Cannot use a session that has ended") { - super(message); - } - get name() { - return "MongoExpiredSessionError"; + class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; } } - exports.MongoExpiredSessionError = MongoExpiredSessionError; + exports.Batch = Batch; - class MongoKerberosError extends MongoRuntimeError { - constructor(message) { - super(message); - } - get name() { - return "MongoKerberosError"; + class BulkWriteResult { + static generateIdMap(ids) { + const idMap = {}; + for (const doc3 of ids) { + idMap[doc3.index] = doc3._id; + } + return idMap; } - } - exports.MongoKerberosError = MongoKerberosError; - - class MongoAWSError extends MongoRuntimeError { - constructor(message, options) { - super(message, options); + constructor(bulkResult, isOrdered) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered)); + Object.defineProperty(this, "result", { value: this.result, enumerable: false }); } - get name() { - return "MongoAWSError"; + get ok() { + return this.result.ok; } - } - exports.MongoAWSError = MongoAWSError; - - class MongoOIDCError extends MongoRuntimeError { - constructor(message) { - super(message); + getSuccessfullyInsertedIds(bulkResult, isOrdered) { + if (bulkResult.writeErrors.length === 0) + return bulkResult.insertedIds; + if (isOrdered) { + return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index); + } + return bulkResult.insertedIds.filter(({ index: index2 }) => !bulkResult.writeErrors.some((writeError) => index2 === writeError.index)); } - get name() { - return "MongoOIDCError"; + getUpsertedIdAt(index2) { + return this.result.upserted[index2]; } - } - exports.MongoOIDCError = MongoOIDCError; - - class MongoAzureError extends MongoOIDCError { - constructor(message) { - super(message); + getRawResponse() { + return this.result; } - get name() { - return "MongoAzureError"; + hasWriteErrors() { + return this.result.writeErrors.length > 0; } - } - exports.MongoAzureError = MongoAzureError; - - class MongoGCPError extends MongoOIDCError { - constructor(message) { - super(message); + getWriteErrorCount() { + return this.result.writeErrors.length; } - get name() { - return "MongoGCPError"; + getWriteErrorAt(index2) { + return index2 < this.result.writeErrors.length ? this.result.writeErrors[index2] : undefined; } - } - exports.MongoGCPError = MongoGCPError; - - class MongoClientBulkWriteError extends MongoServerError { - constructor(message) { - super(message); - this.writeConcernErrors = []; - this.writeErrors = new Map; + getWriteErrors() { + return this.result.writeErrors; } - get name() { - return "MongoClientBulkWriteError"; + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return; + } else if (this.result.writeConcernErrors.length === 1) { + return this.result.writeConcernErrors[0]; + } else { + let errmsg = ""; + for (let i2 = 0;i2 < this.result.writeConcernErrors.length; i2++) { + const err = this.result.writeConcernErrors[i2]; + errmsg = errmsg + err.errmsg; + if (i2 === 0) + errmsg = errmsg + " and "; + } + return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernTimeout }); + } } - } - exports.MongoClientBulkWriteError = MongoClientBulkWriteError; - - class MongoClientBulkWriteCursorError extends MongoRuntimeError { - constructor(message) { - super(message); + toString() { + return `BulkWriteResult(${bson_1.EJSON.stringify(this.result)})`; } - get name() { - return "MongoClientBulkWriteCursorError"; + isOk() { + return this.result.ok === 1; } } - exports.MongoClientBulkWriteCursorError = MongoClientBulkWriteCursorError; + exports.BulkWriteResult = BulkWriteResult; - class MongoClientBulkWriteExecutionError extends MongoRuntimeError { - constructor(message) { - super(message); + class WriteConcernError { + constructor(error91) { + this.serverError = error91; } - get name() { - return "MongoClientBulkWriteExecutionError"; + get code() { + return this.serverError.code; } - } - exports.MongoClientBulkWriteExecutionError = MongoClientBulkWriteExecutionError; - - class MongoChangeStreamError extends MongoRuntimeError { - constructor(message) { - super(message); + get errmsg() { + return this.serverError.errmsg; } - get name() { - return "MongoChangeStreamError"; + get errInfo() { + return this.serverError.errInfo; } - } - exports.MongoChangeStreamError = MongoChangeStreamError; - - class MongoTailableCursorError extends MongoAPIError { - constructor(message = "Tailable cursor does not support this operation") { - super(message); + toJSON() { + return this.serverError; } - get name() { - return "MongoTailableCursorError"; + toString() { + return `WriteConcernError(${this.errmsg})`; } } - exports.MongoTailableCursorError = MongoTailableCursorError; + exports.WriteConcernError = WriteConcernError; - class MongoGridFSStreamError extends MongoRuntimeError { - constructor(message) { - super(message); - } - get name() { - return "MongoGridFSStreamError"; + class WriteError { + constructor(err) { + this.err = err; } - } - exports.MongoGridFSStreamError = MongoGridFSStreamError; - - class MongoGridFSChunkError extends MongoRuntimeError { - constructor(message) { - super(message); + get code() { + return this.err.code; } - get name() { - return "MongoGridFSChunkError"; + get index() { + return this.err.index; } - } - exports.MongoGridFSChunkError = MongoGridFSChunkError; - - class MongoUnexpectedServerResponseError extends MongoRuntimeError { - constructor(message, options) { - super(message, options); + get errmsg() { + return this.err.errmsg; } - get name() { - return "MongoUnexpectedServerResponseError"; + get errInfo() { + return this.err.errInfo; } - } - exports.MongoUnexpectedServerResponseError = MongoUnexpectedServerResponseError; - - class MongoOperationTimeoutError extends MongoDriverError { - get name() { - return "MongoOperationTimeoutError"; + getOperation() { + return this.err.op; } - } - exports.MongoOperationTimeoutError = MongoOperationTimeoutError; - - class MongoCursorInUseError extends MongoAPIError { - constructor(message = "Cursor is already initialized") { - super(message); + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; } - get name() { - return "MongoCursorInUseError"; + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; } } - exports.MongoCursorInUseError = MongoCursorInUseError; - - class MongoServerClosedError extends MongoAPIError { - constructor(message = "Server is closed") { - super(message); - } - get name() { - return "MongoServerClosedError"; + exports.WriteError = WriteError; + function mergeBatchResults(batch, bulkResult, err, result) { + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; } - } - exports.MongoServerClosedError = MongoServerClosedError; - - class MongoCursorExhaustedError extends MongoAPIError { - constructor(message) { - super(message || "Cursor is exhausted"); + if (result == null) { + return; } - get name() { - return "MongoCursorExhaustedError"; + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + errInfo: result.errInfo, + op: batch.operations[0] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; } - } - exports.MongoCursorExhaustedError = MongoCursorExhaustedError; - - class MongoTopologyClosedError extends MongoAPIError { - constructor(message = "Topology is closed") { - super(message); + if (isInsertBatch(batch) && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; } - get name() { - return "MongoTopologyClosedError"; + if (isDeleteBatch(batch) && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; } - } - exports.MongoTopologyClosedError = MongoTopologyClosedError; - - class MongoClientClosedError extends MongoAPIError { - constructor() { - super("Operation interrupted because client was closed"); + let nUpserted = 0; + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + for (let i2 = 0;i2 < result.upserted.length; i2++) { + bulkResult.upserted.push({ + index: result.upserted[i2].index + batch.originalZeroIndex, + _id: result.upserted[i2]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); } - get name() { - return "MongoClientClosedError"; + if (isUpdateBatch(batch) && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + if (typeof nModified === "number") { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = 0; + } } - } - exports.MongoClientClosedError = MongoClientClosedError; - - class MongoNetworkError extends MongoError { - constructor(message, options) { - super(message, { cause: options?.cause }); - this.beforeHandshake = !!options?.beforeHandshake; + if (Array.isArray(result.writeErrors)) { + for (let i2 = 0;i2 < result.writeErrors.length; i2++) { + const writeError = { + index: batch.originalIndexes[result.writeErrors[i2].index], + code: result.writeErrors[i2].code, + errmsg: result.writeErrors[i2].errmsg, + errInfo: result.writeErrors[i2].errInfo, + op: batch.operations[result.writeErrors[i2].index] + }; + bulkResult.writeErrors.push(new WriteError(writeError)); + } } - get name() { - return "MongoNetworkError"; + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); } } - exports.MongoNetworkError = MongoNetworkError; - - class MongoNetworkTimeoutError extends MongoNetworkError { - constructor(message, options) { - super(message, options); + async function executeCommands(bulkOperation, options) { + if (bulkOperation.s.batches.length === 0) { + return new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); } - get name() { - return "MongoNetworkTimeoutError"; + for (const batch of bulkOperation.s.batches) { + const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { + ...options, + ordered: bulkOperation.isOrdered + }); + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + if (bulkOperation.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + if (bulkOperation.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + if (finalOptions.retryWrites) { + if (isUpdateBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.multi); + } + if (isDeleteBatch(batch)) { + finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.limit === 0); + } + } + const operation = isInsertBatch(batch) ? new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isUpdateBatch(batch) ? new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isDeleteBatch(batch) ? new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : null; + if (operation == null) + throw new error_1.MongoRuntimeError(`Unknown batchType: ${batch.batchType}`); + let thrownError = null; + let result; + try { + result = await (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, operation, finalOptions.timeoutContext); + } catch (error91) { + thrownError = error91; + } + if (thrownError != null) { + if (thrownError instanceof error_1.MongoWriteConcernError) { + mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); + const writeResult3 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + throw new MongoBulkWriteError({ + message: thrownError.result.writeConcernError.errmsg, + code: thrownError.result.writeConcernError.code + }, writeResult3); + } else { + throw new MongoBulkWriteError(thrownError, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)); + } + } + mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); + const writeResult2 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + bulkOperation.handleWriteError(writeResult2); } + bulkOperation.s.batches.length = 0; + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + bulkOperation.handleWriteError(writeResult); + return writeResult; } - exports.MongoNetworkTimeoutError = MongoNetworkTimeoutError; - class MongoParseError extends MongoDriverError { - constructor(message) { - super(message); + class MongoBulkWriteError extends error_1.MongoServerError { + constructor(error91, result) { + super(error91); + this.writeErrors = []; + if (error91 instanceof WriteConcernError) + this.err = error91; + else if (!(error91 instanceof Error)) { + this.message = error91.message; + this.code = error91.code; + this.writeErrors = error91.writeErrors ?? []; + } + this.result = result; + Object.assign(this, error91); } get name() { - return "MongoParseError"; - } - } - exports.MongoParseError = MongoParseError; - - class MongoInvalidArgumentError extends MongoAPIError { - constructor(message, options) { - super(message, options); + return "MongoBulkWriteError"; } - get name() { - return "MongoInvalidArgumentError"; + get insertedCount() { + return this.result.insertedCount; } - } - exports.MongoInvalidArgumentError = MongoInvalidArgumentError; - - class MongoCompatibilityError extends MongoAPIError { - constructor(message) { - super(message); + get matchedCount() { + return this.result.matchedCount; } - get name() { - return "MongoCompatibilityError"; + get modifiedCount() { + return this.result.modifiedCount; } - } - exports.MongoCompatibilityError = MongoCompatibilityError; - - class MongoMissingCredentialsError extends MongoAPIError { - constructor(message) { - super(message); + get deletedCount() { + return this.result.deletedCount; } - get name() { - return "MongoMissingCredentialsError"; + get upsertedCount() { + return this.result.upsertedCount; } - } - exports.MongoMissingCredentialsError = MongoMissingCredentialsError; - - class MongoMissingDependencyError extends MongoAPIError { - constructor(message, options) { - super(message, options); - this.dependencyName = options.dependencyName; + get insertedIds() { + return this.result.insertedIds; } - get name() { - return "MongoMissingDependencyError"; + get upsertedIds() { + return this.result.upsertedIds; } } - exports.MongoMissingDependencyError = MongoMissingDependencyError; + exports.MongoBulkWriteError = MongoBulkWriteError; - class MongoSystemError extends MongoError { - constructor(message, reason) { - if (reason && reason.error) { - super(MongoError.buildErrorMessage(reason.error.message || reason.error), { - cause: reason.error - }); - } else { - super(message); - } - if (reason) { - this.reason = reason; - } - this.code = reason.error?.code; - } - get name() { - return "MongoSystemError"; + class FindOperators { + constructor(bulkOperation) { + this.bulkOperation = bulkOperation; } - } - exports.MongoSystemError = MongoSystemError; - - class MongoServerSelectionError extends MongoSystemError { - constructor(message, reason) { - super(message, reason); + update(updateDocument) { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { + ...currentOp, + multi: true + })); } - get name() { - return "MongoServerSelectionError"; + updateOne(updateDocument) { + if (!(0, utils_1.hasAtomicOperators)(updateDocument, this.bulkOperation.bsonOptions)) { + throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); } - } - exports.MongoServerSelectionError = MongoServerSelectionError; - - class MongoWriteConcernError extends MongoServerError { - constructor(result) { - super({ ...result.writeConcernError, ...result }); - this.errInfo = result.writeConcernError.errInfo; - this.result = result; + replaceOne(replacement) { + if ((0, utils_1.hasAtomicOperators)(replacement)) { + throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); + } + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); } - get name() { - return "MongoWriteConcernError"; + deleteOne() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); } - } - exports.MongoWriteConcernError = MongoWriteConcernError; - var RETRYABLE_READ_ERROR_CODES = new Set([ - exports.MONGODB_ERROR_CODES.HostUnreachable, - exports.MONGODB_ERROR_CODES.HostNotFound, - exports.MONGODB_ERROR_CODES.NetworkTimeout, - exports.MONGODB_ERROR_CODES.ShutdownInProgress, - exports.MONGODB_ERROR_CODES.PrimarySteppedDown, - exports.MONGODB_ERROR_CODES.SocketException, - exports.MONGODB_ERROR_CODES.NotWritablePrimary, - exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, - exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, - exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary, - exports.MONGODB_ERROR_CODES.ExceededTimeLimit, - exports.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet - ]); - var RETRYABLE_WRITE_ERROR_CODES = RETRYABLE_READ_ERROR_CODES; - function needsRetryableWriteLabel(error91, maxWireVersion, serverType) { - if (error91 instanceof MongoNetworkError) { - return true; + delete() { + const currentOp = buildCurrentOp(this.bulkOperation); + return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); } - if (error91 instanceof MongoError) { - if ((maxWireVersion >= 9 || isRetryableWriteError(error91)) && !error91.hasErrorLabel(exports.MongoErrorLabel.HandshakeError)) { - return false; + upsert() { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; } + this.bulkOperation.s.currentOp.upsert = true; + return this; } - if (error91 instanceof MongoWriteConcernError) { - if (serverType === "Mongos" && maxWireVersion < 9) { - return RETRYABLE_WRITE_ERROR_CODES.has(error91.result.code ?? 0); + collation(collation) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; } - const code = error91.result.writeConcernError.code ?? Number(error91.code); - return RETRYABLE_WRITE_ERROR_CODES.has(Number.isNaN(code) ? 0 : code); - } - if (error91 instanceof MongoError) { - return RETRYABLE_WRITE_ERROR_CODES.has(Number(error91.code)); + this.bulkOperation.s.currentOp.collation = collation; + return this; } - const isNotWritablePrimaryError2 = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error91.message); - if (isNotWritablePrimaryError2) { - return true; + arrayFilters(arrayFilters) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; + return this; } - const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error91.message); - if (isNodeIsRecoveringError) { - return true; + hint(hint) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.hint = hint; + return this; } - return false; - } - function isRetryableWriteError(error91) { - return error91.hasErrorLabel(exports.MongoErrorLabel.RetryableWriteError) || error91.hasErrorLabel(exports.MongoErrorLabel.PoolRequstedRetry); } - function isRetryableReadError(error91) { - const hasRetryableErrorCode = typeof error91.code === "number" ? RETRYABLE_READ_ERROR_CODES.has(error91.code) : false; - if (hasRetryableErrorCode) { - return true; - } - if (error91 instanceof MongoNetworkError) { - return true; - } - const isNotWritablePrimaryError2 = exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(error91.message); - if (isNotWritablePrimaryError2) { - return true; + exports.FindOperators = FindOperators; + + class BulkOperationBase { + constructor(collection, options, isOrdered) { + this.collection = collection; + this.isOrdered = isOrdered; + const topology = (0, utils_1.getTopology)(collection); + options = options == null ? {} : options; + const namespace = collection.s.namespace; + const executed = false; + const currentOp = undefined; + const hello = topology.lastHello(); + const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); + const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; + const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; + const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + let finalOptions = Object.assign({}, options); + finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.db); + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + this.s = { + bulkResult, + currentBatch: undefined, + currentIndex: 0, + currentBatchSize: 0, + currentBatchSizeBytes: 0, + currentInsertBatch: undefined, + currentUpdateBatch: undefined, + currentRemoveBatch: undefined, + batches: [], + writeConcern: write_concern_1.WriteConcern.fromOptions(options), + maxBsonObjectSize, + maxBatchSizeBytes, + maxWriteBatchSize, + maxKeySize, + namespace, + topology, + options: finalOptions, + bsonOptions: (0, bson_1.resolveBSONOptions)(options), + currentOp, + executed, + collection, + err: undefined, + checkKeys: typeof options.checkKeys === "boolean" ? options.checkKeys : false + }; + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } } - const isNodeIsRecoveringError = exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(error91.message); - if (isNodeIsRecoveringError) { - return true; + insert(document2) { + (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { + forceServerObjectId: this.shouldForceServerObjectId() + }); + return this.addToOperationsList(exports.BatchType.INSERT, document2); } - return false; - } - var SDAM_RECOVERING_CODES = new Set([ - exports.MONGODB_ERROR_CODES.ShutdownInProgress, - exports.MONGODB_ERROR_CODES.PrimarySteppedDown, - exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, - exports.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange, - exports.MONGODB_ERROR_CODES.NotPrimaryOrSecondary - ]); - var SDAM_NOT_PRIMARY_CODES = new Set([ - exports.MONGODB_ERROR_CODES.NotWritablePrimary, - exports.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk, - exports.MONGODB_ERROR_CODES.LegacyNotPrimary - ]); - var SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - exports.MONGODB_ERROR_CODES.InterruptedAtShutdown, - exports.MONGODB_ERROR_CODES.ShutdownInProgress - ]); - function isRecoveringError(err) { - if (typeof err.code === "number") { - return SDAM_RECOVERING_CODES.has(err.code); + find(selector) { + if (!selector) { + throw new error_1.MongoInvalidArgumentError("Bulk find operation must specify a selector"); + } + this.s.currentOp = { + selector + }; + return new FindOperators(this); } - return exports.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(err.message) || exports.NODE_IS_RECOVERING_ERROR_MESSAGE.test(err.message); - } - function isNotWritablePrimaryError(err) { - if (typeof err.code === "number") { - return SDAM_NOT_PRIMARY_CODES.has(err.code); + raw(op) { + if (op == null || typeof op !== "object") { + throw new error_1.MongoInvalidArgumentError("Operation must be an object with an operation key"); + } + if ("insertOne" in op) { + const forceServerObjectId = this.shouldForceServerObjectId(); + const document2 = op.insertOne && op.insertOne.document == null ? op.insertOne : op.insertOne.document; + (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { forceServerObjectId }); + return this.addToOperationsList(exports.BatchType.INSERT, document2); + } + if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) { + if ("replaceOne" in op) { + if ("q" in op.replaceOne) { + throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); + if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { + throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ("updateOne" in op) { + if ("q" in op.updateOne) { + throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { + ...op.updateOne, + multi: false + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { + throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + if ("updateMany" in op) { + if ("q" in op.updateMany) { + throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } + const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { + ...op.updateMany, + multi: true + }); + if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { + throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } + return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } + } + if ("deleteOne" in op) { + if ("q" in op.deleteOne) { + throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); + } + if ("deleteMany" in op) { + if ("q" in op.deleteMany) { + throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } + return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); + } + throw new error_1.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany"); } - if (isRecoveringError(err)) { - return false; + get length() { + return this.s.currentIndex; } - return exports.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(err.message); - } - function isNodeShuttingDownError(err) { - return !!(typeof err.code === "number" && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code)); - } - function isSDAMUnrecoverableError(error91) { - if (error91 instanceof MongoParseError || error91 == null) { - return true; + get bsonOptions() { + return this.s.bsonOptions; } - return isRecoveringError(error91) || isNotWritablePrimaryError(error91); - } - function isNetworkTimeoutError(err) { - return !!(err instanceof MongoNetworkError && err.message.match(/timed out/)); - } - function isResumableError(error91, wireVersion) { - if (error91 == null || !(error91 instanceof MongoError)) { - return false; + get writeConcern() { + return this.s.writeConcern; } - if (error91 instanceof MongoNetworkError) { - return true; + get batches() { + const batches = [...this.s.batches]; + if (this.isOrdered) { + if (this.s.currentBatch) + batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) + batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + batches.push(this.s.currentRemoveBatch); + } + return batches; } - if (error91 instanceof MongoServerSelectionError) { - return true; + async execute(options = {}) { + if (this.s.executed) { + throw new error_1.MongoBatchReExecutionError; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options); + if (writeConcern) { + this.s.writeConcern = writeConcern; + } + if (this.isOrdered) { + if (this.s.currentBatch) + this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) + this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) + this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) + this.s.batches.push(this.s.currentRemoveBatch); + } + if (this.s.batches.length === 0) { + throw new error_1.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty"); + } + this.s.executed = true; + const finalOptions = (0, utils_1.resolveOptions)(this.collection, { ...this.s.options, ...options }); + finalOptions.timeoutContext ??= timeout_1.TimeoutContext.create({ + session: finalOptions.session, + timeoutMS: finalOptions.timeoutMS, + serverSelectionTimeoutMS: this.collection.client.s.options.serverSelectionTimeoutMS, + waitQueueTimeoutMS: this.collection.client.s.options.waitQueueTimeoutMS + }); + if (finalOptions.session == null) { + return await this.collection.client.withSession({ explicit: false }, async (session) => { + return await executeCommands(this, { ...finalOptions, session }); + }); + } + return await executeCommands(this, { ...finalOptions }); } - if (wireVersion != null && wireVersion >= 9) { - if (error91.code === exports.MONGODB_ERROR_CODES.CursorNotFound) { - return true; + handleWriteError(writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + const msg = this.s.bulkResult.writeErrors[0].errmsg ? this.s.bulkResult.writeErrors[0].errmsg : "write operation failed"; + throw new MongoBulkWriteError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }, writeResult); + } + const writeConcernError = writeResult.getWriteConcernError(); + if (writeConcernError) { + throw new MongoBulkWriteError(writeConcernError, writeResult); } - return error91.hasErrorLabel(exports.MongoErrorLabel.ResumableChangeStreamError); } - if (typeof error91.code === "number") { - return exports.GET_MORE_RESUMABLE_CODES.has(error91.code); + shouldForceServerObjectId() { + return this.s.options.forceServerObjectId === true || this.s.collection.db.options?.forceServerObjectId === true; } - return false; + } + exports.BulkOperationBase = BulkOperationBase; + function isInsertBatch(batch) { + return batch.batchType === exports.BatchType.INSERT; + } + function isUpdateBatch(batch) { + return batch.batchType === exports.BatchType.UPDATE; + } + function isDeleteBatch(batch) { + return batch.batchType === exports.BatchType.DELETE; + } + function buildCurrentOp(bulkOp) { + let { currentOp } = bulkOp.s; + bulkOp.s.currentOp = undefined; + if (!currentOp) + currentOp = {}; + return currentOp; } }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/read_preference.js -var require_read_preference = __commonJS((exports) => { +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/ordered.js +var require_ordered = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReadPreference = exports.ReadPreferenceMode = undefined; + exports.OrderedBulkOperation = undefined; + var BSON = require_bson2(); var error_1 = require_error2(); - exports.ReadPreferenceMode = Object.freeze({ - primary: "primary", - primaryPreferred: "primaryPreferred", - secondary: "secondary", - secondaryPreferred: "secondaryPreferred", - nearest: "nearest" - }); + var common_1 = require_common5(); - class ReadPreference { - constructor(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new error_1.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(mode)}`); + class OrderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, true); + } + addToOperationsList(batchType, document2) { + const bsonSize = BSON.calculateObjectSize(document2, { + checkKeys: false, + ignoreUndefined: false + }); + if (bsonSize >= this.s.maxBsonObjectSize) + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } - if (options == null && typeof tags === "object" && !Array.isArray(tags)) { - options = tags; - tags = undefined; - } else if (tags && !Array.isArray(tags)) { - throw new error_1.MongoInvalidArgumentError("ReadPreference tags must be an array"); + const maxKeySize = this.s.maxKeySize; + if (this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || this.s.currentBatchSize > 0 && this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || this.s.currentBatch.batchType !== batchType) { + this.s.batches.push(this.s.currentBatch); + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + this.s.currentBatchSize = 0; + this.s.currentBatchSizeBytes = 0; } - this.mode = mode; - this.tags = tags; - this.hedge = options?.hedge; - this.maxStalenessSeconds = undefined; - this.minWireVersion = undefined; - options = options ?? {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new error_1.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer"); - } - this.maxStalenessSeconds = options.maxStalenessSeconds; - this.minWireVersion = 5; + if (batchType === common_1.BatchType.INSERT) { + this.s.bulkResult.insertedIds.push({ + index: this.s.currentIndex, + _id: document2._id + }); } - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with tags"); - } - if (this.maxStalenessSeconds) { - throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds"); - } - if (this.hedge) { - throw new error_1.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge"); - } + if (Array.isArray(document2)) { + throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); } + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentBatch.operations.push(document2); + this.s.currentBatchSize += 1; + this.s.currentBatchSizeBytes += maxKeySize + bsonSize; + this.s.currentIndex += 1; + return this; } - get preference() { - return this.mode; - } - static fromString(mode) { - return new ReadPreference(mode); + } + exports.OrderedBulkOperation = OrderedBulkOperation; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/unordered.js +var require_unordered = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UnorderedBulkOperation = undefined; + var BSON = require_bson2(); + var error_1 = require_error2(); + var common_1 = require_common5(); + + class UnorderedBulkOperation extends common_1.BulkOperationBase { + constructor(collection, options) { + super(collection, options, false); } - static fromOptions(options) { - if (!options) - return; - const readPreference = options.readPreference ?? options.session?.transaction.options.readPreference; - const readPreferenceTags = options.readPreferenceTags; - if (readPreference == null) { + handleWriteError(writeResult) { + if (this.s.batches.length) { return; } - if (typeof readPreference === "string") { - return new ReadPreference(readPreference, readPreferenceTags, { - maxStalenessSeconds: options.maxStalenessSeconds, - hedge: options.hedge - }); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === "object") { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === "string") { - return new ReadPreference(mode, readPreference.tags ?? readPreferenceTags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds, - hedge: options.hedge - }); - } + return super.handleWriteError(writeResult); + } + addToOperationsList(batchType, document2) { + const bsonSize = BSON.calculateObjectSize(document2, { + checkKeys: false, + ignoreUndefined: false + }); + if (bsonSize >= this.s.maxBsonObjectSize) { + throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); } - if (readPreferenceTags) { - readPreference.tags = readPreferenceTags; + this.s.currentBatch = undefined; + if (batchType === common_1.BatchType.INSERT) { + this.s.currentBatch = this.s.currentInsertBatch; + } else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentBatch = this.s.currentUpdateBatch; + } else if (batchType === common_1.BatchType.DELETE) { + this.s.currentBatch = this.s.currentRemoveBatch; } - return readPreference; - } - static translate(options) { - if (options.readPreference == null) - return options; - const r2 = options.readPreference; - if (typeof r2 === "string") { - options.readPreference = new ReadPreference(r2); - } else if (r2 && !(r2 instanceof ReadPreference) && typeof r2 === "object") { - const mode = r2.mode || r2.preference; - if (mode && typeof mode === "string") { - options.readPreference = new ReadPreference(mode, r2.tags, { - maxStalenessSeconds: r2.maxStalenessSeconds - }); - } - } else if (!(r2 instanceof ReadPreference)) { - throw new error_1.MongoInvalidArgumentError(`Invalid read preference: ${r2}`); + const maxKeySize = this.s.maxKeySize; + if (this.s.currentBatch == null) { + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); } - return options; - } - static isValid(mode) { - const VALID_MODES = new Set([ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null - ]); - return VALID_MODES.has(mode); - } - isValid(mode) { - return ReadPreference.isValid(typeof mode === "string" ? mode : this.mode); - } - secondaryOk() { - const NEEDS_SECONDARYOK = new Set([ - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST - ]); - return NEEDS_SECONDARYOK.has(this.mode); - } - equals(readPreference) { - return readPreference.mode === this.mode; - } - toJSON() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) - readPreference.tags = this.tags; - if (this.maxStalenessSeconds) - readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - if (this.hedge) - readPreference.hedge = this.hedge; - return readPreference; + if (this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || this.s.currentBatch.size > 0 && this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || this.s.currentBatch.batchType !== batchType) { + this.s.batches.push(this.s.currentBatch); + this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + } + if (Array.isArray(document2)) { + throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); + } + this.s.currentBatch.operations.push(document2); + this.s.currentBatch.originalIndexes.push(this.s.currentIndex); + this.s.currentIndex = this.s.currentIndex + 1; + if (batchType === common_1.BatchType.INSERT) { + this.s.currentInsertBatch = this.s.currentBatch; + this.s.bulkResult.insertedIds.push({ + index: this.s.bulkResult.insertedIds.length, + _id: document2._id + }); + } else if (batchType === common_1.BatchType.UPDATE) { + this.s.currentUpdateBatch = this.s.currentBatch; + } else if (batchType === common_1.BatchType.DELETE) { + this.s.currentRemoveBatch = this.s.currentBatch; + } + this.s.currentBatch.size += 1; + this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + return this; } } - exports.ReadPreference = ReadPreference; - ReadPreference.PRIMARY = exports.ReadPreferenceMode.primary; - ReadPreference.PRIMARY_PREFERRED = exports.ReadPreferenceMode.primaryPreferred; - ReadPreference.SECONDARY = exports.ReadPreferenceMode.secondary; - ReadPreference.SECONDARY_PREFERRED = exports.ReadPreferenceMode.secondaryPreferred; - ReadPreference.NEAREST = exports.ReadPreferenceMode.nearest; - ReadPreference.primary = new ReadPreference(exports.ReadPreferenceMode.primary); - ReadPreference.primaryPreferred = new ReadPreference(exports.ReadPreferenceMode.primaryPreferred); - ReadPreference.secondary = new ReadPreference(exports.ReadPreferenceMode.secondary); - ReadPreference.secondaryPreferred = new ReadPreference(exports.ReadPreferenceMode.secondaryPreferred); - ReadPreference.nearest = new ReadPreference(exports.ReadPreferenceMode.nearest); + exports.UnorderedBulkOperation = UnorderedBulkOperation; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sdam/common.js -var require_common4 = __commonJS((exports) => { +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/mongo_logger.js +var require_mongo_logger = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.ServerType = exports.TopologyType = exports.STATE_CONNECTED = exports.STATE_CONNECTING = exports.STATE_CLOSED = exports.STATE_CLOSING = undefined; - exports._advanceClusterTime = _advanceClusterTime; - exports.STATE_CLOSING = "closing"; - exports.STATE_CLOSED = "closed"; - exports.STATE_CONNECTING = "connecting"; - exports.STATE_CONNECTED = "connected"; - exports.TopologyType = Object.freeze({ - Single: "Single", - ReplicaSetNoPrimary: "ReplicaSetNoPrimary", - ReplicaSetWithPrimary: "ReplicaSetWithPrimary", - Sharded: "Sharded", - Unknown: "Unknown", - LoadBalanced: "LoadBalanced" - }); - exports.ServerType = Object.freeze({ - Standalone: "Standalone", - Mongos: "Mongos", - PossiblePrimary: "PossiblePrimary", - RSPrimary: "RSPrimary", - RSSecondary: "RSSecondary", - RSArbiter: "RSArbiter", - RSOther: "RSOther", - RSGhost: "RSGhost", - Unknown: "Unknown", - LoadBalancer: "LoadBalancer" + exports.MongoLogger = exports.MongoLoggableComponent = exports.SEVERITY_LEVEL_MAP = exports.DEFAULT_MAX_DOCUMENT_LENGTH = exports.SeverityLevel = undefined; + exports.parseSeverityFromString = parseSeverityFromString; + exports.createStdioLogger = createStdioLogger; + exports.stringifyWithMaxLen = stringifyWithMaxLen; + exports.defaultLogTransform = defaultLogTransform; + var util_1 = __require("util"); + var bson_1 = require_bson2(); + var constants_1 = require_constants6(); + var utils_1 = require_utils5(); + exports.SeverityLevel = Object.freeze({ + EMERGENCY: "emergency", + ALERT: "alert", + CRITICAL: "critical", + ERROR: "error", + WARNING: "warn", + NOTICE: "notice", + INFORMATIONAL: "info", + DEBUG: "debug", + TRACE: "trace", + OFF: "off" }); - function _advanceClusterTime(entity, $clusterTime) { - if (entity.clusterTime == null) { - entity.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(entity.clusterTime.clusterTime)) { - entity.clusterTime = $clusterTime; + exports.DEFAULT_MAX_DOCUMENT_LENGTH = 1000; + + class SeverityLevelMap extends Map { + constructor(entries) { + const newEntries = []; + for (const [level, value] of entries) { + newEntries.push([value, level]); } + newEntries.push(...entries); + super(newEntries); + } + getNumericSeverityLevel(severity) { + return this.get(severity); + } + getSeverityLevelName(level) { + return this.get(level); } } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sdam/server_selection.js -var require_server_selection = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MIN_SECONDARY_WRITE_WIRE_VERSION = undefined; - exports.writableServerSelector = writableServerSelector; - exports.sameServerSelector = sameServerSelector; - exports.secondaryWritableServerSelector = secondaryWritableServerSelector; - exports.readPreferenceServerSelector = readPreferenceServerSelector; - var error_1 = require_error2(); - var read_preference_1 = require_read_preference(); - var common_1 = require_common4(); - var IDLE_WRITE_PERIOD = 1e4; - var SMALLEST_MAX_STALENESS_SECONDS = 90; - exports.MIN_SECONDARY_WRITE_WIRE_VERSION = 13; - function writableServerSelector() { - return function writableServer(topologyDescription, servers) { - return latencyWindowReducer(topologyDescription, servers.filter((s) => s.isWritable)); - }; + exports.SEVERITY_LEVEL_MAP = new SeverityLevelMap([ + [exports.SeverityLevel.OFF, -Infinity], + [exports.SeverityLevel.EMERGENCY, 0], + [exports.SeverityLevel.ALERT, 1], + [exports.SeverityLevel.CRITICAL, 2], + [exports.SeverityLevel.ERROR, 3], + [exports.SeverityLevel.WARNING, 4], + [exports.SeverityLevel.NOTICE, 5], + [exports.SeverityLevel.INFORMATIONAL, 6], + [exports.SeverityLevel.DEBUG, 7], + [exports.SeverityLevel.TRACE, 8] + ]); + exports.MongoLoggableComponent = Object.freeze({ + COMMAND: "command", + TOPOLOGY: "topology", + SERVER_SELECTION: "serverSelection", + CONNECTION: "connection", + CLIENT: "client" + }); + function parseSeverityFromString(s) { + const validSeverities = Object.values(exports.SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity; + } + return null; } - function sameServerSelector(description) { - return function sameServerSelector2(topologyDescription, servers) { - if (!description) - return []; - return servers.filter((sd) => { - return sd.address === description.address && sd.type !== common_1.ServerType.Unknown; - }); + function createStdioLogger(stream2) { + return { + write: (0, util_1.promisify)((log2, cb) => { + const logLine = (0, util_1.inspect)(log2, { compact: true, breakLength: Infinity }); + stream2.write(`${logLine} +`, "utf-8", cb); + return; + }) }; } - function secondaryWritableServerSelector(wireVersion, readPreference) { - if (!readPreference || !wireVersion || wireVersion && wireVersion < exports.MIN_SECONDARY_WRITE_WIRE_VERSION) { - return readPreferenceServerSelector(read_preference_1.ReadPreference.primary); + function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { + if (typeof mongodbLogPath === "string" && /^stderr$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; } - return readPreferenceServerSelector(readPreference); - } - function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; + if (typeof mongodbLogPath === "string" && /^stdout$/i.test(mongodbLogPath)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; } - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${maxStalenessVariance} seconds`); + if (typeof mongodbLogPath === "object" && typeof mongodbLogPath?.write === "function") { + return { mongodbLogPath, mongodbLogPathIsStdErr: false }; } - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new error_1.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds`); + if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; } - if (topologyDescription.type === common_1.TopologyType.ReplicaSetWithPrimary) { - const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = server.lastUpdateTime - server.lastWriteDate - (primary.lastUpdateTime - primary.lastWriteDate) + topologyDescription.heartbeatFrequencyMS; - const staleness = stalenessMS / 1000; - const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; - if (staleness <= maxStalenessSeconds) { - result.push(server); - } - return result; - }, []); + if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) { + return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; } - if (topologyDescription.type === common_1.TopologyType.ReplicaSetNoPrimary) { - if (servers.length === 0) { - return servers; + return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + } + function resolveSeverityConfiguration(clientOption, environmentOption, defaultSeverity) { + return parseSeverityFromString(clientOption) ?? parseSeverityFromString(environmentOption) ?? defaultSeverity; + } + function compareSeverity(s0, s1) { + const s0Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0); + const s1Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1); + return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0; + } + function stringifyWithMaxLen(value, maxDocumentLength, options = {}) { + let strToTruncate = ""; + let currentLength = 0; + const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer2(key, value2) { + if (currentLength >= maxDocumentLength) { + return; } - const sMax = servers.reduce((max, s) => s.lastWriteDate > max.lastWriteDate ? s : max); - return servers.reduce((result, server) => { - const stalenessMS = sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - const staleness = stalenessMS / 1000; - const maxStalenessSeconds = readPreference.maxStalenessSeconds ?? 0; - if (staleness <= maxStalenessSeconds) { - result.push(server); + if (key === "") { + currentLength += 1; + return value2; + } + currentLength += key.length + 4; + if (value2 == null) + return value2; + switch (typeof value2) { + case "string": + currentLength += value2.length + 2; + break; + case "number": + case "bigint": + currentLength += String(value2).length; + break; + case "boolean": + currentLength += value2 ? 4 : 5; + break; + case "object": + if ((0, utils_1.isUint8Array)(value2)) { + currentLength += 22 + value2.byteLength + value2.byteLength * 0.33 + 18 | 0; + } else if ("_bsontype" in value2) { + const v = value2; + switch (v._bsontype) { + case "Int32": + currentLength += String(v.value).length; + break; + case "Double": + currentLength += (v.value | 0) === v.value ? String(v.value).length + 2 : String(v.value).length; + break; + case "Long": + currentLength += v.toString().length; + break; + case "ObjectId": + currentLength += 35; + break; + case "MaxKey": + case "MinKey": + currentLength += 13; + break; + case "Binary": + currentLength += 22 + value2.position + value2.position * 0.33 + 18 | 0; + break; + case "Timestamp": + currentLength += 19 + String(v.t).length + 5 + String(v.i).length + 2; + break; + case "Code": + if (v.scope == null) { + currentLength += v.code.length + 10 + 2; + } else { + currentLength += v.code.length + 10 + 11; + } + break; + case "BSONRegExp": + currentLength += 34 + v.pattern.length + 13 + v.options.length + 3; + break; + } + } + } + return value2; + }; + if (typeof value === "string") { + strToTruncate = value; + } else if (typeof value === "function") { + strToTruncate = value.name; + } else { + try { + if (maxDocumentLength !== 0) { + strToTruncate = bson_1.EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options); + } else { + strToTruncate = bson_1.EJSON.stringify(value, options); } - return result; - }, []); - } - return servers; - } - function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i2 = 0;i2 < keys.length; ++i2) { - const key = keys[i2]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; + } catch (e) { + strToTruncate = `Extended JSON serialization failed with: ${e.message}`; } } - return true; - } - function tagSetReducer(readPreference, servers) { - if (readPreference.tags == null || Array.isArray(readPreference.tags) && readPreference.tags.length === 0) { - return servers; - } - for (let i2 = 0;i2 < readPreference.tags.length; ++i2) { - const tagSet = readPreference.tags[i2]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) - matched.push(server); - return matched; - }, []); - if (serversMatchingTagset.length) { - return serversMatchingTagset; + if (maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength && strToTruncate.charCodeAt(maxDocumentLength - 1) !== strToTruncate.codePointAt(maxDocumentLength - 1)) { + maxDocumentLength--; + if (maxDocumentLength === 0) { + return ""; } } - return []; + return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength ? `${strToTruncate.slice(0, maxDocumentLength)}...` : strToTruncate; } - function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce((min, server) => Math.min(server.roundTripTime, min), Infinity); - const high = low + topologyDescription.localThresholdMS; - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) - result.push(server); - return result; - }, []); + function isLogConvertible(obj) { + const objAsLogConvertible = obj; + return objAsLogConvertible.toLog !== undefined && typeof objAsLogConvertible.toLog === "function"; } - function primaryFilter(server) { - return server.type === common_1.ServerType.RSPrimary; + function attachServerSelectionFields(log2, serverSelectionEvent, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { + const { selector, operation, topologyDescription, message } = serverSelectionEvent; + log2.selector = stringifyWithMaxLen(selector, maxDocumentLength); + log2.operation = operation; + log2.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength); + log2.message = message; + return log2; } - function secondaryFilter(server) { - return server.type === common_1.ServerType.RSSecondary; + function attachCommandFields(log2, commandEvent) { + log2.commandName = commandEvent.commandName; + log2.requestId = commandEvent.requestId; + log2.driverConnectionId = commandEvent.connectionId; + const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort(); + log2.serverHost = host; + log2.serverPort = port; + if (commandEvent?.serviceId) { + log2.serviceId = commandEvent.serviceId.toHexString(); + } + log2.databaseName = commandEvent.databaseName; + log2.serverConnectionId = commandEvent.serverConnectionId; + return log2; } - function nearestFilter(server) { - return server.type === common_1.ServerType.RSSecondary || server.type === common_1.ServerType.RSPrimary; + function attachConnectionFields(log2, event) { + const { host, port } = utils_1.HostAddress.fromString(event.address).toHostPort(); + log2.serverHost = host; + log2.serverPort = port; + return log2; } - function knownFilter(server) { - return server.type !== common_1.ServerType.Unknown; + function attachSDAMFields(log2, sdamEvent) { + log2.topologyId = sdamEvent.topologyId; + return log2; } - function loadBalancerFilter(server) { - return server.type === common_1.ServerType.LoadBalancer; + function attachServerHeartbeatFields(log2, serverHeartbeatEvent) { + const { awaited, connectionId } = serverHeartbeatEvent; + log2.awaited = awaited; + log2.driverConnectionId = serverHeartbeatEvent.connectionId; + const { host, port } = utils_1.HostAddress.fromString(connectionId).toHostPort(); + log2.serverHost = host; + log2.serverPort = port; + return log2; } - function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new error_1.MongoInvalidArgumentError("Invalid read preference specified"); - } - return function readPreferenceServers(topologyDescription, servers, deprioritized = []) { - if (topologyDescription.type === common_1.TopologyType.LoadBalanced) { - return servers.filter(loadBalancerFilter); - } - if (topologyDescription.type === common_1.TopologyType.Unknown) { - return []; - } - if (topologyDescription.type === common_1.TopologyType.Single) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - if (topologyDescription.type === common_1.TopologyType.Sharded) { - const filtered = servers.filter((server) => { - return !deprioritized.includes(server); - }); - const selectable = filtered.length > 0 ? filtered : deprioritized; - return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter)); - } - const mode = readPreference.mode; - if (mode === read_preference_1.ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - if (mode === read_preference_1.ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; + function defaultLogTransform(logObject, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { + let log2 = Object.create(null); + switch (logObject.name) { + case constants_1.SERVER_SELECTION_STARTED: + log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); + return log2; + case constants_1.SERVER_SELECTION_FAILED: + log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); + log2.failure = logObject.failure?.message; + return log2; + case constants_1.SERVER_SELECTION_SUCCEEDED: + log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); + log2.serverHost = logObject.serverHost; + log2.serverPort = logObject.serverPort; + return log2; + case constants_1.WAITING_FOR_SUITABLE_SERVER: + log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); + log2.remainingTimeMS = logObject.remainingTimeMS; + return log2; + case constants_1.COMMAND_STARTED: + log2 = attachCommandFields(log2, logObject); + log2.message = "Command started"; + log2.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true }); + log2.databaseName = logObject.databaseName; + return log2; + case constants_1.COMMAND_SUCCEEDED: + log2 = attachCommandFields(log2, logObject); + log2.message = "Command succeeded"; + log2.durationMS = logObject.duration; + log2.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log2; + case constants_1.COMMAND_FAILED: + log2 = attachCommandFields(log2, logObject); + log2.message = "Command failed"; + log2.durationMS = logObject.duration; + log2.failure = logObject.failure?.message ?? "(redacted)"; + return log2; + case constants_1.CONNECTION_POOL_CREATED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection pool created"; + if (logObject.options) { + const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options; + log2 = { + ...log2, + maxIdleTimeMS, + minPoolSize, + maxPoolSize, + maxConnecting, + waitQueueTimeoutMS + }; } - } - const filter = mode === read_preference_1.ReadPreference.NEAREST ? nearestFilter : secondaryFilter; - const selectedServers = latencyWindowReducer(topologyDescription, tagSetReducer(readPreference, maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)))); - if (mode === read_preference_1.ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { - return servers.filter(primaryFilter); - } - return selectedServers; - }; - } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/constants.js -var require_constants5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_DELETE = exports.OP_QUERY = exports.OP_INSERT = exports.OP_UPDATE = exports.OP_REPLY = exports.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = exports.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = exports.MIN_SUPPORTED_QE_SERVER_VERSION = exports.MIN_SUPPORTED_QE_WIRE_VERSION = exports.MAX_SUPPORTED_WIRE_VERSION = exports.MIN_SUPPORTED_WIRE_VERSION = exports.MAX_SUPPORTED_SERVER_VERSION = exports.MIN_SUPPORTED_SERVER_VERSION = undefined; - exports.MIN_SUPPORTED_SERVER_VERSION = "4.2"; - exports.MAX_SUPPORTED_SERVER_VERSION = "8.2"; - exports.MIN_SUPPORTED_WIRE_VERSION = 8; - exports.MAX_SUPPORTED_WIRE_VERSION = 27; - exports.MIN_SUPPORTED_QE_WIRE_VERSION = 21; - exports.MIN_SUPPORTED_QE_SERVER_VERSION = "7.0"; - exports.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION = 27; - exports.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION = "8.2"; - exports.OP_REPLY = 1; - exports.OP_UPDATE = 2001; - exports.OP_INSERT = 2002; - exports.OP_QUERY = 2004; - exports.OP_DELETE = 2006; - exports.OP_COMPRESSED = 2012; - exports.OP_MSG = 2013; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/constants.js -var require_constants6 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.END = exports.CHANGE = exports.INIT = exports.MORE = exports.RESPONSE = exports.SERVER_HEARTBEAT_FAILED = exports.SERVER_HEARTBEAT_SUCCEEDED = exports.SERVER_HEARTBEAT_STARTED = exports.COMMAND_FAILED = exports.COMMAND_SUCCEEDED = exports.COMMAND_STARTED = exports.CLUSTER_TIME_RECEIVED = exports.CONNECTION_CHECKED_IN = exports.CONNECTION_CHECKED_OUT = exports.CONNECTION_CHECK_OUT_FAILED = exports.CONNECTION_CHECK_OUT_STARTED = exports.CONNECTION_CLOSED = exports.CONNECTION_READY = exports.CONNECTION_CREATED = exports.CONNECTION_POOL_READY = exports.CONNECTION_POOL_CLEARED = exports.CONNECTION_POOL_CLOSED = exports.CONNECTION_POOL_CREATED = exports.WAITING_FOR_SUITABLE_SERVER = exports.SERVER_SELECTION_SUCCEEDED = exports.SERVER_SELECTION_FAILED = exports.SERVER_SELECTION_STARTED = exports.TOPOLOGY_DESCRIPTION_CHANGED = exports.TOPOLOGY_CLOSED = exports.TOPOLOGY_OPENING = exports.SERVER_DESCRIPTION_CHANGED = exports.SERVER_CLOSED = exports.SERVER_OPENING = exports.DESCRIPTION_RECEIVED = exports.UNPINNED = exports.PINNED = exports.MESSAGE = exports.ENDED = exports.CLOSED = exports.CONNECT = exports.OPEN = exports.CLOSE = exports.TIMEOUT = exports.ERROR = exports.SYSTEM_JS_COLLECTION = exports.SYSTEM_COMMAND_COLLECTION = exports.SYSTEM_USER_COLLECTION = exports.SYSTEM_PROFILE_COLLECTION = exports.SYSTEM_INDEX_COLLECTION = exports.SYSTEM_NAMESPACE_COLLECTION = undefined; - exports.kDecoratedKeys = exports.kDecorateResult = exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = exports.LEGACY_HELLO_COMMAND = exports.MONGO_CLIENT_EVENTS = exports.LOCAL_SERVER_EVENTS = exports.SERVER_RELAY_EVENTS = exports.APM_EVENTS = exports.TOPOLOGY_EVENTS = exports.CMAP_EVENTS = exports.HEARTBEAT_EVENTS = exports.RESUME_TOKEN_CHANGED = undefined; - exports.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; - exports.SYSTEM_INDEX_COLLECTION = "system.indexes"; - exports.SYSTEM_PROFILE_COLLECTION = "system.profile"; - exports.SYSTEM_USER_COLLECTION = "system.users"; - exports.SYSTEM_COMMAND_COLLECTION = "$cmd"; - exports.SYSTEM_JS_COLLECTION = "system.js"; - exports.ERROR = "error"; - exports.TIMEOUT = "timeout"; - exports.CLOSE = "close"; - exports.OPEN = "open"; - exports.CONNECT = "connect"; - exports.CLOSED = "closed"; - exports.ENDED = "ended"; - exports.MESSAGE = "message"; - exports.PINNED = "pinned"; - exports.UNPINNED = "unpinned"; - exports.DESCRIPTION_RECEIVED = "descriptionReceived"; - exports.SERVER_OPENING = "serverOpening"; - exports.SERVER_CLOSED = "serverClosed"; - exports.SERVER_DESCRIPTION_CHANGED = "serverDescriptionChanged"; - exports.TOPOLOGY_OPENING = "topologyOpening"; - exports.TOPOLOGY_CLOSED = "topologyClosed"; - exports.TOPOLOGY_DESCRIPTION_CHANGED = "topologyDescriptionChanged"; - exports.SERVER_SELECTION_STARTED = "serverSelectionStarted"; - exports.SERVER_SELECTION_FAILED = "serverSelectionFailed"; - exports.SERVER_SELECTION_SUCCEEDED = "serverSelectionSucceeded"; - exports.WAITING_FOR_SUITABLE_SERVER = "waitingForSuitableServer"; - exports.CONNECTION_POOL_CREATED = "connectionPoolCreated"; - exports.CONNECTION_POOL_CLOSED = "connectionPoolClosed"; - exports.CONNECTION_POOL_CLEARED = "connectionPoolCleared"; - exports.CONNECTION_POOL_READY = "connectionPoolReady"; - exports.CONNECTION_CREATED = "connectionCreated"; - exports.CONNECTION_READY = "connectionReady"; - exports.CONNECTION_CLOSED = "connectionClosed"; - exports.CONNECTION_CHECK_OUT_STARTED = "connectionCheckOutStarted"; - exports.CONNECTION_CHECK_OUT_FAILED = "connectionCheckOutFailed"; - exports.CONNECTION_CHECKED_OUT = "connectionCheckedOut"; - exports.CONNECTION_CHECKED_IN = "connectionCheckedIn"; - exports.CLUSTER_TIME_RECEIVED = "clusterTimeReceived"; - exports.COMMAND_STARTED = "commandStarted"; - exports.COMMAND_SUCCEEDED = "commandSucceeded"; - exports.COMMAND_FAILED = "commandFailed"; - exports.SERVER_HEARTBEAT_STARTED = "serverHeartbeatStarted"; - exports.SERVER_HEARTBEAT_SUCCEEDED = "serverHeartbeatSucceeded"; - exports.SERVER_HEARTBEAT_FAILED = "serverHeartbeatFailed"; - exports.RESPONSE = "response"; - exports.MORE = "more"; - exports.INIT = "init"; - exports.CHANGE = "change"; - exports.END = "end"; - exports.RESUME_TOKEN_CHANGED = "resumeTokenChanged"; - exports.HEARTBEAT_EVENTS = Object.freeze([ - exports.SERVER_HEARTBEAT_STARTED, - exports.SERVER_HEARTBEAT_SUCCEEDED, - exports.SERVER_HEARTBEAT_FAILED - ]); - exports.CMAP_EVENTS = Object.freeze([ - exports.CONNECTION_POOL_CREATED, - exports.CONNECTION_POOL_READY, - exports.CONNECTION_POOL_CLEARED, - exports.CONNECTION_POOL_CLOSED, - exports.CONNECTION_CREATED, - exports.CONNECTION_READY, - exports.CONNECTION_CLOSED, - exports.CONNECTION_CHECK_OUT_STARTED, - exports.CONNECTION_CHECK_OUT_FAILED, - exports.CONNECTION_CHECKED_OUT, - exports.CONNECTION_CHECKED_IN - ]); - exports.TOPOLOGY_EVENTS = Object.freeze([ - exports.SERVER_OPENING, - exports.SERVER_CLOSED, - exports.SERVER_DESCRIPTION_CHANGED, - exports.TOPOLOGY_OPENING, - exports.TOPOLOGY_CLOSED, - exports.TOPOLOGY_DESCRIPTION_CHANGED, - exports.ERROR, - exports.TIMEOUT, - exports.CLOSE - ]); - exports.APM_EVENTS = Object.freeze([ - exports.COMMAND_STARTED, - exports.COMMAND_SUCCEEDED, - exports.COMMAND_FAILED - ]); - exports.SERVER_RELAY_EVENTS = Object.freeze([ - exports.SERVER_HEARTBEAT_STARTED, - exports.SERVER_HEARTBEAT_SUCCEEDED, - exports.SERVER_HEARTBEAT_FAILED, - exports.COMMAND_STARTED, - exports.COMMAND_SUCCEEDED, - exports.COMMAND_FAILED, - ...exports.CMAP_EVENTS - ]); - exports.LOCAL_SERVER_EVENTS = Object.freeze([ - exports.CONNECT, - exports.DESCRIPTION_RECEIVED, - exports.CLOSED, - exports.ENDED - ]); - exports.MONGO_CLIENT_EVENTS = Object.freeze([ - ...exports.CMAP_EVENTS, - ...exports.APM_EVENTS, - ...exports.TOPOLOGY_EVENTS, - ...exports.HEARTBEAT_EVENTS - ]); - exports.LEGACY_HELLO_COMMAND = "ismaster"; - exports.LEGACY_HELLO_COMMAND_CAMEL_CASE = "isMaster"; - exports.kDecorateResult = Symbol.for("@@mdb.decorateDecryptionResult"); - exports.kDecoratedKeys = Symbol.for("@@mdb.decryptedKeys"); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/read_concern.js -var require_read_concern = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReadConcern = exports.ReadConcernLevel = undefined; - exports.ReadConcernLevel = Object.freeze({ - local: "local", - majority: "majority", - linearizable: "linearizable", - available: "available", - snapshot: "snapshot" - }); - - class ReadConcern { - constructor(level) { - this.level = exports.ReadConcernLevel[level] ?? level; - } - static fromOptions(options) { - if (options == null) { - return; - } - if (options.readConcern) { - const { readConcern } = options; - if (readConcern instanceof ReadConcern) { - return readConcern; - } else if (typeof readConcern === "string") { - return new ReadConcern(readConcern); - } else if ("level" in readConcern && readConcern.level) { - return new ReadConcern(readConcern.level); + return log2; + case constants_1.CONNECTION_POOL_READY: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection pool ready"; + return log2; + case constants_1.CONNECTION_POOL_CLEARED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection pool cleared"; + if (logObject.serviceId?._bsontype === "ObjectId") { + log2.serviceId = logObject.serviceId?.toHexString(); + } + return log2; + case constants_1.CONNECTION_POOL_CLOSED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection pool closed"; + return log2; + case constants_1.CONNECTION_CREATED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection created"; + log2.driverConnectionId = logObject.connectionId; + return log2; + case constants_1.CONNECTION_READY: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection ready"; + log2.driverConnectionId = logObject.connectionId; + log2.durationMS = logObject.durationMS; + return log2; + case constants_1.CONNECTION_CLOSED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection closed"; + log2.driverConnectionId = logObject.connectionId; + switch (logObject.reason) { + case "stale": + log2.reason = "Connection became stale because the pool was cleared"; + break; + case "idle": + log2.reason = "Connection has been available but unused for longer than the configured max idle time"; + break; + case "error": + log2.reason = "An error occurred while using the connection"; + if (logObject.error) { + log2.error = logObject.error; + } + break; + case "poolClosed": + log2.reason = "Connection pool was closed"; + break; + default: + log2.reason = `Unknown close reason: ${logObject.reason}`; + } + return log2; + case constants_1.CONNECTION_CHECK_OUT_STARTED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection checkout started"; + return log2; + case constants_1.CONNECTION_CHECK_OUT_FAILED: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection checkout failed"; + switch (logObject.reason) { + case "poolClosed": + log2.reason = "Connection pool was closed"; + break; + case "timeout": + log2.reason = "Wait queue timeout elapsed without a connection becoming available"; + break; + case "connectionError": + log2.reason = "An error occurred while trying to establish a new connection"; + if (logObject.error) { + log2.error = logObject.error; + } + break; + default: + log2.reason = `Unknown close reason: ${logObject.reason}`; + } + log2.durationMS = logObject.durationMS; + return log2; + case constants_1.CONNECTION_CHECKED_OUT: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection checked out"; + log2.driverConnectionId = logObject.connectionId; + log2.durationMS = logObject.durationMS; + return log2; + case constants_1.CONNECTION_CHECKED_IN: + log2 = attachConnectionFields(log2, logObject); + log2.message = "Connection checked in"; + log2.driverConnectionId = logObject.connectionId; + return log2; + case constants_1.SERVER_OPENING: + log2 = attachSDAMFields(log2, logObject); + log2 = attachConnectionFields(log2, logObject); + log2.message = "Starting server monitoring"; + return log2; + case constants_1.SERVER_CLOSED: + log2 = attachSDAMFields(log2, logObject); + log2 = attachConnectionFields(log2, logObject); + log2.message = "Stopped server monitoring"; + return log2; + case constants_1.SERVER_HEARTBEAT_STARTED: + log2 = attachSDAMFields(log2, logObject); + log2 = attachServerHeartbeatFields(log2, logObject); + log2.message = "Server heartbeat started"; + return log2; + case constants_1.SERVER_HEARTBEAT_SUCCEEDED: + log2 = attachSDAMFields(log2, logObject); + log2 = attachServerHeartbeatFields(log2, logObject); + log2.message = "Server heartbeat succeeded"; + log2.durationMS = logObject.duration; + log2.serverConnectionId = logObject.serverConnectionId; + log2.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); + return log2; + case constants_1.SERVER_HEARTBEAT_FAILED: + log2 = attachSDAMFields(log2, logObject); + log2 = attachServerHeartbeatFields(log2, logObject); + log2.message = "Server heartbeat failed"; + log2.durationMS = logObject.duration; + log2.failure = logObject.failure?.message; + return log2; + case constants_1.TOPOLOGY_OPENING: + log2 = attachSDAMFields(log2, logObject); + log2.message = "Starting topology monitoring"; + return log2; + case constants_1.TOPOLOGY_CLOSED: + log2 = attachSDAMFields(log2, logObject); + log2.message = "Stopped topology monitoring"; + return log2; + case constants_1.TOPOLOGY_DESCRIPTION_CHANGED: + log2 = attachSDAMFields(log2, logObject); + log2.message = "Topology description changed"; + log2.previousDescription = log2.reply = stringifyWithMaxLen(logObject.previousDescription, maxDocumentLength); + log2.newDescription = log2.reply = stringifyWithMaxLen(logObject.newDescription, maxDocumentLength); + return log2; + default: + for (const [key, value] of Object.entries(logObject)) { + if (value != null) + log2[key] = value; } - } - if (options.level) { - return new ReadConcern(options.level); - } - return; - } - static get MAJORITY() { - return exports.ReadConcernLevel.majority; - } - static get AVAILABLE() { - return exports.ReadConcernLevel.available; - } - static get LINEARIZABLE() { - return exports.ReadConcernLevel.linearizable; - } - static get SNAPSHOT() { - return exports.ReadConcernLevel.snapshot; - } - toJSON() { - return { level: this.level }; } + return log2; } - exports.ReadConcern = ReadConcern; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/on_demand/document.js -var require_document = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OnDemandDocument = undefined; - var bson_1 = require_bson2(); - var BSONElementOffset = { - type: 0, - nameOffset: 1, - nameLength: 2, - offset: 3, - length: 4 - }; - class OnDemandDocument { - constructor(bson, offset = 0, isArray3 = false, elements) { - this.cache = Object.create(null); - this.indexFound = Object.create(null); - this.bson = bson; - this.offset = offset; - this.isArray = isArray3; - this.elements = elements ?? (0, bson_1.parseToElementsToArray)(this.bson, offset); - } - isElementName(name, element) { - const nameLength = element[BSONElementOffset.nameLength]; - const nameOffset = element[BSONElementOffset.nameOffset]; - if (name.length !== nameLength) - return false; - const nameEnd = nameOffset + nameLength; - for (let byteIndex = nameOffset, charIndex = 0;charIndex < name.length && byteIndex < nameEnd; charIndex++, byteIndex++) { - if (this.bson[byteIndex] !== name.charCodeAt(charIndex)) - return false; - } - return true; + class MongoLogger { + constructor(options) { + this.pendingLog = null; + this.error = this.log.bind(this, "error"); + this.warn = this.log.bind(this, "warn"); + this.info = this.log.bind(this, "info"); + this.debug = this.log.bind(this, "debug"); + this.trace = this.log.bind(this, "trace"); + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + this.logDestinationIsStdErr = options.logDestinationIsStdErr; + this.severities = this.createLoggingSeverities(); } - getElement(name) { - const cachedElement = this.cache[name]; - if (cachedElement === false) - return null; - if (cachedElement != null) { - return cachedElement; - } - if (typeof name === "number") { - if (this.isArray) { - if (name < this.elements.length) { - const element = this.elements[name]; - const cachedElement2 = { element, value: undefined }; - this.cache[name] = cachedElement2; - this.indexFound[name] = true; - return cachedElement2; - } else { - return null; - } - } else { - return null; + createLoggingSeverities() { + const severities = Object(); + for (const component of Object.values(exports.MongoLoggableComponent)) { + severities[component] = {}; + for (const severityLevel of Object.values(exports.SeverityLevel)) { + severities[component][severityLevel] = compareSeverity(severityLevel, this.componentSeverities[component]) <= 0; } } - for (let index2 = 0;index2 < this.elements.length; index2++) { - const element = this.elements[index2]; - if (!(index2 in this.indexFound) && this.isElementName(name, element)) { - const cachedElement2 = { element, value: undefined }; - this.cache[name] = cachedElement2; - this.indexFound[index2] = true; - return cachedElement2; + return severities; + } + turnOffSeverities() { + for (const component of Object.values(exports.MongoLoggableComponent)) { + this.componentSeverities[component] = exports.SeverityLevel.OFF; + for (const severityLevel of Object.values(exports.SeverityLevel)) { + this.severities[component][severityLevel] = false; } } - this.cache[name] = false; - return null; } - toJSValue(element, as) { - const type = element[BSONElementOffset.type]; - const offset = element[BSONElementOffset.offset]; - const length = element[BSONElementOffset.length]; - if (as !== type) { - return null; + logWriteFailureHandler(error91) { + if (this.logDestinationIsStdErr) { + this.turnOffSeverities(); + this.clearPendingLog(); + return; } - switch (as) { - case bson_1.BSONType.null: - case bson_1.BSONType.undefined: - return null; - case bson_1.BSONType.double: - return (0, bson_1.getFloat64LE)(this.bson, offset); - case bson_1.BSONType.int: - return (0, bson_1.getInt32LE)(this.bson, offset); - case bson_1.BSONType.long: - return (0, bson_1.getBigInt64LE)(this.bson, offset); - case bson_1.BSONType.bool: - return Boolean(this.bson[offset]); - case bson_1.BSONType.objectId: - return new bson_1.ObjectId(this.bson.subarray(offset, offset + 12)); - case bson_1.BSONType.timestamp: - return new bson_1.Timestamp((0, bson_1.getBigInt64LE)(this.bson, offset)); - case bson_1.BSONType.string: - return (0, bson_1.toUTF8)(this.bson, offset + 4, offset + length - 1, false); - case bson_1.BSONType.binData: { - const totalBinarySize = (0, bson_1.getInt32LE)(this.bson, offset); - const subType = this.bson[offset + 4]; - if (subType === 2) { - const subType2BinarySize = (0, bson_1.getInt32LE)(this.bson, offset + 1 + 4); - if (subType2BinarySize < 0) - throw new bson_1.BSONError("Negative binary type element size found for subtype 0x02"); - if (subType2BinarySize > totalBinarySize - 4) - throw new bson_1.BSONError("Binary type with subtype 0x02 contains too long binary size"); - if (subType2BinarySize < totalBinarySize - 4) - throw new bson_1.BSONError("Binary type with subtype 0x02 contains too short binary size"); - return new bson_1.Binary(this.bson.subarray(offset + 1 + 4 + 4, offset + 1 + 4 + 4 + subType2BinarySize), 2); - } - return new bson_1.Binary(this.bson.subarray(offset + 1 + 4, offset + 1 + 4 + totalBinarySize), subType); + this.logDestination = createStdioLogger(process.stderr); + this.logDestinationIsStdErr = true; + this.clearPendingLog(); + this.error(exports.MongoLoggableComponent.CLIENT, { + toLog: function() { + return { + message: "User input for mongodbLogPath is now invalid. Logging is halted.", + error: error91.message + }; } - case bson_1.BSONType.date: - return new Date(Number((0, bson_1.getBigInt64LE)(this.bson, offset))); - case bson_1.BSONType.object: - return new OnDemandDocument(this.bson, offset); - case bson_1.BSONType.array: - return new OnDemandDocument(this.bson, offset, true); - default: - throw new bson_1.BSONError(`Unsupported BSON type: ${as}`); - } + }); + this.turnOffSeverities(); + this.clearPendingLog(); } - size() { - return this.elements.length; + clearPendingLog() { + this.pendingLog = null; } - has(name) { - const cachedElement = this.cache[name]; - if (cachedElement === false) + willLog(component, severity) { + if (severity === exports.SeverityLevel.OFF) return false; - if (cachedElement != null) - return true; - return this.getElement(name) != null; + return this.severities[component][severity]; } - get(name, as, required3) { - const element = this.getElement(name); - if (element == null) { - if (required3 === true) { - throw new bson_1.BSONError(`BSON element "${name}" is missing`); + log(severity, component, message) { + if (!this.willLog(component, severity)) + return; + let logMessage = { t: new Date, c: component, s: severity }; + if (typeof message === "string") { + logMessage.message = message; + } else if (typeof message === "object") { + if (isLogConvertible(message)) { + logMessage = { ...logMessage, ...message.toLog() }; } else { - return null; + logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) }; } } - if (element.value == null) { - const value = this.toJSValue(element.element, as); - if (value == null) { - if (required3 === true) { - throw new bson_1.BSONError(`BSON element "${name}" is missing`); - } else { - return null; - } - } - element.value = value; + if ((0, utils_1.isPromiseLike)(this.pendingLog)) { + this.pendingLog = this.pendingLog.then(() => this.logDestination.write(logMessage)).then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + return; } - return element.value; - } - getNumber(name, required3) { - const maybeBool = this.get(name, bson_1.BSONType.bool); - const bool = maybeBool == null ? null : maybeBool ? 1 : 0; - const maybeLong = this.get(name, bson_1.BSONType.long); - const long = maybeLong == null ? null : Number(maybeLong); - const result = bool ?? long ?? this.get(name, bson_1.BSONType.int) ?? this.get(name, bson_1.BSONType.double); - if (required3 === true && result == null) { - throw new bson_1.BSONError(`BSON element "${name}" is missing`); + try { + const logResult = this.logDestination.write(logMessage); + if ((0, utils_1.isPromiseLike)(logResult)) { + this.pendingLog = logResult.then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + } + } catch (error91) { + this.logWriteFailureHandler(error91); } - return result; - } - toObject(options) { - return (0, bson_1.deserialize)(this.bson, { - ...options, - index: this.offset, - allowObjectSmallerThanBufferSize: true - }); } - toBytes() { - const size = (0, bson_1.getInt32LE)(this.bson, this.offset); - return this.bson.subarray(this.offset, this.offset + size); + static resolveOptions(envOptions, clientOptions) { + const resolvedLogPath = resolveLogPath(envOptions, clientOptions); + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolvedLogPath.mongodbLogPath, + mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr + }; + const defaultSeverity = resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.default, combinedOptions.MONGODB_LOG_ALL, exports.SeverityLevel.OFF); + return { + componentSeverities: { + command: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.command, combinedOptions.MONGODB_LOG_COMMAND, defaultSeverity), + topology: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.topology, combinedOptions.MONGODB_LOG_TOPOLOGY, defaultSeverity), + serverSelection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.serverSelection, combinedOptions.MONGODB_LOG_SERVER_SELECTION, defaultSeverity), + connection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.connection, combinedOptions.MONGODB_LOG_CONNECTION, defaultSeverity), + client: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.client, combinedOptions.MONGODB_LOG_CLIENT, defaultSeverity), + default: defaultSeverity + }, + maxDocumentLength: combinedOptions.mongodbLogMaxDocumentLength ?? (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, + logDestination: combinedOptions.mongodbLogPath, + logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr + }; } } - exports.OnDemandDocument = OnDemandDocument; + exports.MongoLogger = MongoLogger; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/wire_protocol/responses.js -var require_responses = __commonJS((exports) => { +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/mongo_types.js +var require_mongo_types = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.ClientBulkWriteCursorResponse = exports.ExplainedCursorResponse = exports.CursorResponse = exports.MongoDBResponse = undefined; - exports.isErrorResponse = isErrorResponse; - var bson_1 = require_bson2(); - var error_1 = require_error2(); + exports.CancellationToken = exports.TypedEventEmitter = undefined; + var events_1 = __require("events"); + var mongo_logger_1 = require_mongo_logger(); var utils_1 = require_utils5(); - var document_1 = require_document(); - var BSONElementOffset = { - type: 0, - nameOffset: 1, - nameLength: 2, - offset: 3, - length: 4 - }; - function isErrorResponse(bson, elements) { - for (let eIdx = 0;eIdx < elements.length; eIdx++) { - const element = elements[eIdx]; - if (element[BSONElementOffset.nameLength] === 2) { - const nameOffset = element[BSONElementOffset.nameOffset]; - if (bson[nameOffset] === 111 && bson[nameOffset + 1] === 107) { - const valueOffset = element[BSONElementOffset.offset]; - const valueLength = element[BSONElementOffset.length]; - for (let i2 = valueOffset;i2 < valueOffset + valueLength; i2++) { - if (bson[i2] !== 0) - return false; - } - return true; - } + + class TypedEventEmitter extends events_1.EventEmitter { + emitAndLog(event, ...args) { + this.emit(event, ...args); + if (this.component) + this.mongoLogger?.debug(this.component, args[0]); + } + emitAndLogHeartbeat(event, topologyId, serverConnectionId, ...args) { + this.emit(event, ...args); + if (this.component) { + const loggableHeartbeatEvent = { + topologyId, + serverConnectionId: serverConnectionId ?? null, + ...args[0] + }; + this.mongoLogger?.debug(this.component, loggableHeartbeatEvent); + } + } + emitAndLogCommand(monitorCommands, event, databaseName, connectionEstablished, ...args) { + if (monitorCommands) { + this.emit(event, ...args); + } + if (connectionEstablished) { + const loggableCommandEvent = { + databaseName, + ...args[0] + }; + this.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.COMMAND, loggableCommandEvent); } } - return true; } + exports.TypedEventEmitter = TypedEventEmitter; - class MongoDBResponse extends document_1.OnDemandDocument { - get(name, as, required3) { - try { - return super.get(name, as, required3); - } catch (cause) { - throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); - } + class CancellationToken extends TypedEventEmitter { + constructor(...args) { + super(...args); + this.on("error", utils_1.noop); } - static is(value) { - return value instanceof MongoDBResponse; + } + exports.CancellationToken = CancellationToken; +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/get_more.js +var require_get_more = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GetMoreOperation = undefined; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var utils_1 = require_utils5(); + var operation_1 = require_operation(); + + class GetMoreOperation extends operation_1.AbstractOperation { + constructor(ns3, cursorId, server, options) { + super(options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; + this.options = options; + this.ns = ns3; + this.cursorId = cursorId; + this.server = server; } - static make(bson) { - const elements = (0, bson_1.parseToElementsToArray)(bson, 0); - const isError5 = isErrorResponse(bson, elements); - return isError5 ? new MongoDBResponse(bson, 0, false, elements) : new this(bson, 0, false, elements); + get commandName() { + return "getMore"; } - get isMaxTimeExpiredError() { - const isTopLevel = this.ok === 0 && this.code === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; - if (isTopLevel) - return true; - if (this.ok === 0) - return false; - const isWriteConcern = this.get("writeConcernError", bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; - if (isWriteConcern) - return true; - const writeErrors = this.get("writeErrors", bson_1.BSONType.array); - if (writeErrors?.size()) { - for (let i2 = 0;i2 < writeErrors.size(); i2++) { - const isWriteError = writeErrors.get(i2, bson_1.BSONType.object)?.getNumber("code") === error_1.MONGODB_ERROR_CODES.MaxTimeMSExpired; - if (isWriteError) - return true; - } + buildCommand(connection) { + if (this.cursorId == null || this.cursorId.isZero()) { + throw new error_1.MongoRuntimeError("Unable to iterate cursor with no id"); } - return false; - } - get recoveryToken() { - return this.get("recoveryToken", bson_1.BSONType.object)?.toObject({ - promoteValues: false, - promoteLongs: false, - promoteBuffers: false, - validation: { utf8: true } - }) ?? null; - } - get atClusterTime() { - return this.get("cursor", bson_1.BSONType.object)?.get("atClusterTime", bson_1.BSONType.timestamp) ?? this.get("atClusterTime", bson_1.BSONType.timestamp); - } - get operationTime() { - return this.get("operationTime", bson_1.BSONType.timestamp); + const collection = this.ns.collection; + if (collection == null) { + throw new error_1.MongoRuntimeError("A collection name must be determined before getMore"); + } + const getMoreCmd = { + getMore: this.cursorId, + collection + }; + if (typeof this.options.batchSize === "number") { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + if (typeof this.options.maxAwaitTimeMS === "number") { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + if (this.options.comment !== undefined && (0, utils_1.maxWireVersion)(connection) >= 9) { + getMoreCmd.comment = this.options.comment; + } + return getMoreCmd; } - get ok() { - return this.getNumber("ok") ? 1 : 0; + buildOptions(timeoutContext) { + return { + returnFieldSelector: null, + documentsReturnedIn: "nextBatch", + timeoutContext, + ...this.options + }; } - get $err() { - return this.get("$err", bson_1.BSONType.string); + handleOk(response) { + return response; } - get errmsg() { - return this.get("errmsg", bson_1.BSONType.string); + } + exports.GetMoreOperation = GetMoreOperation; + (0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +}); + +// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/kill_cursors.js +var require_kill_cursors = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KillCursorsOperation = undefined; + var responses_1 = require_responses(); + var error_1 = require_error2(); + var operation_1 = require_operation(); + + class KillCursorsOperation extends operation_1.AbstractOperation { + constructor(cursorId, ns3, server, options) { + super(options); + this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; + this.ns = ns3; + this.cursorId = cursorId; + this.server = server; } - get code() { - return this.getNumber("code"); + get commandName() { + return "killCursors"; } - get $clusterTime() { - if (!("clusterTime" in this)) { - const clusterTimeDoc = this.get("$clusterTime", bson_1.BSONType.object); - if (clusterTimeDoc == null) { - this.clusterTime = null; - return null; - } - const clusterTime = clusterTimeDoc.get("clusterTime", bson_1.BSONType.timestamp, true); - const signature = clusterTimeDoc.get("signature", bson_1.BSONType.object)?.toObject(); - this.clusterTime = { clusterTime, signature }; + buildCommand(_connection, _session) { + const killCursors = this.ns.collection; + if (killCursors == null) { + throw new error_1.MongoRuntimeError("A collection name must be determined before killCursors"); } - return this.clusterTime ?? null; + const killCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + return killCursorsCommand; } - toObject(options) { - const exactBSONOptions = { - ...(0, bson_1.pluckBSONSerializeOptions)(options ?? {}), - validation: (0, bson_1.parseUtf8ValidationOption)(options) + buildOptions(timeoutContext) { + return { + session: this.session, + timeoutContext }; - return super.toObject(exactBSONOptions); } + handleError(_error) {} } - exports.MongoDBResponse = MongoDBResponse; - MongoDBResponse.empty = new MongoDBResponse(new Uint8Array([13, 0, 0, 0, 16, 111, 107, 0, 1, 0, 0, 0, 0])); + exports.KillCursorsOperation = KillCursorsOperation; + (0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]); +}); - class CursorResponse extends MongoDBResponse { - constructor() { - super(...arguments); - this._batch = null; - this.iterated = 0; - this._encryptedBatch = null; +// ../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js +var require_extend = __commonJS((exports, module) => { + var hasOwn2 = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var defineProperty = Object.defineProperty; + var gOPD = Object.getOwnPropertyDescriptor; + var isArray3 = function isArray4(arr3) { + if (typeof Array.isArray === "function") { + return Array.isArray(arr3); } - static get emptyGetMore() { - return new CursorResponse((0, bson_1.serialize)({ ok: 1, cursor: { id: 0n, nextBatch: [] } })); + return toStr.call(arr3) === "[object Array]"; + }; + var isPlainObject3 = function isPlainObject4(obj) { + if (!obj || toStr.call(obj) !== "[object Object]") { + return false; } - static is(value) { - return value instanceof CursorResponse || value === CursorResponse.emptyGetMore; + var hasOwnConstructor = hasOwn2.call(obj, "constructor"); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn2.call(obj.constructor.prototype, "isPrototypeOf"); + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; } - get cursor() { - return this.get("cursor", bson_1.BSONType.object, true); + var key; + for (key in obj) {} + return typeof key === "undefined" || hasOwn2.call(obj, key); + }; + var setProperty = function setProperty2(target, options) { + if (defineProperty && options.name === "__proto__") { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; } - get id() { - try { - return bson_1.Long.fromBigInt(this.cursor.get("id", bson_1.BSONType.long, true)); - } catch (cause) { - throw new error_1.MongoUnexpectedServerResponseError(cause.message, { cause }); + }; + var getProperty = function getProperty2(obj, name) { + if (name === "__proto__") { + if (!hasOwn2.call(obj, name)) { + return; + } else if (gOPD) { + return gOPD(obj, name).value; + } + } + return obj[name]; + }; + module.exports = function extend3() { + var options, name, src, copy, copyIsArray, clone3; + var target = arguments[0]; + var i2 = 1; + var length = arguments.length; + var deep = false; + if (typeof target === "boolean") { + deep = target; + target = arguments[1] || {}; + i2 = 2; + } + if (target == null || typeof target !== "object" && typeof target !== "function") { + target = {}; + } + for (;i2 < length; ++i2) { + options = arguments[i2]; + if (options != null) { + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + if (target !== copy) { + if (deep && copy && (isPlainObject3(copy) || (copyIsArray = isArray3(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone3 = src && isArray3(src) ? src : []; + } else { + clone3 = src && isPlainObject3(src) ? src : {}; + } + setProperty(target, { name, newValue: extend3(deep, clone3, copy) }); + } else if (typeof copy !== "undefined") { + setProperty(target, { name, newValue: copy }); + } + } + } } } - get ns() { - const namespace = this.cursor.get("ns", bson_1.BSONType.string); - if (namespace != null) - return (0, utils_1.ns)(namespace); - return null; - } - get length() { - return Math.max(this.batchSize - this.iterated, 0); + return target; + }; +}); + +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/package.json +var require_package = __commonJS((exports, module) => { + module.exports = { + name: "gaxios", + version: "7.1.4", + description: "A simple common HTTP client specifically for Google APIs and services.", + main: "build/cjs/src/index.js", + types: "build/cjs/src/index.d.ts", + files: [ + "build/" + ], + exports: { + ".": { + import: { + types: "./build/esm/src/index.d.ts", + default: "./build/esm/src/index.js" + }, + require: { + types: "./build/cjs/src/index.d.ts", + default: "./build/cjs/src/index.js" + } + } + }, + scripts: { + lint: "gts check --no-inline-config", + test: "c8 mocha build/esm/test", + "presystem-test": "npm run compile", + "system-test": "mocha build/esm/system-test --timeout 80000", + compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs", + fix: "gts fix", + prepare: "npm run compile", + pretest: "npm run compile", + webpack: "webpack", + "prebrowser-test": "npm run compile", + "browser-test": "node build/browser-test/browser-test-runner.js", + docs: "jsdoc -c .jsdoc.js", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + prelint: "cd samples; npm link ../; npm install", + clean: "gts clean" + }, + repository: { + type: "git", + directory: "packages/gaxios", + url: "https://github.com/googleapis/google-cloud-node-core.git" + }, + keywords: [ + "google" + ], + engines: { + node: ">=18" + }, + author: "Google, LLC", + license: "Apache-2.0", + devDependencies: { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@types/cors": "^2.8.6", + "@types/express": "^5.0.0", + "@types/extend": "^3.0.1", + "@types/mocha": "^10.0.10", + "@types/multiparty": "4.2.1", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.8", + "@types/node": "^22.13.1", + "@types/sinon": "^17.0.3", + "@types/tmp": "^0.2.6", + assert: "^2.0.0", + browserify: "^17.0.0", + c8: "^10.1.3", + cors: "^2.8.5", + express: "^5.0.0", + gts: "^6.0.2", + "is-docker": "^3.0.0", + jsdoc: "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + karma: "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", + linkinator: "^6.1.2", + mocha: "^11.1.0", + multiparty: "^4.2.1", + mv: "^2.1.1", + ncp: "^2.0.0", + nock: "^14.0.5", + "null-loader": "^4.0.1", + "pack-n-play": "^4.0.0", + puppeteer: "^24.0.0", + sinon: "^21.0.0", + "stream-browserify": "^3.0.0", + tmp: "0.2.5", + "ts-loader": "^9.5.2", + typescript: "5.8.3", + webpack: "^5.97.1", + "webpack-cli": "^6.0.1" + }, + dependencies: { + extend: "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios" + }; +}); + +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/util.cjs +var require_util = __commonJS((exports, module) => { + var pkg = require_package(); + module.exports = { pkg }; +}); + +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/common.js +var require_common6 = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = undefined; + exports.defaultErrorRedactor = defaultErrorRedactor; + var extend_1 = __importDefault(require_extend()); + var util_cjs_1 = __importDefault(require_util()); + var pkg = util_cjs_1.default.pkg; + exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`); + + class GaxiosError extends Error { + config; + response; + code; + status; + error; + [exports.GAXIOS_ERROR_SYMBOL] = pkg.version; + static [Symbol.hasInstance](instance) { + if (instance && typeof instance === "object" && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) { + return true; + } + return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); } - get encryptedBatch() { - if (this.encryptedResponse == null) - return null; - if (this._encryptedBatch != null) - return this._encryptedBatch; - const cursor = this.encryptedResponse?.get("cursor", bson_1.BSONType.object); - if (cursor?.has("firstBatch")) - this._encryptedBatch = cursor.get("firstBatch", bson_1.BSONType.array, true); - else if (cursor?.has("nextBatch")) - this._encryptedBatch = cursor.get("nextBatch", bson_1.BSONType.array, true); - else - throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); - return this._encryptedBatch; + constructor(message, config3, response, cause) { + super(message, { cause }); + this.config = config3; + this.response = response; + this.error = cause instanceof Error ? cause : undefined; + this.config = (0, extend_1.default)(true, {}, config3); + if (this.response) { + this.response.config = (0, extend_1.default)(true, {}, this.response.config); + } + if (this.response) { + try { + this.response.data = translateData(this.config.responseType, this.response?.bodyUsed ? this.response?.data : undefined); + } catch {} + this.status = this.response.status; + } + if (cause instanceof DOMException) { + this.code = cause.name; + } else if (cause && typeof cause === "object" && "code" in cause && (typeof cause.code === "string" || typeof cause.code === "number")) { + this.code = cause.code; + } } - get batch() { - if (this._batch != null) - return this._batch; - const cursor = this.cursor; - if (cursor.has("firstBatch")) - this._batch = cursor.get("firstBatch", bson_1.BSONType.array, true); - else if (cursor.has("nextBatch")) - this._batch = cursor.get("nextBatch", bson_1.BSONType.array, true); - else - throw new error_1.MongoUnexpectedServerResponseError("Cursor document did not contain a batch"); - return this._batch; + static extractAPIErrorFromResponse(res, defaultErrorMessage = "The request failed") { + let message = defaultErrorMessage; + if (typeof res.data === "string") { + message = res.data; + } + if (res.data && typeof res.data === "object" && "error" in res.data && res.data.error && !res.ok) { + if (typeof res.data.error === "string") { + return { + message: res.data.error, + code: res.status, + status: res.statusText + }; + } + if (typeof res.data.error === "object") { + message = "message" in res.data.error && typeof res.data.error.message === "string" ? res.data.error.message : message; + const status = "status" in res.data.error && typeof res.data.error.status === "string" ? res.data.error.status : res.statusText; + const code = "code" in res.data.error && typeof res.data.error.code === "number" ? res.data.error.code : res.status; + if ("errors" in res.data.error && Array.isArray(res.data.error.errors)) { + const errorMessages4 = []; + for (const e of res.data.error.errors) { + if (typeof e === "object" && "message" in e && typeof e.message === "string") { + errorMessages4.push(e.message); + } + } + return Object.assign({ + message: errorMessages4.join(` +`) || message, + code, + status + }, res.data.error); + } + return Object.assign({ + message, + code, + status + }, res.data.error); + } + } + return { + message, + code: res.status, + status: res.statusText + }; } - get batchSize() { - return this.batch?.size(); + } + exports.GaxiosError = GaxiosError; + function translateData(responseType, data) { + switch (responseType) { + case "stream": + return data; + case "json": + return JSON.parse(JSON.stringify(data)); + case "arraybuffer": + return JSON.parse(Buffer.from(data).toString("utf8")); + case "blob": + return JSON.parse(data.text()); + default: + return data; } - get postBatchResumeToken() { - return this.cursor.get("postBatchResumeToken", bson_1.BSONType.object)?.toObject({ - promoteValues: false, - promoteLongs: false, - promoteBuffers: false, - validation: { utf8: true } - }) ?? null; + } + function defaultErrorRedactor(data) { + const REDACT = "< - See `errorRedactor` option in `gaxios` for configuration>."; + function redactHeaders(headers) { + if (!headers) + return; + headers.forEach((_2, key) => { + if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key)) + headers.set(key, REDACT); + }); } - shift(options) { - if (this.iterated >= this.batchSize) { - return null; + function redactString(obj, key) { + if (typeof obj === "object" && obj !== null && typeof obj[key] === "string") { + const text = obj[key]; + if (/grant_type=/i.test(text) || /assertion=/i.test(text) || /secret/i.test(text)) { + obj[key] = REDACT; + } } - const result = this.batch.get(this.iterated, bson_1.BSONType.object, true) ?? null; - const encryptedResult = this.encryptedBatch?.get(this.iterated, bson_1.BSONType.object, true) ?? null; - this.iterated += 1; - if (options?.raw) { - return result.toBytes(); + } + function redactObject(obj) { + if (!obj || typeof obj !== "object") { + return; + } else if (obj instanceof FormData || obj instanceof URLSearchParams || "forEach" in obj && "set" in obj) { + obj.forEach((_2, key) => { + if (["grant_type", "assertion"].includes(key) || /secret/.test(key)) { + obj.set(key, REDACT); + } + }); } else { - const object3 = result.toObject(options); - if (encryptedResult) { - (0, utils_1.decorateDecryptionResult)(object3, encryptedResult.toObject(options), true); + if ("grant_type" in obj) { + obj["grant_type"] = REDACT; + } + if ("assertion" in obj) { + obj["assertion"] = REDACT; + } + if ("client_secret" in obj) { + obj["client_secret"] = REDACT; } - return object3; } } - clear() { - this.iterated = this.batchSize; + if (data.config) { + redactHeaders(data.config.headers); + redactString(data.config, "data"); + redactObject(data.config.data); + redactString(data.config, "body"); + redactObject(data.config.body); + if (data.config.url.searchParams.has("token")) { + data.config.url.searchParams.set("token", REDACT); + } + if (data.config.url.searchParams.has("client_secret")) { + data.config.url.searchParams.set("client_secret", REDACT); + } + } + if (data.response) { + defaultErrorRedactor({ config: data.response.config }); + redactHeaders(data.response.headers); + if (data.response.bodyUsed) { + redactString(data.response, "data"); + redactObject(data.response.data); + } } + return data; } - exports.CursorResponse = CursorResponse; +}); - class ExplainedCursorResponse extends CursorResponse { - constructor() { - super(...arguments); - this.isExplain = true; - this._length = 1; +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/retry.js +var require_retry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRetryConfig = getRetryConfig; + async function getRetryConfig(err) { + let config3 = getConfig3(err); + if (!err || !err.config || !config3 && !err.config.retry) { + return { shouldRetry: false }; + } + config3 = config3 || {}; + config3.currentRetryAttempt = config3.currentRetryAttempt || 0; + config3.retry = config3.retry === undefined || config3.retry === null ? 3 : config3.retry; + config3.httpMethodsToRetry = config3.httpMethodsToRetry || [ + "GET", + "HEAD", + "PUT", + "OPTIONS", + "DELETE" + ]; + config3.noResponseRetries = config3.noResponseRetries === undefined || config3.noResponseRetries === null ? 2 : config3.noResponseRetries; + config3.retryDelayMultiplier = config3.retryDelayMultiplier ? config3.retryDelayMultiplier : 2; + config3.timeOfFirstRequest = config3.timeOfFirstRequest ? config3.timeOfFirstRequest : Date.now(); + config3.totalTimeout = config3.totalTimeout ? config3.totalTimeout : Number.MAX_SAFE_INTEGER; + config3.maxRetryDelay = config3.maxRetryDelay ? config3.maxRetryDelay : Number.MAX_SAFE_INTEGER; + const retryRanges = [ + [100, 199], + [408, 408], + [429, 429], + [500, 599] + ]; + config3.statusCodesToRetry = config3.statusCodesToRetry || retryRanges; + err.config.retryConfig = config3; + const shouldRetryFn = config3.shouldRetry || shouldRetryRequest; + if (!await shouldRetryFn(err)) { + return { shouldRetry: false, config: err.config }; + } + const delay2 = getNextRetryDelay(config3); + err.config.retryConfig.currentRetryAttempt += 1; + const backoff = config3.retryBackoff ? config3.retryBackoff(err, delay2) : new Promise((resolve2) => { + setTimeout(resolve2, delay2); + }); + if (config3.onRetryAttempt) { + await config3.onRetryAttempt(err); + } + await backoff; + return { shouldRetry: true, config: err.config }; + } + function shouldRetryRequest(err) { + const config3 = getConfig3(err); + if (err.config.signal?.aborted && err.code !== "TimeoutError" || err.code === "AbortError") { + return false; } - get id() { - return bson_1.Long.fromBigInt(0n); + if (!config3 || config3.retry === 0) { + return false; } - get batchSize() { - return 0; + if (!err.response && (config3.currentRetryAttempt || 0) >= config3.noResponseRetries) { + return false; } - get ns() { - return null; + if (!config3.httpMethodsToRetry || !config3.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || "GET")) { + return false; } - get length() { - return this._length; + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config3.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } } - shift(options) { - if (this._length === 0) - return null; - this._length -= 1; - return this.toObject(options); + config3.currentRetryAttempt = config3.currentRetryAttempt || 0; + if (config3.currentRetryAttempt >= config3.retry) { + return false; } + return true; } - exports.ExplainedCursorResponse = ExplainedCursorResponse; - - class ClientBulkWriteCursorResponse extends CursorResponse { - get insertedCount() { - return this.get("nInserted", bson_1.BSONType.int, true); - } - get upsertedCount() { - return this.get("nUpserted", bson_1.BSONType.int, true); + function getConfig3(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; } - get matchedCount() { - return this.get("nMatched", bson_1.BSONType.int, true); + return; + } + function getNextRetryDelay(config3) { + const retryDelay = config3.currentRetryAttempt ? 0 : config3.retryDelay ?? 100; + const calculatedDelay = retryDelay + (Math.pow(config3.retryDelayMultiplier, config3.currentRetryAttempt) - 1) / 2 * 1000; + const maxAllowableDelay = config3.totalTimeout - (Date.now() - config3.timeOfFirstRequest); + return Math.min(calculatedDelay, maxAllowableDelay, config3.maxRetryDelay); + } +}); + +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/interceptor.js +var require_interceptor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GaxiosInterceptorManager = undefined; + + class GaxiosInterceptorManager extends Set { + } + exports.GaxiosInterceptorManager = GaxiosInterceptorManager; +}); + +// ../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/helpers.js +var require_helpers = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m, k2); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k2]; + } }; } - get modifiedCount() { - return this.get("nModified", bson_1.BSONType.int, true); + Object.defineProperty(o2, k22, desc); + } : function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m[k2]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { + Object.defineProperty(o2, "default", { enumerable: true, value: v }); + } : function(o2, v) { + o2["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k2 in mod) + if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) + __createBinding(result, mod, k2); } - get deletedCount() { - return this.get("nDeleted", bson_1.BSONType.int, true); + __setModuleDefault(result, mod); + return result; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.req = exports.json = exports.toBuffer = undefined; + var http = __importStar(__require("http")); + var https = __importStar(__require("https")); + async function toBuffer(stream2) { + let length = 0; + const chunks = []; + for await (const chunk of stream2) { + length += chunk.length; + chunks.push(chunk); } - get writeConcernError() { - return this.get("writeConcernError", bson_1.BSONType.object, false); + return Buffer.concat(chunks, length); + } + exports.toBuffer = toBuffer; + async function json3(stream2) { + const buf = await toBuffer(stream2); + const str = buf.toString("utf8"); + try { + return JSON.parse(str); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; } } - exports.ClientBulkWriteCursorResponse = ClientBulkWriteCursorResponse; + exports.json = json3; + function req(url3, opts = {}) { + const href = typeof url3 === "string" ? url3 : url3.href; + const req2 = (href.startsWith("https:") ? https : http).request(url3, opts); + const promise3 = new Promise((resolve2, reject) => { + req2.once("response", resolve2).once("error", reject).end(); + }); + req2.then = promise3.then.bind(promise3); + return req2; + } + exports.req = req; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/write_concern.js -var require_write_concern = __commonJS((exports) => { +// ../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/index.js +var require_dist7 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m, k2); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k2]; + } }; + } + Object.defineProperty(o2, k22, desc); + } : function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m[k2]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { + Object.defineProperty(o2, "default", { enumerable: true, value: v }); + } : function(o2, v) { + o2["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k2 in mod) + if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) + __createBinding(result, mod, k2); + } + __setModuleDefault(result, mod); + return result; + }; + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p2 in m) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m, p2); + }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.WriteConcern = exports.WRITE_CONCERN_KEYS = undefined; - exports.throwIfWriteConcernError = throwIfWriteConcernError; - var responses_1 = require_responses(); - var error_1 = require_error2(); - exports.WRITE_CONCERN_KEYS = ["w", "wtimeout", "j", "journal", "fsync"]; - - class WriteConcern { - constructor(w, wtimeoutMS, journal, fsync) { - if (w != null) { - if (!Number.isNaN(Number(w))) { - this.w = Number(w); - } else { - this.w = w; + exports.Agent = undefined; + var net = __importStar(__require("net")); + var http = __importStar(__require("http")); + var https_1 = __require("https"); + __exportStar(require_helpers(), exports); + var INTERNAL = Symbol("AgentBaseInternalState"); + + class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; } } - if (wtimeoutMS != null) { - this.wtimeoutMS = this.wtimeout = wtimeoutMS; + const { stack } = new Error; + if (typeof stack !== "string") + return false; + return stack.split(` +`).some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + } + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; } - if (journal != null) { - this.journal = this.j = journal; + if (!this.sockets[name]) { + this.sockets[name] = []; } - if (fsync != null) { - this.journal = this.j = fsync ? true : false; + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; + } + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index2 = sockets.indexOf(socket); + if (index2 !== -1) { + sockets.splice(index2, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; + } } } - static apply(command, writeConcern) { - const wc = {}; - if (writeConcern.w != null) - wc.w = writeConcern.w; - if (writeConcern.wtimeoutMS != null) - wc.wtimeout = writeConcern.wtimeoutMS; - if (writeConcern.journal != null) - wc.j = writeConcern.j; - command.writeConcern = wc; - return command; + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); } - static fromOptions(options, inherit) { - if (options == null) - return; - inherit = inherit ?? {}; - let opts; - if (typeof options === "string" || typeof options === "number") { - opts = { w: options }; - } else if (options instanceof WriteConcern) { - opts = options; - } else { - opts = options.writeConcern; + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); + } + } + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); + } + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); } - const parentOpts = inherit instanceof WriteConcern ? inherit : inherit.writeConcern; - const mergedOpts = { ...parentOpts, ...opts }; - const { w = undefined, wtimeout = undefined, j: j2 = undefined, fsync = undefined, journal = undefined, wtimeoutMS = undefined } = mergedOpts; - if (w != null || wtimeout != null || wtimeoutMS != null || j2 != null || journal != null || fsync != null) { - return new WriteConcern(w, wtimeout ?? wtimeoutMS, j2 ?? journal, fsync); + return socket; + } + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + } + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; } - return; } - } - exports.WriteConcern = WriteConcern; - function throwIfWriteConcernError(response) { - if (typeof response === "object" && response != null) { - const writeConcernError = responses_1.MongoDBResponse.is(response) && response.has("writeConcernError") ? response.toObject() : !responses_1.MongoDBResponse.is(response) && ("writeConcernError" in response) ? response : null; - if (writeConcernError != null) { - throw new error_1.MongoWriteConcernError(writeConcernError); + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + } + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; } } } + exports.Agent = Agent; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/utils.js -var require_utils5 = __commonJS((exports) => { +// ../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.kDispose = exports.randomBytes = exports.COSMOS_DB_MSG = exports.DOCUMENT_DB_MSG = exports.COSMOS_DB_CHECK = exports.DOCUMENT_DB_CHECK = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.MongoDBCollectionNamespace = exports.MongoDBNamespace = exports.ByteUtils = undefined; - exports.isUint8Array = isUint8Array; - exports.hostMatchesWildcards = hostMatchesWildcards; - exports.normalizeHintField = normalizeHintField; - exports.isObject = isObject4; - exports.mergeOptions = mergeOptions; - exports.filterOptions = filterOptions; - exports.applyRetryableWrites = applyRetryableWrites; - exports.isPromiseLike = isPromiseLike3; - exports.decorateWithCollation = decorateWithCollation; - exports.decorateWithReadConcern = decorateWithReadConcern; - exports.getTopology = getTopology; - exports.ns = ns3; - exports.makeCounter = makeCounter; - exports.uuidV4 = uuidV4; - exports.maxWireVersion = maxWireVersion; - exports.arrayStrictEqual = arrayStrictEqual; - exports.errorStrictEqual = errorStrictEqual; - exports.makeStateMachine = makeStateMachine; - exports.now = now; - exports.calculateDurationInMs = calculateDurationInMs; - exports.hasAtomicOperators = hasAtomicOperators; - exports.resolveTimeoutOptions = resolveTimeoutOptions; - exports.resolveOptions = resolveOptions; - exports.isSuperset = isSuperset; - exports.isHello = isHello; - exports.setDifference = setDifference; - exports.isRecord = isRecord4; - exports.emitWarning = emitWarning; - exports.emitWarningOnce = emitWarningOnce; - exports.enumToString = enumToString; - exports.supportsRetryableWrites = supportsRetryableWrites; - exports.shuffle = shuffle; - exports.commandSupportsReadConcern = commandSupportsReadConcern; - exports.compareObjectId = compareObjectId; - exports.parseInteger = parseInteger; - exports.parseUnsignedInteger = parseUnsignedInteger; - exports.checkParentDomainMatch = checkParentDomainMatch; - exports.get = get; - exports.request = request; - exports.isHostMatch = isHostMatch; - exports.promiseWithResolvers = promiseWithResolvers2; - exports.squashError = squashError; - exports.once = once; - exports.maybeAddIdToDocuments = maybeAddIdToDocuments; - exports.fileIsAccessible = fileIsAccessible; - exports.csotMin = csotMin; - exports.noop = noop2; - exports.decorateDecryptionResult = decorateDecryptionResult; - exports.addAbortListener = addAbortListener; - exports.abortable = abortable; - var crypto3 = __require("crypto"); - var fs_1 = __require("fs"); - var http = __require("http"); - var timers_1 = __require("timers"); - var url3 = __require("url"); - var url_1 = __require("url"); - var util_1 = __require("util"); - var bson_1 = require_bson2(); - var constants_1 = require_constants5(); - var constants_2 = require_constants6(); - var error_1 = require_error2(); - var read_concern_1 = require_read_concern(); - var read_preference_1 = require_read_preference(); - var common_1 = require_common4(); - var write_concern_1 = require_write_concern(); - exports.ByteUtils = { - toLocalBufferType(buffer) { - return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); - }, - equals(seqA, seqB) { - return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB); - }, - compare(seqA, seqB) { - return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB); - }, - toBase64(uint8array) { - return exports.ByteUtils.toLocalBufferType(uint8array).toString("base64"); + exports.parseProxyResponse = undefined; + var debug_1 = __importDefault(require_src()); + var debug2 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve2, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b2 = socket.read(); + if (b2) + ondata(b2); + else + socket.once("readable", read); + } + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); + } + function onend() { + cleanup(); + debug2("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); + } + function onerror(err) { + cleanup(); + debug2("onerror %o", err); + reject(err); + } + function ondata(b2) { + buffers.push(b2); + buffersLength += b2.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf(`\r +\r +`); + if (endOfHeaders === -1) { + debug2("have not received end of HTTP headers yet..."); + read(); + return; + } + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split(`\r +`); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } + } + debug2("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve2({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); + } + socket.on("error", onerror); + socket.on("end", onend); + read(); + }); + } + exports.parseProxyResponse = parseProxyResponse; +}); + +// ../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/index.js +var require_dist8 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m, k2); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k2]; + } }; + } + Object.defineProperty(o2, k22, desc); + } : function(o2, m, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m[k2]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { + Object.defineProperty(o2, "default", { enumerable: true, value: v }); + } : function(o2, v) { + o2["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k2 in mod) + if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) + __createBinding(result, mod, k2); + } + __setModuleDefault(result, mod); + return result; + }; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HttpsProxyAgent = undefined; + var net = __importStar(__require("net")); + var tls = __importStar(__require("tls")); + var assert_1 = __importDefault(__require("assert")); + var debug_1 = __importDefault(require_src()); + var agent_base_1 = require_dist7(); + var url_1 = __require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug2 = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; } + return options; }; - function isUint8Array(value) { - return value != null && typeof value === "object" && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Uint8Array"; - } - function hostMatchesWildcards(host, wildcards) { - for (const wildcard of wildcards) { - if (host === wildcard || wildcard.startsWith("*.") && host?.endsWith(wildcard.substring(2, wildcard.length)) || wildcard.startsWith("*/") && host?.endsWith(wildcard.substring(2, wildcard.length))) { - return true; - } + + class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug2("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ALPNProtocols: ["http/1.1"], + ...opts ? omit3(opts, "headers") : null, + host, + port + }; } - return false; - } - function normalizeHintField(hint) { - let finalHint = undefined; - if (typeof hint === "string") { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - hint.forEach((param) => { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === "object") { - finalHint = {}; - for (const name in hint) { - finalHint[name] = hint[name]; + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); } + let socket; + if (proxy.protocol === "https:") { + debug2("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug2("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); + } + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; + } + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; + } + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; + } + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug2("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit3(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); + } + return socket; + } + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug2("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; } - return finalHint; - } - var TO_STRING = (object3) => Object.prototype.toString.call(object3); - function isObject4(arg) { - return TO_STRING(arg) === "[object Object]"; } - function mergeOptions(target, source) { - return { ...target, ...source }; + HttpsProxyAgent.protocols = ["http", "https"]; + exports.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); } - function filterOptions(options, names) { - const filterOptions2 = {}; - for (const name in options) { - if (names.includes(name)) { - filterOptions2[name] = options[name]; + function omit3(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; } } - return filterOptions2; + return ret; } - function applyRetryableWrites(target, db) { - if (db && db.s.options?.retryWrites) { - target.retryWrites = true; - } - return target; +}); + +// ../../node_modules/.pnpm/data-uri-to-buffer@4.0.1/node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri2) { + if (!/^data:/i.test(uri2)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); } - function isPromiseLike3(value) { - return value != null && typeof value === "object" && "then" in value && typeof value.then === "function"; + uri2 = uri2.replace(/\r?\n/g, ""); + const firstComma = uri2.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); } - function decorateWithCollation(command, options) { - if (options.collation && typeof options.collation === "object") { - command.collation = options.collation; + const meta3 = uri2.substring(5, firstComma).split(";"); + let charset = ""; + let base647 = false; + const type = meta3[0] || "text/plain"; + let typeFull = type; + for (let i2 = 1;i2 < meta3.length; i2++) { + if (meta3[i2] === "base64") { + base647 = true; + } else if (meta3[i2]) { + typeFull += `;${meta3[i2]}`; + if (meta3[i2].indexOf("charset=") === 0) { + charset = meta3[i2].substring(8); + } } } - function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { + if (!meta3[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base647 ? "base64" : "ascii"; + const data = unescape(uri2.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default; +var init_dist11 = __esm(() => { + dist_default = dataUriToBuffer; +}); + +// ../../node_modules/.pnpm/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS((exports, module) => { + (function(global2, factory) { + typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + function noop2() { return; } - const readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); + function typeIsObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; } - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern }); + const rethrowAssertionErrorRejection = noop2; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, "name", { + value: name, + configurable: true + }); + } catch (_a6) {} } - } - function getTopology(provider) { - if ("topology" in provider && provider.topology) { - return provider.topology; - } else if ("client" in provider && provider.client.topology) { - return provider.client.topology; + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); } - throw new error_1.MongoNotConnectedError("MongoClient must be connected to perform this operation"); - } - function ns3(ns4) { - return MongoDBNamespace.fromString(ns4); - } - - class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection === "" ? undefined : collection; + function promiseResolvedWith(value) { + return newPromise((resolve2) => resolve2(value)); } - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); } - withCollection(collection) { - return new MongoDBCollectionNamespace(this.db, collection); + function PerformPromiseThen(promise3, onFulfilled, onRejected) { + return originalPromiseThen.call(promise3, onFulfilled, onRejected); } - static fromString(namespace) { - if (typeof namespace !== "string" || namespace === "") { - throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); - } - const [db, ...collectionParts] = namespace.split("."); - const collection = collectionParts.join("."); - return new MongoDBNamespace(db, collection === "" ? undefined : collection); + function uponPromise(promise3, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise3, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); } - } - exports.MongoDBNamespace = MongoDBNamespace; - - class MongoDBCollectionNamespace extends MongoDBNamespace { - constructor(db, collection) { - super(db, collection); - this.collection = collection; + function uponFulfillment(promise3, onFulfilled) { + uponPromise(promise3, onFulfilled); } - static fromString(namespace) { - return super.fromString(namespace); + function uponRejection(promise3, onRejected) { + uponPromise(promise3, undefined, onRejected); } - } - exports.MongoDBCollectionNamespace = MongoDBCollectionNamespace; - function* makeCounter(seed = 0) { - let count = seed; - while (true) { - const newCount = count; - count += 1; - yield newCount; + function transformPromiseWith(promise3, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise3, fulfillmentHandler, rejectionHandler); } - } - function uuidV4() { - const result = crypto3.randomBytes(16); - result[6] = result[6] & 15 | 64; - result[8] = result[8] & 63 | 128; - return result; - } - function maxWireVersion(handshakeAware) { - if (handshakeAware) { - if (handshakeAware.hello) { - return handshakeAware.hello.maxWireVersion; + function setPromiseIsHandledToTrue(promise3) { + PerformPromiseThen(promise3, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = (callback) => { + if (typeof queueMicrotask === "function") { + _queueMicrotask = queueMicrotask; + } else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb); } - if (handshakeAware.serverApi?.version) { - return constants_1.MAX_SUPPORTED_WIRE_VERSION; + return _queueMicrotask(callback); + }; + function reflectCall(F2, V2, args) { + if (typeof F2 !== "function") { + throw new TypeError("Argument is not a function"); } - if (handshakeAware.loadBalanced) { - return constants_1.MAX_SUPPORTED_WIRE_VERSION; + return Function.prototype.apply.call(F2, V2, args); + } + function promiseCall(F2, V2, args) { + try { + return promiseResolvedWith(reflectCall(F2, V2, args)); + } catch (value) { + return promiseRejectedWith(value); } - if ("lastHello" in handshakeAware && typeof handshakeAware.lastHello === "function") { - const lastHello = handshakeAware.lastHello(); - if (lastHello) { - return lastHello.maxWireVersion; + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; } + ++this._size; } - if (handshakeAware.description && "maxWireVersion" in handshakeAware.description && handshakeAware.description.maxWireVersion != null) { - return handshakeAware.description.maxWireVersion; + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = undefined; + return element; + } + forEach(callback) { + let i2 = this._cursor; + let node = this._front; + let elements = node._elements; + while (i2 !== elements.length || node._next !== undefined) { + if (i2 === elements.length) { + node = node._next; + elements = node._elements; + i2 = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i2]); + ++i2; + } + } + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + const AbortSteps = Symbol("[[AbortSteps]]"); + const ErrorSteps = Symbol("[[ErrorSteps]]"); + const CancelSteps = Symbol("[[CancelSteps]]"); + const PullSteps = Symbol("[[PullSteps]]"); + const ReleaseSteps = Symbol("[[ReleaseSteps]]"); + function ReadableStreamReaderGenericInitialize(reader, stream2) { + reader._ownerReadableStream = stream2; + stream2._reader = reader; + if (stream2._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream2._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream2._storedError); } } - return 0; - } - function arrayStrictEqual(arr3, arr22) { - if (!Array.isArray(arr3) || !Array.isArray(arr22)) { - return false; + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream2 = reader._ownerReadableStream; + return ReadableStreamCancel(stream2, reason); } - return arr3.length === arr22.length && arr3.every((elt, idx) => elt === arr22[idx]); - } - function errorStrictEqual(lhs, rhs) { - if (lhs === rhs) { - return true; + function ReadableStreamReaderGenericRelease(reader) { + const stream2 = reader._ownerReadableStream; + if (stream2._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream2._readableStreamController[ReleaseSteps](); + stream2._reader = undefined; + reader._ownerReadableStream = undefined; } - if (!lhs || !rhs) { - return lhs === rhs; + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); } - if (lhs == null && rhs != null || lhs != null && rhs == null) { - return false; + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve2, reject) => { + reader._closedPromise_resolve = resolve2; + reader._closedPromise_reject = reject; + }); } - if (lhs.constructor.name !== rhs.constructor.name) { - return false; + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); } - if (lhs.message !== rhs.message) { - return false; + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); } - return true; - } - function makeStateMachine(stateTable) { - return function stateTransition(target, newState) { - const legalStates = stateTable[target.s.state]; - if (legalStates && legalStates.indexOf(newState) < 0) { - throw new error_1.MongoRuntimeError(`illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]`); + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; } - target.emit("stateChanged", target.s.state, newState); - target.s.state = newState; + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + const NumberIsFinite = Number.isFinite || function(x2) { + return typeof x2 === "number" && isFinite(x2); }; - } - function now() { - const hrtime = process.hrtime(); - return Math.floor(hrtime[0] * 1000 + hrtime[1] / 1e6); - } - function calculateDurationInMs(started) { - if (typeof started !== "number") { - return -1; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x2) { + return typeof x2 === "object" || typeof x2 === "function"; } - const elapsed2 = now() - started; - return elapsed2 < 0 ? 0 : elapsed2; - } - function hasAtomicOperators(doc3, options) { - if (Array.isArray(doc3)) { - for (const document2 of doc3) { - if (hasAtomicOperators(document2)) { - return true; - } + function assertDictionary(obj, context2) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context2} is not an object.`); } - return false; } - const keys = Object.keys(doc3); - if (options?.ignoreUndefined) { - let allUndefined = true; - for (const key of keys) { - if (doc3[key] !== undefined) { - allUndefined = false; - break; - } + function assertFunction(x2, context2) { + if (typeof x2 !== "function") { + throw new TypeError(`${context2} is not a function.`); } - if (allUndefined) { - throw new error_1.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided."); + } + function isObject4(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + function assertObject(x2, context2) { + if (!isObject4(x2)) { + throw new TypeError(`${context2} is not an object.`); } } - return keys.length > 0 && keys[0][0] === "$"; - } - function resolveTimeoutOptions(client2, options) { - const { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS } = client2.s.options; - return { socketTimeoutMS, serverSelectionTimeoutMS, waitQueueTimeoutMS, timeoutMS, ...options }; - } - function resolveOptions(parent, options) { - const result = Object.assign({}, options, (0, bson_1.resolveBSONOptions)(options, parent)); - const timeoutMS = options?.timeoutMS ?? parent?.timeoutMS; - const session = options?.session; - if (!session?.inTransaction()) { - const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; - if (readConcern) { - result.readConcern = readConcern; + function assertRequiredArgument(x2, position, context2) { + if (x2 === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context2}'.`); } - let writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; - if (writeConcern) { - if (timeoutMS != null) { - writeConcern = write_concern_1.WriteConcern.fromOptions({ - writeConcern: { - ...writeConcern, - wtimeout: undefined, - wtimeoutMS: undefined - } - }); - } - result.writeConcern = writeConcern; + } + function assertRequiredField(x2, field, context2) { + if (x2 === undefined) { + throw new TypeError(`${field} is required in '${context2}'.`); } } - result.timeoutMS = timeoutMS; - const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? parent?.readPreference; - if (readPreference) { - result.readPreference = readPreference; + function convertUnrestrictedDouble(value) { + return Number(value); } - const isConvenientTransaction = session?.explicit && session?.timeoutContext != null; - if (isConvenientTransaction && options?.timeoutMS != null) { - throw new error_1.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting"); + function censorNegativeZero(x2) { + return x2 === 0 ? 0 : x2; } - return result; - } - function isSuperset(set3, subset) { - set3 = Array.isArray(set3) ? new Set(set3) : set3; - subset = Array.isArray(subset) ? new Set(subset) : subset; - for (const elem of subset) { - if (!set3.has(elem)) { + function integerPart(x2) { + return censorNegativeZero(MathTrunc(x2)); + } + function convertUnsignedLongLongWithEnforceRange(value, context2) { + const lowerBound2 = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x2 = Number(value); + x2 = censorNegativeZero(x2); + if (!NumberIsFinite(x2)) { + throw new TypeError(`${context2} is not a finite number`); + } + x2 = integerPart(x2); + if (x2 < lowerBound2 || x2 > upperBound) { + throw new TypeError(`${context2} is outside the accepted range of ${lowerBound2} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x2) || x2 === 0) { + return 0; + } + return x2; + } + function assertReadableStream(x2, context2) { + if (!IsReadableStream(x2)) { + throw new TypeError(`${context2} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream2) { + return new ReadableStreamDefaultReader(stream2); + } + function ReadableStreamAddReadRequest(stream2, readRequest) { + stream2._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream2, chunk, done) { + const reader = stream2._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream2) { + return stream2._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream2) { + const reader = stream2._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { return false; } + return true; } - return true; - } - function isHello(doc3) { - return doc3[constants_2.LEGACY_HELLO_COMMAND] || doc3.hello ? true : false; - } - function setDifference(setA, setB) { - const difference = new Set(setA); - for (const elem of setB) { - difference.delete(elem); + + class ReadableStreamDefaultReader { + constructor(stream2) { + assertRequiredArgument(stream2, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream2, "First parameter"); + if (IsReadableStreamLocked(stream2)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream2); + this._readRequests = new SimpleQueue; + } + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise3 = newPromise((resolve2, reject) => { + resolvePromise = resolve2; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: (e) => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise3; + } + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } } - return difference; - } - var HAS_OWN = (object3, prop) => Object.prototype.hasOwnProperty.call(object3, prop); - function isRecord4(value, requiredKeys = undefined) { - if (!isObject4(value)) { - return false; + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel"); + setFunctionName(ReadableStreamDefaultReader.prototype.read, "read"); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); } - const ctor = value.constructor; - if (ctor && ctor.prototype) { - if (!isObject4(ctor.prototype)) { + function IsReadableStreamDefaultReader(x2) { + if (!typeIsObject(x2)) { return false; } - if (!HAS_OWN(ctor.prototype, "isPrototypeOf")) { + if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { return false; } + return x2 instanceof ReadableStreamDefaultReader; } - if (requiredKeys) { - const keys = Object.keys(value); - return isSuperset(keys, requiredKeys); + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream2 = reader._ownerReadableStream; + stream2._disturbed = true; + if (stream2._state === "closed") { + readRequest._closeSteps(); + } else if (stream2._state === "errored") { + readRequest._errorSteps(stream2._storedError); + } else { + stream2._readableStreamController[PullSteps](readRequest); + } } - return true; - } - - class List { - get length() { - return this.count; + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError("Reader was released"); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); } - get [Symbol.toStringTag]() { - return "List"; + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue; + readRequests.forEach((readRequest) => { + readRequest._errorSteps(e); + }); } - constructor() { - this.count = 0; - this.head = { - next: null, - prev: null, - value: null - }; - this.head.next = this.head; - this.head.prev = this.head; + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); } - toArray() { - return Array.from(this); + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise3 = newPromise((resolve2, reject) => { + resolvePromise = resolve2; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = undefined; + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise3; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } } - toString() { - return `head <=> ${this.toArray().join(" <=> ")} <=> head`; + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + function AcquireReadableStreamAsyncIterator(stream2, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream2); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; } - *[Symbol.iterator]() { - for (const node of this.nodes()) { - yield node.value; + function IsReadableStreamAsyncIterator(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { + return false; + } + try { + return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a6) { + return false; } } - *nodes() { - let ptr = this.head.next; - while (ptr !== this.head) { - const { next } = ptr; - yield ptr; - ptr = next; + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x2) { + return x2 !== x2; + }; + var _a5, _b, _c; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n4) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n4), destOffset); + } + let TransferArrayBuffer = (O2) => { + if (typeof O2.transfer === "function") { + TransferArrayBuffer = (buffer) => buffer.transfer(); + } else if (typeof structuredClone === "function") { + TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] }); + } else { + TransferArrayBuffer = (buffer) => buffer; + } + return TransferArrayBuffer(O2); + }; + let IsDetachedBuffer = (O2) => { + if (typeof O2.detached === "boolean") { + IsDetachedBuffer = (buffer) => buffer.detached; + } else { + IsDetachedBuffer = (buffer) => buffer.byteLength === 0; + } + return IsDetachedBuffer(O2); + }; + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; } - push(value) { - this.count += 1; - const newNode = { - next: this.head, - prev: this.head.prev, - value - }; - this.head.prev.next = newNode; - this.head.prev = newNode; + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return; + } + if (typeof func !== "function") { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + const asyncIterator = async function* () { + return yield* syncIterable; + }(); + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + const SymbolAsyncIterator = (_c = (_a5 = Symbol.asyncIterator) !== null && _a5 !== undefined ? _a5 : (_b = Symbol.for) === null || _b === undefined ? undefined : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== undefined ? _c : "@@asyncIterator"; + function GetIterator(obj, hint = "sync", method) { + if (method === undefined) { + if (hint === "async") { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, "sync", syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError("The object is not iterable"); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError("The iterator method must return an object"); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; } - pushMany(iterable) { - for (const value of iterable) { - this.push(value); + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError("The iterator.next() method must return an object"); } + return result; } - unshift(value) { - this.count += 1; - const newNode = { - next: this.head.next, - prev: this.head, - value - }; - this.head.next.prev = newNode; - this.head.next = newNode; + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); } - remove(node) { - if (node === this.head || this.length === 0) { - return null; + function IteratorValue(iterResult) { + return iterResult.value; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; } - this.count -= 1; - const prevNode = node.prev; - const nextNode = node.next; - prevNode.next = nextNode; - nextNode.prev = prevNode; - return node.value; + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; } - shift() { - return this.remove(this.head.next); + function CloneAsUint8Array(O2) { + const buffer = ArrayBufferSlice(O2.buffer, O2.byteOffset, O2.byteOffset + O2.byteLength); + return new Uint8Array(buffer); } - pop() { - return this.remove(this.head.prev); + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; } - prune(filter) { - for (const node of this.nodes()) { - if (filter(node.value)) { - this.remove(node); - } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); } + container._queue.push({ value, size }); + container._queueTotalSize += size; } - clear() { - this.count = 0; - this.head.next = this.head; - this.head.prev = this.head; + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; } - first() { - return this.head.next.value; + function ResetQueue(container) { + container._queue = new SimpleQueue; + container._queueTotalSize = 0; } - last() { - return this.head.prev.value; + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view3) { + return isDataViewConstructor(view3.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; } - } - exports.List = List; - class BufferPool { - constructor() { - this.buffers = new List; - this.totalByteLength = 0; + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view3) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view3, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view3)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view3.buffer)) { + throw new TypeError("The given view's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view3); + } } - get length() { - return this.totalByteLength; + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond"); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); } - append(buffer) { - this.buffers.push(buffer); - this.totalByteLength += buffer.length; + + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e); + } + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream2 = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream2, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = "none"; + this._pendingPullIntos = new SimpleQueue; + this._pendingPullIntos.push(firstPullInto); + } + } } - getInt32() { - if (this.totalByteLength < 4) { - return null; + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, "close"); + setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue"); + setFunctionName(ReadableByteStreamController.prototype.error, "error"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x2) { + if (!typeIsObject(x2)) { + return false; } - const firstBuffer = this.buffers.first(); - if (firstBuffer != null && firstBuffer.byteLength >= 4) { - return firstBuffer.readInt32LE(0); + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) { + return false; } - const top4Bytes = this.read(4); - const value = top4Bytes.readInt32LE(0); - this.totalByteLength += 4; - this.buffers.unshift(top4Bytes); - return value; + return x2 instanceof ReadableByteStreamController; } - read(size) { - if (typeof size !== "number" || size < 0) { - throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + function IsReadableStreamBYOBRequest(x2) { + if (!typeIsObject(x2)) { + return false; } - if (size > this.totalByteLength) { - return Buffer.alloc(0); + if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) { + return false; } - const result = Buffer.allocUnsafe(size); - for (let bytesRead = 0;bytesRead < size; ) { - const buffer = this.buffers.shift(); - if (buffer == null) { - break; + return x2 instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); } - const bytesRemaining = size - bytesRead; - const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); - const bytes = buffer.subarray(0, bytesReadable); - result.set(bytes, bytesRead); - bytesRead += bytesReadable; - this.totalByteLength -= bytesReadable; - if (bytesReadable < buffer.byteLength) { - this.buffers.unshift(buffer.subarray(bytesReadable)); + return null; + }, (e) => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue; + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream2, pullIntoDescriptor) { + let done = false; + if (stream2._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream2, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream2, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue2 = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue2.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue2.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; } - return result; + return ready; } - } - exports.BufferPool = BufferPool; - - class HostAddress { - constructor(hostString) { - this.host = undefined; - this.port = undefined; - this.socketPath = undefined; - this.isIPv6 = false; - const escapedHost = hostString.split(" ").join("%20"); - if (escapedHost.endsWith(".sock")) { - this.socketPath = decodeURIComponent(escapedHost); + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { return; } - const urlString = `iLoveJS://${escapedHost}`; - let url4; + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view3, min, readIntoRequest) { + const stream2 = controller._controlledReadableByteStream; + const ctor = view3.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view3; + const minimumFill = min * elementSize; + let buffer; try { - url4 = new url_1.URL(urlString); - } catch (urlError) { - const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); - runtimeError.cause = urlError; - throw runtimeError; + buffer = TransferArrayBuffer(view3.buffer); + } catch (e) { + readIntoRequest._errorSteps(e); + return; } - const hostname4 = url4.hostname; - const port = url4.port; - let normalized = decodeURIComponent(hostname4).toLowerCase(); - if (normalized.startsWith("[") && normalized.endsWith("]")) { - this.isIPv6 = true; - normalized = normalized.substring(1, hostname4.length - 1); + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream2, readIntoRequest); + return; } - this.host = normalized.toLowerCase(); - if (typeof port === "number") { - this.port = port; - } else if (typeof port === "string" && port !== "") { - this.port = Number.parseInt(port, 10); + if (stream2._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream2, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === "none") { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream2 = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream2)) { + while (ReadableStreamGetNumReadIntoRequests(stream2) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream2, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "none") { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); } else { - this.port = 27017; + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } - if (this.port === 0) { - throw new error_1.MongoParseError("Invalid port (zero) with hostname"); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream2 = controller._controlledReadableByteStream; + if (stream2._state !== "readable") { + return false; } - Object.freeze(this); + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream2) && ReadableStreamGetNumReadIntoRequests(stream2) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; } - [Symbol.for("nodejs.util.inspect.custom")]() { - return this.inspect(); + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; } - inspect() { - return `new HostAddress('${this.toString()}')`; + function ReadableByteStreamControllerClose(controller) { + const stream2 = controller._controlledReadableByteStream; + if (controller._closeRequested || stream2._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream2); } - toString() { - if (typeof this.host === "string") { - if (this.isIPv6) { - return `[${this.host}]:${this.port}`; + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream2 = controller._controlledReadableByteStream; + if (controller._closeRequested || stream2._state !== "readable") { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError("chunk's buffer is detached and so cannot be enqueued"); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk"); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === "none") { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); } - return `${this.host}:${this.port}`; } - return `${this.socketPath}`; + if (ReadableStreamHasDefaultReader(stream2)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream2) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream2, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream2)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); } - static fromString(s) { - return new HostAddress(s); + function ReadableByteStreamControllerError(controller, e) { + const stream2 = controller._controlledReadableByteStream; + if (stream2._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream2, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view3 = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view3); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view3 = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view3); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; } - static fromHostPort(host, port) { - if (host.includes(":")) { - host = `[${host}]`; + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } } - return HostAddress.fromString(`${host}:${port}`); + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } - static fromSrvRecord({ name, port }) { - return HostAddress.fromHostPort(name, port); + function ReadableByteStreamControllerRespondWithNewView(controller, view3) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view3.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view3.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view3.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view3.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view3.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view3.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view3.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream2; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue; + stream2._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, (r2) => { + ReadableByteStreamControllerError(controller, r2); + return null; + }); } - toHostPort() { - if (this.socketPath) { - return { host: this.socketPath, port: 0 }; + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream2, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } else { + startAlgorithm = () => { + return; + }; } - const host = this.host ?? ""; - const port = this.port ?? 0; - return { host, port }; + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); } - } - exports.HostAddress = HostAddress; - exports.DEFAULT_PK_FACTORY = { - createPk() { - return new bson_1.ObjectId; + function SetUpReadableStreamBYOBRequest(request, controller, view3) { + request._associatedReadableByteStreamController = controller; + request._view = view3; } - }; - exports.MONGODB_WARNING_CODE = "MONGODB DRIVER"; - function emitWarning(message) { - return process.emitWarning(message, { code: exports.MONGODB_WARNING_CODE }); - } - var emittedWarnings = new Set; - function emitWarningOnce(message) { - if (!emittedWarnings.has(message)) { - emittedWarnings.add(message); - return emitWarning(message); + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); } - } - function enumToString(en) { - return Object.values(en).join(", "); - } - function supportsRetryableWrites(server) { - if (!server) { - return false; + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); } - if (server.loadBalanced) { - return true; + function convertReaderOptions(options, context2) { + assertDictionary(options, context2); + const mode = options === null || options === undefined ? undefined : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context2} has member 'mode' that`) + }; } - if (server.description.logicalSessionTimeoutMinutes != null) { - if (server.description.type !== common_1.ServerType.Standalone) { - return true; + function convertReadableStreamReaderMode(mode, context2) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context2} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); } + return mode; } - return false; - } - function shuffle(sequence, limit = 0) { - const items = Array.from(sequence); - if (limit > items.length) { - throw new error_1.MongoRuntimeError("Limit must be less than the number of items"); + function convertByobReadOptions(options, context2) { + var _a6; + assertDictionary(options, context2); + const min = (_a6 = options === null || options === undefined ? undefined : options.min) !== null && _a6 !== undefined ? _a6 : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context2} has member 'min' that`) + }; } - let remainingItemsToShuffle = items.length; - const lowerBound2 = limit % items.length === 0 ? 1 : items.length - limit; - while (remainingItemsToShuffle > lowerBound2) { - const randomIndex = Math.floor(Math.random() * remainingItemsToShuffle); - remainingItemsToShuffle -= 1; - const swapHold = items[remainingItemsToShuffle]; - items[remainingItemsToShuffle] = items[randomIndex]; - items[randomIndex] = swapHold; + function AcquireReadableStreamBYOBReader(stream2) { + return new ReadableStreamBYOBReader(stream2); } - return limit % items.length === 0 ? items : items.slice(lowerBound2); - } - function commandSupportsReadConcern(command) { - if (command.aggregate || command.count || command.distinct || command.find || command.geoNear) { + function ReadableStreamAddReadIntoRequest(stream2, readIntoRequest) { + stream2._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream2, chunk, done) { + const reader = stream2._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream2) { + return stream2._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream2) { + const reader = stream2._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } return true; } - return false; - } - function compareObjectId(oid1, oid2) { - if (oid1 == null && oid2 == null) { - return 0; + + class ReadableStreamBYOBReader { + constructor(stream2) { + assertRequiredArgument(stream2, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream2, "First parameter"); + if (IsReadableStreamLocked(stream2)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream2._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte " + "source"); + } + ReadableStreamReaderGenericInitialize(this, stream2); + this._readIntoRequests = new SimpleQueue; + } + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view3, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view3)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view3.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view3.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view3.buffer)) { + return promiseRejectedWith(new TypeError("view's buffer has been detached")); + } + let options; + try { + options = convertByobReadOptions(rawOptions, "options"); + } catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError("options.min must be greater than 0")); + } + if (!isDataView(view3)) { + if (min > view3.length) { + return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length")); + } + } else if (min > view3.byteLength) { + return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise3 = newPromise((resolve2, reject) => { + resolvePromise = resolve2; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e) => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view3, min, readIntoRequest); + return promise3; + } + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } } - if (oid1 == null) { - return -1; + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel"); + setFunctionName(ReadableStreamBYOBReader.prototype.read, "read"); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); } - if (oid2 == null) { - return 1; + function IsReadableStreamBYOBReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) { + return false; + } + return x2 instanceof ReadableStreamBYOBReader; } - return exports.ByteUtils.compare(oid1.id, oid2.id); - } - function parseInteger(value) { - if (typeof value === "number") - return Math.trunc(value); - const parsedValue = Number.parseInt(String(value), 10); - return Number.isNaN(parsedValue) ? null : parsedValue; - } - function parseUnsignedInteger(value) { - const parsedInt = parseInteger(value); - return parsedInt != null && parsedInt >= 0 ? parsedInt : null; - } - function checkParentDomainMatch(address, srvHost) { - const normalizedAddress = address.endsWith(".") ? address.slice(0, address.length - 1) : address; - const normalizedSrvHost = srvHost.endsWith(".") ? srvHost.slice(0, srvHost.length - 1) : srvHost; - const allCharacterBeforeFirstDot = /^.*?\./; - const srvIsLessThanThreeParts = normalizedSrvHost.split(".").length < 3; - const addressDomain = `.${normalizedAddress.replace(allCharacterBeforeFirstDot, "")}`; - let srvHostDomain = srvIsLessThanThreeParts ? normalizedSrvHost : `.${normalizedSrvHost.replace(allCharacterBeforeFirstDot, "")}`; - if (!srvHostDomain.startsWith(".")) { - srvHostDomain = "." + srvHostDomain; + function ReadableStreamBYOBReaderRead(reader, view3, min, readIntoRequest) { + const stream2 = reader._ownerReadableStream; + stream2._disturbed = true; + if (stream2._state === "errored") { + readIntoRequest._errorSteps(stream2._storedError); + } else { + ReadableByteStreamControllerPullInto(stream2._readableStreamController, view3, min, readIntoRequest); + } } - if (srvIsLessThanThreeParts && normalizedAddress.split(".").length <= normalizedSrvHost.split(".").length) { - throw new error_1.MongoAPIError("Server record does not have at least one more domain level than parent URI"); + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError("Reader was released"); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); } - if (!addressDomain.endsWith(srvHostDomain)) { - throw new error_1.MongoAPIError("Server record does not share hostname with parent URI"); + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue; + readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e); + }); } - } - function get(url4, options = {}) { - return new Promise((resolve2, reject) => { - let timeoutId; - const request2 = http.get(url4, options, (response) => { - response.setEncoding("utf8"); - let body = ""; - response.on("data", (chunk) => body += chunk); - response.on("end", () => { - (0, timers_1.clearTimeout)(timeoutId); - resolve2({ status: response.statusCode, body }); - }); - }).on("error", (error91) => { - (0, timers_1.clearTimeout)(timeoutId); - reject(error91); - }).end(); - timeoutId = (0, timers_1.setTimeout)(() => { - request2.destroy(new error_1.MongoNetworkTimeoutError(`request timed out after 10 seconds`)); - }, 1e4); - }); - } - async function request(uri2, options = {}) { - return await new Promise((resolve2, reject) => { - const requestOptions = { - method: "GET", - timeout: 1e4, - json: true, - ...url3.parse(uri2), - ...options + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context2) { + assertDictionary(init, context2); + const highWaterMark = init === null || init === undefined ? undefined : init.highWaterMark; + const size = init === null || init === undefined ? undefined : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context2} has member 'size' that`) }; - const req = http.request(requestOptions, (res) => { - res.setEncoding("utf8"); - let data = ""; - res.on("data", (d) => { - data += d; - }); - res.once("end", () => { - if (options.json === false) { - resolve2(data); - return; - } - try { - const parsed = JSON.parse(data); - resolve2(parsed); - } catch { - reject(new error_1.MongoRuntimeError(`Invalid JSON response: "${data}"`)); - } - }); - }); - req.once("timeout", () => req.destroy(new error_1.MongoNetworkTimeoutError(`Network request to ${uri2} timed out after ${options.timeout} ms`))); - req.once("error", (error91) => reject(error91)); - req.end(); - }); - } - exports.DOCUMENT_DB_CHECK = /(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/; - exports.COSMOS_DB_CHECK = /\.cosmos\.azure\.com$/; - exports.DOCUMENT_DB_MSG = "You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb"; - exports.COSMOS_DB_MSG = "You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb"; - function isHostMatch(match2, host) { - return host && match2.test(host.toLowerCase()) ? true : false; - } - function promiseWithResolvers2() { - let resolve2; - let reject; - const promise3 = new Promise(function withResolversExecutor(promiseResolve, promiseReject) { - resolve2 = promiseResolve; - reject = promiseReject; - }); - return { promise: promise3, resolve: resolve2, reject }; - } - function squashError(_error) { - return; - } - exports.randomBytes = (0, util_1.promisify)(crypto3.randomBytes); - async function once(ee2, name, options) { - options?.signal?.throwIfAborted(); - const { promise: promise3, resolve: resolve2, reject } = promiseWithResolvers2(); - const onEvent = (data) => resolve2(data); - const onError3 = (error91) => reject(error91); - const abortListener = addAbortListener(options?.signal, function() { - reject(this.reason); - }); - ee2.once(name, onEvent).once("error", onError3); - try { - return await promise3; - } finally { - ee2.off(name, onEvent); - ee2.off("error", onError3); - abortListener?.[exports.kDispose](); } - } - function maybeAddIdToDocuments(collection, document2, options) { - const forceServerObjectId = options.forceServerObjectId ?? collection.db.options?.forceServerObjectId ?? false; - if (forceServerObjectId) { - return document2; + function convertQueuingStrategySize(fn, context2) { + assertFunction(fn, context2); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); } - if (document2._id == null) { - document2._id = collection.s.pkFactory.createPk(); + function convertUnderlyingSink(original, context2) { + assertDictionary(original, context2); + const abort = original === null || original === undefined ? undefined : original.abort; + const close = original === null || original === undefined ? undefined : original.close; + const start = original === null || original === undefined ? undefined : original.start; + const type = original === null || original === undefined ? undefined : original.type; + const write = original === null || original === undefined ? undefined : original.write; + return { + abort: abort === undefined ? undefined : convertUnderlyingSinkAbortCallback(abort, original, `${context2} has member 'abort' that`), + close: close === undefined ? undefined : convertUnderlyingSinkCloseCallback(close, original, `${context2} has member 'close' that`), + start: start === undefined ? undefined : convertUnderlyingSinkStartCallback(start, original, `${context2} has member 'start' that`), + write: write === undefined ? undefined : convertUnderlyingSinkWriteCallback(write, original, `${context2} has member 'write' that`), + type + }; } - return document2; - } - async function fileIsAccessible(fileName, mode) { - try { - await fs_1.promises.access(fileName, mode); - return true; - } catch { - return false; + function convertUnderlyingSinkAbortCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); } - } - function csotMin(duration1, duration22) { - if (duration1 === 0) - return duration22; - if (duration22 === 0) - return duration1; - return Math.min(duration1, duration22); - } - function noop2() { - return; - } - function decorateDecryptionResult(decrypted, original, isTopLevelDecorateCall = true) { - if (isTopLevelDecorateCall) { - if (Buffer.isBuffer(original)) { - original = (0, bson_1.deserialize)(original); + function convertUnderlyingSinkCloseCallback(fn, original, context2) { + assertFunction(fn, context2); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context2) { + assertFunction(fn, context2); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x2, context2) { + if (!IsWritableStream(x2)) { + throw new TypeError(`${context2} is not a WritableStream.`); + } + } + function isAbortSignal(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a6) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController; + } + return; + } + + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); } - if (Buffer.isBuffer(decrypted)) { - throw new error_1.MongoRuntimeError("Expected result of decryption to be deserialized BSON object"); + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); } - } - if (!decrypted || typeof decrypted !== "object") - return; - for (const k2 of Object.keys(decrypted)) { - const originalValue = original[k2]; - if (originalValue && originalValue._bsontype === "Binary" && originalValue.sub_type === 6) { - if (!decrypted[constants_2.kDecoratedKeys]) { - Object.defineProperty(decrypted, constants_2.kDecoratedKeys, { - value: [], - configurable: true, - enumerable: false, - writable: false - }); + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); } - decrypted[constants_2.kDecoratedKeys].push(k2); - continue; + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); } - decorateDecryptionResult(decrypted[k2], originalValue, false); - } - } - exports.kDispose = Symbol.dispose ?? Symbol("dispose"); - function addAbortListener(signal, listener) { - if (signal == null) - return; - signal.addEventListener("abort", listener, { once: true }); - return { [exports.kDispose]: () => signal.removeEventListener("abort", listener) }; - } - async function abortable(promise3, { signal }) { - if (signal == null) { - return await promise3; } - const { promise: aborted3, reject } = promiseWithResolvers2(); - const abortListener = signal.aborted ? reject(signal.reason) : addAbortListener(signal, function() { - reject(this.reason); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } }); - try { - return await Promise.race([promise3, aborted3]); - } finally { - abortListener?.[exports.kDispose](); + setFunctionName(WritableStream.prototype.abort, "abort"); + setFunctionName(WritableStream.prototype.close, "close"); + setFunctionName(WritableStream.prototype.getWriter, "getWriter"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: "WritableStream", + configurable: true + }); } - } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/timeout.js -var require_timeout = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LegacyTimeoutContext = exports.CSOTTimeoutContext = exports.TimeoutContext = exports.Timeout = exports.TimeoutError = undefined; - var timers_1 = __require("timers"); - var error_1 = require_error2(); - var utils_1 = require_utils5(); - - class TimeoutError2 extends Error { - get name() { - return "TimeoutError"; + function AcquireWritableStreamDefaultWriter(stream2) { + return new WritableStreamDefaultWriter(stream2); } - constructor(message, options) { - super(message, options); - this.duration = options.duration; + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream2 = Object.create(WritableStream.prototype); + InitializeWritableStream(stream2); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream2; } - static is(error91) { - return error91 != null && typeof error91 === "object" && "name" in error91 && error91.name === "TimeoutError"; + function InitializeWritableStream(stream2) { + stream2._state = "writable"; + stream2._storedError = undefined; + stream2._writer = undefined; + stream2._writableStreamController = undefined; + stream2._writeRequests = new SimpleQueue; + stream2._inFlightWriteRequest = undefined; + stream2._closeRequest = undefined; + stream2._inFlightCloseRequest = undefined; + stream2._pendingAbortRequest = undefined; + stream2._backpressure = false; + } + function IsWritableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) { + return false; + } + return x2 instanceof WritableStream; } - } - exports.TimeoutError = TimeoutError2; - - class Timeout extends Promise { - get remainingTime() { - if (this.timedOut) - return 0; - if (this.duration === 0) - return Infinity; - return this.start + this.duration - Math.trunc(performance.now()); + function IsWritableStreamLocked(stream2) { + if (stream2._writer === undefined) { + return false; + } + return true; } - get timeElapsed() { - return Math.trunc(performance.now()) - this.start; + function WritableStreamAbort(stream2, reason) { + var _a6; + if (stream2._state === "closed" || stream2._state === "errored") { + return promiseResolvedWith(undefined); + } + stream2._writableStreamController._abortReason = reason; + (_a6 = stream2._writableStreamController._abortController) === null || _a6 === undefined || _a6.abort(reason); + const state = stream2._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(undefined); + } + if (stream2._pendingAbortRequest !== undefined) { + return stream2._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = undefined; + } + const promise3 = newPromise((resolve2, reject) => { + stream2._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve2, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream2._pendingAbortRequest._promise = promise3; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream2, reason); + } + return promise3; } - constructor(executor = () => null, options) { - const duration5 = options?.duration ?? 0; - const unref = !!options?.unref; - const rejection = options?.rejection; - if (duration5 < 0) { - throw new error_1.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration"); + function WritableStreamClose(stream2) { + const state = stream2._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); } - let reject; - super((_2, promiseReject) => { - reject = promiseReject; - executor(utils_1.noop, promiseReject); + const promise3 = newPromise((resolve2, reject) => { + const closeRequest = { + _resolve: resolve2, + _reject: reject + }; + stream2._closeRequest = closeRequest; }); - this.ended = null; - this.timedOut = false; - this.cleared = false; - this.duration = duration5; - this.start = Math.trunc(performance.now()); - if (rejection == null && this.duration > 0) { - this.id = (0, timers_1.setTimeout)(() => { - this.ended = Math.trunc(performance.now()); - this.timedOut = true; - reject(new TimeoutError2(`Expired after ${duration5}ms`, { duration: duration5 })); - }, this.duration); - if (typeof this.id.unref === "function" && unref) { - this.id.unref(); - } - } else if (rejection != null) { - this.ended = Math.trunc(performance.now()); - this.timedOut = true; - reject(rejection); + const writer3 = stream2._writer; + if (writer3 !== undefined && stream2._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer3); } + WritableStreamDefaultControllerClose(stream2._writableStreamController); + return promise3; } - clear() { - (0, timers_1.clearTimeout)(this.id); - this.id = undefined; - this.timedOut = false; - this.cleared = true; + function WritableStreamAddWriteRequest(stream2) { + const promise3 = newPromise((resolve2, reject) => { + const writeRequest = { + _resolve: resolve2, + _reject: reject + }; + stream2._writeRequests.push(writeRequest); + }); + return promise3; } - throwIfExpired() { - if (this.timedOut) { - this.then(undefined, utils_1.squashError); - throw new TimeoutError2("Timed out", { duration: this.duration }); + function WritableStreamDealWithRejection(stream2, error91) { + const state = stream2._state; + if (state === "writable") { + WritableStreamStartErroring(stream2, error91); + return; } + WritableStreamFinishErroring(stream2); } - static expires(duration5, unref) { - return new Timeout(undefined, { duration: duration5, unref }); + function WritableStreamStartErroring(stream2, reason) { + const controller = stream2._writableStreamController; + stream2._state = "erroring"; + stream2._storedError = reason; + const writer3 = stream2._writer; + if (writer3 !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer3, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream2) && controller._started) { + WritableStreamFinishErroring(stream2); + } } - static reject(rejection) { - return new Timeout(undefined, { duration: 0, unref: true, rejection }); + function WritableStreamFinishErroring(stream2) { + stream2._state = "errored"; + stream2._writableStreamController[ErrorSteps](); + const storedError = stream2._storedError; + stream2._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream2._writeRequests = new SimpleQueue; + if (stream2._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2); + return; + } + const abortRequest = stream2._pendingAbortRequest; + stream2._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2); + return; + } + const promise3 = stream2._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise3, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2); + return null; + }); } - } - exports.Timeout = Timeout; - function isLegacyTimeoutContextOptions(v) { - return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "waitQueueTimeoutMS" in v && typeof v.waitQueueTimeoutMS === "number"; - } - function isCSOTTimeoutContextOptions(v) { - return v != null && typeof v === "object" && "serverSelectionTimeoutMS" in v && typeof v.serverSelectionTimeoutMS === "number" && "timeoutMS" in v && typeof v.timeoutMS === "number"; - } - - class TimeoutContext { - static create(options) { - if (options.session?.timeoutContext != null) - return options.session?.timeoutContext; - if (isCSOTTimeoutContextOptions(options)) - return new CSOTTimeoutContext(options); - else if (isLegacyTimeoutContextOptions(options)) - return new LegacyTimeoutContext(options); - else - throw new error_1.MongoRuntimeError("Unrecognized options"); + function WritableStreamFinishInFlightWrite(stream2) { + stream2._inFlightWriteRequest._resolve(undefined); + stream2._inFlightWriteRequest = undefined; } - } - exports.TimeoutContext = TimeoutContext; - - class CSOTTimeoutContext extends TimeoutContext { - constructor(options) { - super(); - this.minRoundTripTime = 0; - this.start = Math.trunc(performance.now()); - this.timeoutMS = options.timeoutMS; - this.serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; - this.socketTimeoutMS = options.socketTimeoutMS; - this.clearServerSelectionTimeout = false; + function WritableStreamFinishInFlightWriteWithError(stream2, error91) { + stream2._inFlightWriteRequest._reject(error91); + stream2._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream2, error91); } - get maxTimeMS() { - return this.remainingTimeMS - this.minRoundTripTime; + function WritableStreamFinishInFlightClose(stream2) { + stream2._inFlightCloseRequest._resolve(undefined); + stream2._inFlightCloseRequest = undefined; + const state = stream2._state; + if (state === "erroring") { + stream2._storedError = undefined; + if (stream2._pendingAbortRequest !== undefined) { + stream2._pendingAbortRequest._resolve(); + stream2._pendingAbortRequest = undefined; + } + } + stream2._state = "closed"; + const writer3 = stream2._writer; + if (writer3 !== undefined) { + defaultWriterClosedPromiseResolve(writer3); + } } - get remainingTimeMS() { - const timePassed = Math.trunc(performance.now()) - this.start; - return this.timeoutMS <= 0 ? Infinity : this.timeoutMS - timePassed; + function WritableStreamFinishInFlightCloseWithError(stream2, error91) { + stream2._inFlightCloseRequest._reject(error91); + stream2._inFlightCloseRequest = undefined; + if (stream2._pendingAbortRequest !== undefined) { + stream2._pendingAbortRequest._reject(error91); + stream2._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream2, error91); } - csotEnabled() { + function WritableStreamCloseQueuedOrInFlight(stream2) { + if (stream2._closeRequest === undefined && stream2._inFlightCloseRequest === undefined) { + return false; + } return true; } - get serverSelectionTimeout() { - if (typeof this._serverSelectionTimeout !== "object" || this._serverSelectionTimeout?.cleared) { - const { remainingTimeMS, serverSelectionTimeoutMS } = this; - if (remainingTimeMS <= 0) - return Timeout.reject(new error_1.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`)); - const usingServerSelectionTimeoutMS = serverSelectionTimeoutMS !== 0 && (0, utils_1.csotMin)(remainingTimeMS, serverSelectionTimeoutMS) === serverSelectionTimeoutMS; - if (usingServerSelectionTimeoutMS) { - this._serverSelectionTimeout = Timeout.expires(serverSelectionTimeoutMS); + function WritableStreamHasOperationMarkedInFlight(stream2) { + if (stream2._inFlightWriteRequest === undefined && stream2._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream2) { + stream2._inFlightCloseRequest = stream2._closeRequest; + stream2._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream2) { + stream2._inFlightWriteRequest = stream2._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream2) { + if (stream2._closeRequest !== undefined) { + stream2._closeRequest._reject(stream2._storedError); + stream2._closeRequest = undefined; + } + const writer3 = stream2._writer; + if (writer3 !== undefined) { + defaultWriterClosedPromiseReject(writer3, stream2._storedError); + } + } + function WritableStreamUpdateBackpressure(stream2, backpressure) { + const writer3 = stream2._writer; + if (writer3 !== undefined && backpressure !== stream2._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer3); } else { - if (remainingTimeMS > 0 && Number.isFinite(remainingTimeMS)) { - this._serverSelectionTimeout = Timeout.expires(remainingTimeMS); - } else { - this._serverSelectionTimeout = null; - } + defaultWriterReadyPromiseResolve(writer3); } } - return this._serverSelectionTimeout; + stream2._backpressure = backpressure; } - get connectionCheckoutTimeout() { - if (typeof this._connectionCheckoutTimeout !== "object" || this._connectionCheckoutTimeout?.cleared) { - if (typeof this._serverSelectionTimeout === "object") { - this._connectionCheckoutTimeout = this._serverSelectionTimeout; + + class WritableStreamDefaultWriter { + constructor(stream2) { + assertRequiredArgument(stream2, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream2, "First parameter"); + if (IsWritableStreamLocked(stream2)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream2; + stream2._writer = this; + const state = stream2._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream2) && stream2._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream2._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); } else { - throw new error_1.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira"); + const storedError = stream2._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); } } - return this._connectionCheckoutTimeout; - } - get timeoutForSocketWrite() { - const { remainingTimeMS } = this; - if (!Number.isFinite(remainingTimeMS)) - return null; - if (remainingTimeMS > 0) - return Timeout.expires(remainingTimeMS); - return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket write")); + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream2 = this._ownerWritableStream; + if (stream2 === undefined) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream2)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream2 = this._ownerWritableStream; + if (stream2 === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } } - get timeoutForSocketRead() { - const { remainingTimeMS } = this; - if (!Number.isFinite(remainingTimeMS)) - return null; - if (remainingTimeMS > 0) - return Timeout.expires(remainingTimeMS); - return Timeout.reject(new error_1.MongoOperationTimeoutError("Timed out before socket read")); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort"); + setFunctionName(WritableStreamDefaultWriter.prototype.close, "close"); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock"); + setFunctionName(WritableStreamDefaultWriter.prototype.write, "write"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); } - refresh() { - this.start = Math.trunc(performance.now()); - this.minRoundTripTime = 0; - this._serverSelectionTimeout?.clear(); - this._connectionCheckoutTimeout?.clear(); + function IsWritableStreamDefaultWriter(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultWriter; } - clear() { - this._serverSelectionTimeout?.clear(); - this._connectionCheckoutTimeout?.clear(); + function WritableStreamDefaultWriterAbort(writer3, reason) { + const stream2 = writer3._ownerWritableStream; + return WritableStreamAbort(stream2, reason); } - getRemainingTimeMSOrThrow(message) { - const { remainingTimeMS } = this; - if (remainingTimeMS <= 0) - throw new error_1.MongoOperationTimeoutError(message ?? `Expired after ${this.timeoutMS}ms`); - return remainingTimeMS; + function WritableStreamDefaultWriterClose(writer3) { + const stream2 = writer3._ownerWritableStream; + return WritableStreamClose(stream2); } - clone() { - const timeoutContext = new CSOTTimeoutContext({ - timeoutMS: this.timeoutMS, - serverSelectionTimeoutMS: this.serverSelectionTimeoutMS - }); - timeoutContext.start = this.start; - return timeoutContext; + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer3) { + const stream2 = writer3._ownerWritableStream; + const state = stream2._state; + if (WritableStreamCloseQueuedOrInFlight(stream2) || state === "closed") { + return promiseResolvedWith(undefined); + } + if (state === "errored") { + return promiseRejectedWith(stream2._storedError); + } + return WritableStreamDefaultWriterClose(writer3); } - refreshed() { - return new CSOTTimeoutContext(this); + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer3, error91) { + if (writer3._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer3, error91); + } else { + defaultWriterClosedPromiseResetToRejected(writer3, error91); + } } - addMaxTimeMSToCommand(command, options) { - if (options.omitMaxTimeMS) - return; - const maxTimeMS = this.remainingTimeMS - this.minRoundTripTime; - if (maxTimeMS > 0 && Number.isFinite(maxTimeMS)) - command.maxTimeMS = maxTimeMS; + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer3, error91) { + if (writer3._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer3, error91); + } else { + defaultWriterReadyPromiseResetToRejected(writer3, error91); + } } - getSocketTimeoutMS() { - return 0; + function WritableStreamDefaultWriterGetDesiredSize(writer3) { + const stream2 = writer3._ownerWritableStream; + const state = stream2._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream2._writableStreamController); } - } - exports.CSOTTimeoutContext = CSOTTimeoutContext; - - class LegacyTimeoutContext extends TimeoutContext { - constructor(options) { - super(); - this.options = options; - this.clearServerSelectionTimeout = true; + function WritableStreamDefaultWriterRelease(writer3) { + const stream2 = writer3._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer3, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer3, releasedError); + stream2._writer = undefined; + writer3._ownerWritableStream = undefined; } - csotEnabled() { - return false; + function WritableStreamDefaultWriterWrite(writer3, chunk) { + const stream2 = writer3._ownerWritableStream; + const controller = stream2._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream2 !== writer3._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream2._state; + if (state === "errored") { + return promiseRejectedWith(stream2._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream2) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream2._storedError); + } + const promise3 = WritableStreamAddWriteRequest(stream2); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise3; } - get serverSelectionTimeout() { - if (this.options.serverSelectionTimeoutMS != null && this.options.serverSelectionTimeoutMS > 0) - return Timeout.expires(this.options.serverSelectionTimeoutMS); - return null; + const closeSentinel = {}; + + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === undefined) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e); + } + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [ErrorSteps]() { + ResetQueue(this); + } } - get connectionCheckoutTimeout() { - if (this.options.waitQueueTimeoutMS != null && this.options.waitQueueTimeoutMS > 0) - return Timeout.expires(this.options.waitQueueTimeoutMS); - return null; + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); } - get timeoutForSocketWrite() { - return null; + function IsWritableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream2; + stream2._writableStreamController = controller; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream2, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, (r2) => { + controller._started = true; + WritableStreamDealWithRejection(stream2, r2); + return null; + }); } - get timeoutForSocketRead() { - return null; + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream2, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } else { + startAlgorithm = () => { + return; + }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream2, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); } - refresh() { - return; + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; } - clear() { - return; + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } - get maxTimeMS() { - return null; + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } } - refreshed() { - return new LegacyTimeoutContext(this.options); + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; } - addMaxTimeMSToCommand(_command, _options) {} - getSocketTimeoutMS() { - return this.options.socketTimeoutMS; + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream2 = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream2) && stream2._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream2, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } - } - exports.LegacyTimeoutContext = LegacyTimeoutContext; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/explain.js -var require_explain = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Explain = exports.ExplainVerbosity = undefined; - exports.validateExplainTimeoutOptions = validateExplainTimeoutOptions; - exports.decorateWithExplain = decorateWithExplain; - var error_1 = require_error2(); - exports.ExplainVerbosity = Object.freeze({ - queryPlanner: "queryPlanner", - queryPlannerExtended: "queryPlannerExtended", - executionStats: "executionStats", - allPlansExecution: "allPlansExecution" - }); - - class Explain { - constructor(verbosity, maxTimeMS) { - if (typeof verbosity === "boolean") { - this.verbosity = verbosity ? exports.ExplainVerbosity.allPlansExecution : exports.ExplainVerbosity.queryPlanner; + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream2 = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream2._inFlightWriteRequest !== undefined) { + return; + } + const state = stream2._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream2); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); } else { - this.verbosity = verbosity; + WritableStreamDefaultControllerProcessWrite(controller, value); } - this.maxTimeMS = maxTimeMS; } - static fromOptions({ explain } = {}) { - if (explain == null) - return; - if (typeof explain === "boolean" || typeof explain === "string") { - return new Explain(explain); + function WritableStreamDefaultControllerErrorIfNeeded(controller, error91) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error91); } - const { verbosity, maxTimeMS } = explain; - return new Explain(verbosity, maxTimeMS); } - } - exports.Explain = Explain; - function validateExplainTimeoutOptions(options, explain) { - const { maxTimeMS, timeoutMS } = options; - if (timeoutMS != null && (maxTimeMS != null || explain?.maxTimeMS != null)) { - throw new error_1.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands."); + function WritableStreamDefaultControllerProcessClose(controller) { + const stream2 = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream2); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream2); + return null; + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream2, reason); + return null; + }); } - } - function decorateWithExplain(command, explain) { - const { verbosity, maxTimeMS } = explain; - const baseCommand = { explain: command, verbosity }; - if (typeof maxTimeMS === "number") { - baseCommand.maxTimeMS = maxTimeMS; + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream2 = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream2); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream2); + const state = stream2._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream2) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream2, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, (reason) => { + if (stream2._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream2, reason); + return null; + }); } - return baseCommand; - } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/operation.js -var require_operation = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AbstractOperation = exports.Aspect = undefined; - exports.defineAspects = defineAspects; - var bson_1 = require_bson2(); - var read_preference_1 = require_read_preference(); - exports.Aspect = { - READ_OPERATION: Symbol("READ_OPERATION"), - WRITE_OPERATION: Symbol("WRITE_OPERATION"), - RETRYABLE: Symbol("RETRYABLE"), - EXPLAINABLE: Symbol("EXPLAINABLE"), - SKIP_COLLATION: Symbol("SKIP_COLLATION"), - CURSOR_CREATING: Symbol("CURSOR_CREATING"), - MUST_SELECT_SAME_SERVER: Symbol("MUST_SELECT_SAME_SERVER"), - COMMAND_BATCHING: Symbol("COMMAND_BATCHING"), - SUPPORTS_RAW_DATA: Symbol("SUPPORTS_RAW_DATA") - }; - - class AbstractOperation { - constructor(options = {}) { - this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) ? read_preference_1.ReadPreference.primary : read_preference_1.ReadPreference.fromOptions(options) ?? read_preference_1.ReadPreference.primary; - this.bsonOptions = (0, bson_1.resolveBSONOptions)(options); - this._session = options.session != null ? options.session : undefined; - this.options = options; - this.bypassPinningCheck = !!options.bypassPinningCheck; + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; } - hasAspect(aspect) { - const ctor = this.constructor; - if (ctor.aspects == null) { - return false; - } - return ctor.aspects.has(aspect); + function WritableStreamDefaultControllerError(controller, error91) { + const stream2 = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream2, error91); } - get session() { - return this._session; + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); } - set session(session) { - this._session = session; + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); } - clearSession() { - this._session = undefined; + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); } - resetBatch() { - return true; + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); } - get canRetryRead() { - return this.hasAspect(exports.Aspect.RETRYABLE) && this.hasAspect(exports.Aspect.READ_OPERATION); + function defaultWriterClosedPromiseInitialize(writer3) { + writer3._closedPromise = newPromise((resolve2, reject) => { + writer3._closedPromise_resolve = resolve2; + writer3._closedPromise_reject = reject; + writer3._closedPromiseState = "pending"; + }); } - get canRetryWrite() { - return this.hasAspect(exports.Aspect.RETRYABLE) && this.hasAspect(exports.Aspect.WRITE_OPERATION); + function defaultWriterClosedPromiseInitializeAsRejected(writer3, reason) { + defaultWriterClosedPromiseInitialize(writer3); + defaultWriterClosedPromiseReject(writer3, reason); } - handleOk(response) { - return response.toObject(this.bsonOptions); + function defaultWriterClosedPromiseInitializeAsResolved(writer3) { + defaultWriterClosedPromiseInitialize(writer3); + defaultWriterClosedPromiseResolve(writer3); } - handleError(error91) { - throw error91; + function defaultWriterClosedPromiseReject(writer3, reason) { + if (writer3._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer3._closedPromise); + writer3._closedPromise_reject(reason); + writer3._closedPromise_resolve = undefined; + writer3._closedPromise_reject = undefined; + writer3._closedPromiseState = "rejected"; } - } - exports.AbstractOperation = AbstractOperation; - function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; + function defaultWriterClosedPromiseResetToRejected(writer3, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer3, reason); } - aspects = new Set(aspects); - Object.defineProperty(operation, "aspects", { - value: aspects, - writable: false - }); - return aspects; - } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/command.js -var require_command = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CommandOperation = undefined; - var constants_1 = require_constants5(); - var error_1 = require_error2(); - var explain_1 = require_explain(); - var read_concern_1 = require_read_concern(); - var utils_1 = require_utils5(); - var write_concern_1 = require_write_concern(); - var operation_1 = require_operation(); - - class CommandOperation extends operation_1.AbstractOperation { - constructor(parent, options) { - super(options); - this.options = options ?? {}; - const dbNameOverride = options?.dbName || options?.authdb; - if (dbNameOverride) { - this.ns = new utils_1.MongoDBNamespace(dbNameOverride, "$cmd"); - } else { - this.ns = parent ? parent.s.namespace.withCollection("$cmd") : new utils_1.MongoDBNamespace("admin", "$cmd"); - } - this.readConcern = read_concern_1.ReadConcern.fromOptions(options); - this.writeConcern = write_concern_1.WriteConcern.fromOptions(options); - if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { - this.explain = explain_1.Explain.fromOptions(options); - if (this.explain) - (0, explain_1.validateExplainTimeoutOptions)(this.options, this.explain); - } else if (options?.explain != null) { - throw new error_1.MongoInvalidArgumentError(`Option "explain" is not supported on this command`); + function defaultWriterClosedPromiseResolve(writer3) { + if (writer3._closedPromise_resolve === undefined) { + return; } + writer3._closedPromise_resolve(undefined); + writer3._closedPromise_resolve = undefined; + writer3._closedPromise_reject = undefined; + writer3._closedPromiseState = "resolved"; } - get canRetryWrite() { - if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { - return this.explain == null; - } - return super.canRetryWrite; + function defaultWriterReadyPromiseInitialize(writer3) { + writer3._readyPromise = newPromise((resolve2, reject) => { + writer3._readyPromise_resolve = resolve2; + writer3._readyPromise_reject = reject; + }); + writer3._readyPromiseState = "pending"; } - buildOptions(timeoutContext) { - return { - ...this.options, - ...this.bsonOptions, - timeoutContext, - readPreference: this.readPreference, - session: this.session - }; + function defaultWriterReadyPromiseInitializeAsRejected(writer3, reason) { + defaultWriterReadyPromiseInitialize(writer3); + defaultWriterReadyPromiseReject(writer3, reason); } - buildCommand(connection, session) { - const command = this.buildCommandDocument(connection, session); - const inTransaction = this.session && this.session.inTransaction(); - if (this.readConcern && (0, utils_1.commandSupportsReadConcern)(command) && !inTransaction) { - Object.assign(command, { readConcern: this.readConcern }); + function defaultWriterReadyPromiseInitializeAsResolved(writer3) { + defaultWriterReadyPromiseInitialize(writer3); + defaultWriterReadyPromiseResolve(writer3); + } + function defaultWriterReadyPromiseReject(writer3, reason) { + if (writer3._readyPromise_reject === undefined) { + return; } - if (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { - write_concern_1.WriteConcern.apply(command, this.writeConcern); + setPromiseIsHandledToTrue(writer3._readyPromise); + writer3._readyPromise_reject(reason); + writer3._readyPromise_resolve = undefined; + writer3._readyPromise_reject = undefined; + writer3._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer3) { + defaultWriterReadyPromiseInitialize(writer3); + } + function defaultWriterReadyPromiseResetToRejected(writer3, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer3, reason); + } + function defaultWriterReadyPromiseResolve(writer3) { + if (writer3._readyPromise_resolve === undefined) { + return; } - if (this.options.collation && typeof this.options.collation === "object" && !this.hasAspect(operation_1.Aspect.SKIP_COLLATION)) { - Object.assign(command, { collation: this.options.collation }); + writer3._readyPromise_resolve(undefined); + writer3._readyPromise_resolve = undefined; + writer3._readyPromise_reject = undefined; + writer3._readyPromiseState = "fulfilled"; + } + function getGlobals() { + if (typeof globalThis !== "undefined") { + return globalThis; + } else if (typeof self !== "undefined") { + return self; + } else if (typeof global !== "undefined") { + return global; } - if (typeof this.options.maxTimeMS === "number") { - command.maxTimeMS = this.options.maxTimeMS; + return; + } + const globals = getGlobals(); + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; } - if (this.options.rawData != null && this.hasAspect(operation_1.Aspect.SUPPORTS_RAW_DATA) && (0, utils_1.maxWireVersion)(connection) >= constants_1.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION) { - command.rawData = this.options.rawData; + if (ctor.name !== "DOMException") { + return false; } - if (this.hasAspect(operation_1.Aspect.EXPLAINABLE) && this.explain) { - return (0, explain_1.decorateWithExplain)(command, this.explain); + try { + new ctor; + return true; + } catch (_a6) { + return false; } - return command; } - } - exports.CommandOperation = CommandOperation; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/aggregate.js -var require_aggregate = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AggregateOperation = exports.DB_AGGREGATE_COLLECTION = undefined; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var write_concern_1 = require_write_concern(); - var command_1 = require_command(); - var operation_1 = require_operation(); - exports.DB_AGGREGATE_COLLECTION = 1; + function getFromGlobal() { + const ctor = globals === null || globals === undefined ? undefined : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + function createPolyfill() { + const ctor = function DOMException3(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, "DOMException"); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException2 = getFromGlobal() || createPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer3 = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve2, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error91 = signal.reason !== undefined ? signal.reason : new DOMException2("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error91); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error91); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error91); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer3._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer3, chunk), undefined, noop2); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + return null; + }); + isOrBecomesErrored(dest, writer3._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + return null; + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer3)); + } else { + shutdown(); + } + return null; + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream2, promise3, action) { + if (stream2._state === "errored") { + action(stream2._storedError); + } else { + uponRejection(promise3, action); + } + } + function isOrBecomesClosed(stream2, promise3, action) { + if (stream2._state === "closed") { + action(); + } else { + uponFulfillment(promise3, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize2(originalIsError, originalError), (newError) => finalize2(true, newError)); + return null; + } + } + function shutdown(isError5, error91) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize2(isError5, error91)); + } else { + finalize2(isError5, error91); + } + } + function finalize2(isError5, error91) { + WritableStreamDefaultWriterRelease(writer3); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError5) { + reject(error91); + } else { + resolve2(undefined); + } + return null; + } + }); + } - class AggregateOperation extends command_1.CommandOperation { - constructor(ns3, pipeline, options) { - super(undefined, { ...options, dbName: ns3.db }); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; - this.options = { ...options }; - this.target = ns3.collection || exports.DB_AGGREGATE_COLLECTION; - this.pipeline = pipeline; - this.hasWriteStage = false; - if (typeof options?.out === "string") { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); } + return ReadableStreamDefaultControllerGetDesiredSize(this); } - if (!this.hasWriteStage) { - delete this.options.writeConcern; + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); } - if (this.explain && this.writeConcern) { - throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); } - if (options?.cursor != null && typeof options.cursor !== "object") { - throw new error_1.MongoInvalidArgumentError("Cursor options must be an object"); + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e); } - this.SERVER_COMMAND_RESPONSE_TYPE = this.explain ? responses_1.ExplainedCursorResponse : responses_1.CursorResponse; + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream2 = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream2); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream2, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + [ReleaseSteps]() {} } - get commandName() { - return "aggregate"; + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, "close"); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue"); + setFunctionName(ReadableStreamDefaultController.prototype.error, "error"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); } - get canRetryRead() { - return !this.hasWriteStage; + function IsReadableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) { + return false; + } + return x2 instanceof ReadableStreamDefaultController; } - addToPipeline(stage) { - this.pipeline.push(stage); + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, (e) => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); } - buildCommandDocument() { - const options = this.options; - const command = { aggregate: this.target, pipeline: this.pipeline }; - if (this.hasWriteStage && this.writeConcern) { - write_concern_1.WriteConcern.apply(command, this.writeConcern); + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream2 = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; } - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; + if (!controller._started) { + return false; } - if (typeof options.allowDiskUse === "boolean") { - command.allowDiskUse = options.allowDiskUse; + if (IsReadableStreamLocked(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) { + return true; } - if (options.hint) { - command.hint = options.hint; + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; } - if (options.let) { - command.let = options.let; + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; } - if (options.comment !== undefined) { - command.comment = options.comment; + const stream2 = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream2); } - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; } - return command; + const stream2 = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream2) && ReadableStreamGetNumReadRequests(stream2) > 0) { + ReadableStreamFulfillReadRequest(stream2, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); } - handleOk(response) { - return response; + function ReadableStreamDefaultControllerError(controller, e) { + const stream2 = controller._controlledReadableStream; + if (stream2._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream2, e); } - } - exports.AggregateOperation = AggregateOperation; - (0, operation_1.defineAspects)(AggregateOperation, [ - operation_1.Aspect.READ_OPERATION, - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.EXPLAINABLE, - operation_1.Aspect.CURSOR_CREATING, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/execute_operation.js -var require_execute_operation = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.executeOperation = executeOperation; - exports.autoConnect = autoConnect; - var error_1 = require_error2(); - var read_preference_1 = require_read_preference(); - var server_selection_1 = require_server_selection(); - var timeout_1 = require_timeout(); - var utils_1 = require_utils5(); - var aggregate_1 = require_aggregate(); - var operation_1 = require_operation(); - var MMAPv1_RETRY_WRITES_ERROR_CODE = error_1.MONGODB_ERROR_CODES.IllegalOperation; - var MMAPv1_RETRY_WRITES_ERROR_MESSAGE = "This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string."; - async function executeOperation(client2, operation, timeoutContext) { - if (!(operation instanceof operation_1.AbstractOperation)) { - throw new error_1.MongoRuntimeError("This method requires a valid operation instance"); + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; } - const topology = client2.topology == null ? await (0, utils_1.abortable)(autoConnect(client2), operation.options) : client2.topology; - let session = operation.session; - let owner; - if (session == null) { - owner = Symbol(); - session = client2.startSession({ owner, explicit: false }); - } else if (session.hasEnded) { - throw new error_1.MongoExpiredSessionError("Use of expired sessions is not permitted"); - } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { - throw new error_1.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later"); - } else if (session.client !== client2) { - throw new error_1.MongoInvalidArgumentError("ClientSession must be from the same MongoClient"); + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; } - operation.session ??= session; - const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; - const inTransaction = !!session?.inTransaction(); - const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); - if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary) && (hasReadAspect || operation.commandName === "runCommand")) { - throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; } - if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) { - session.unpin(); + function SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream2; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream2._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, (r2) => { + ReadableStreamDefaultControllerError(controller, r2); + return null; + }); } - timeoutContext ??= timeout_1.TimeoutContext.create({ - session, - serverSelectionTimeoutMS: client2.s.options.serverSelectionTimeoutMS, - waitQueueTimeoutMS: client2.s.options.waitQueueTimeoutMS, - timeoutMS: operation.options.timeoutMS - }); - try { - return await tryOperation(operation, { - topology, - timeoutContext, - session, - readPreference + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream2, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } else { + startAlgorithm = () => { + return; + }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream2, cloneForBranch2) { + if (IsReadableByteStreamController(stream2._readableStreamController)) { + return ReadableByteStreamTee(stream2); + } + return ReadableStreamDefaultTee(stream2); + } + function ReadableStreamDefaultTee(stream2, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream2); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve2) => { + resolveCancelPromise = resolve2; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream2, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream2, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() {} + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r2) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r2); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; }); - } finally { - if (session?.owner != null && session.owner === owner) { - await session.endSession(); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream2) { + let reader = AcquireReadableStreamDefaultReader(stream2); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve2) => { + resolveCancelPromise = resolve2; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r2) => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r2); + ReadableByteStreamControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); } - } - } - async function autoConnect(client2) { - if (client2.topology == null) { - if (client2.s.hasBeenClosed) { - throw new error_1.MongoNotConnectedError("Client must be connected before running operations"); + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream2); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream2, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view3, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream2); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream2, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view3, 1, readIntoRequest); } - client2.s.options.__skipPingOnConnect = true; - try { - await client2.connect(); - if (client2.topology == null) { - throw new error_1.MongoRuntimeError("client.connect did not create a topology but also did not throw"); + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); } - return client2.topology; - } finally { - delete client2.s.options.__skipPingOnConnect; + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream2, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream2, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; } - return client2.topology; - } - async function tryOperation(operation, { topology, timeoutContext, session, readPreference }) { - let selector; - if (operation.hasAspect(operation_1.Aspect.MUST_SELECT_SAME_SERVER)) { - selector = (0, server_selection_1.sameServerSelector)(operation.server?.description); - } else if (operation instanceof aggregate_1.AggregateOperation && operation.hasWriteStage) { - selector = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); - } else { - selector = readPreference; + function isReadableStreamLike(stream2) { + return typeIsObject(stream2) && typeof stream2.getReader !== "undefined"; } - let server = await topology.selectServer(selector, { - session, - operationName: operation.commandName, - timeoutContext, - signal: operation.options.signal - }); - const hasReadAspect = operation.hasAspect(operation_1.Aspect.READ_OPERATION); - const hasWriteAspect = operation.hasAspect(operation_1.Aspect.WRITE_OPERATION); - const inTransaction = session?.inTransaction() ?? false; - const willRetryRead = topology.s.options.retryReads && !inTransaction && operation.canRetryRead; - const willRetryWrite = topology.s.options.retryWrites && !inTransaction && (0, utils_1.supportsRetryableWrites)(server) && operation.canRetryWrite; - const willRetry = operation.hasAspect(operation_1.Aspect.RETRYABLE) && session != null && (hasReadAspect && willRetryRead || hasWriteAspect && willRetryWrite); - if (hasWriteAspect && willRetryWrite && session != null) { - operation.options.willRetryWrite = true; - session.incrementTransactionNumber(); + function ReadableStreamFrom2(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); } - const maxTries = willRetry ? timeoutContext.csotEnabled() ? Infinity : 2 : 1; - let previousOperationError; - let previousServer; - for (let tries = 0;tries < maxTries; tries++) { - if (previousOperationError) { - if (hasWriteAspect && previousOperationError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { - throw new error_1.MongoServerError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: previousOperationError - }); + function ReadableStreamFromIterable(asyncIterable) { + let stream2; + const iteratorRecord = GetIterator(asyncIterable, "async"); + const startAlgorithm = noop2; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } catch (e) { + return promiseRejectedWith(e); } - if (operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING) && !operation.canRetryWrite) { - throw previousOperationError; + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, (iterResult) => { + if (!typeIsObject(iterResult)) { + throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object"); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream2._readableStreamController); + } else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream2._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, "return"); + } catch (e) { + return promiseRejectedWith(e); } - if (hasWriteAspect && !(0, error_1.isRetryableWriteError)(previousOperationError)) - throw previousOperationError; - if (hasReadAspect && !(0, error_1.isRetryableReadError)(previousOperationError)) { - throw previousOperationError; + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); } - if (previousOperationError instanceof error_1.MongoNetworkError && operation.hasAspect(operation_1.Aspect.CURSOR_CREATING) && session != null && session.isPinned && !session.inTransaction()) { - session.unpin({ force: true, forceClear: true }); + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } catch (e) { + return promiseRejectedWith(e); } - server = await topology.selectServer(selector, { - session, - operationName: operation.commandName, - previousServer, - signal: operation.options.signal + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, (iterResult) => { + if (!typeIsObject(iterResult)) { + throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object"); + } + return; }); - if (hasWriteAspect && !(0, utils_1.supportsRetryableWrites)(server)) { - throw new error_1.MongoUnexpectedServerResponseError("Selected server does not support retryable writes"); + } + stream2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream2; + } + function ReadableStreamFromDefaultReader(reader) { + let stream2; + const startAlgorithm = noop2; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, (readResult) => { + if (!typeIsObject(readResult)) { + throw new TypeError("The promise returned by the reader.read() method must fulfill with an object"); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream2._readableStreamController); + } else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream2._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } catch (e) { + return promiseRejectedWith(e); + } + } + stream2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream2; + } + function convertUnderlyingDefaultOrByteSource(source, context2) { + assertDictionary(source, context2); + const original = source; + const autoAllocateChunkSize = original === null || original === undefined ? undefined : original.autoAllocateChunkSize; + const cancel = original === null || original === undefined ? undefined : original.cancel; + const pull = original === null || original === undefined ? undefined : original.pull; + const start = original === null || original === undefined ? undefined : original.start; + const type = original === null || original === undefined ? undefined : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? undefined : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context2} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? undefined : convertUnderlyingSourceCancelCallback(cancel, original, `${context2} has member 'cancel' that`), + pull: pull === undefined ? undefined : convertUnderlyingSourcePullCallback(pull, original, `${context2} has member 'pull' that`), + start: start === undefined ? undefined : convertUnderlyingSourceStartCallback(start, original, `${context2} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context2} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context2) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context2} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertIteratorOptions(options, context2) { + assertDictionary(options, context2); + const preventCancel = options === null || options === undefined ? undefined : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context2) { + assertDictionary(options, context2); + const preventAbort = options === null || options === undefined ? undefined : options.preventAbort; + const preventCancel = options === null || options === undefined ? undefined : options.preventCancel; + const preventClose = options === null || options === undefined ? undefined : options.preventClose; + const signal = options === null || options === undefined ? undefined : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context2} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context2) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context2} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context2) { + assertDictionary(pair, context2); + const readable = pair === null || pair === undefined ? undefined : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context2} has member 'readable' that`); + const writable = pair === null || pair === undefined ? undefined : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context2} has member 'writable' that`); + return { readable, writable }; + } + + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== undefined) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); } - operation.server = server; - try { - if (tries > 0 && operation.hasAspect(operation_1.Aspect.COMMAND_BATCHING)) { - operation.resetBatch(); + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform3 = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform3.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise3 = ReadableStreamPipeTo(this, transform3.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise3); + return transform3.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; try { - const result = await server.command(operation, timeoutContext); - return operation.handleOk(result); - } catch (error91) { - return operation.handleError(error91); + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e) { + return promiseRejectedWith(e); } - } catch (operationError) { - if (!(operationError instanceof error_1.MongoError)) - throw operationError; - if (previousOperationError != null && operationError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { - throw previousOperationError; + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); } - previousServer = server.description; - previousOperationError = operationError; - timeoutContext.clear(); + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); } - } - throw previousOperationError ?? new error_1.MongoRuntimeError("Tried to propagate retryability error, but no error was found."); - } -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/list_databases.js -var require_list_databases = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ListDatabasesOperation = undefined; - var responses_1 = require_responses(); - var utils_1 = require_utils5(); - var command_1 = require_command(); - var operation_1 = require_operation(); - - class ListDatabasesOperation extends command_1.CommandOperation { - constructor(db, options) { - super(db, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = options ?? {}; - this.ns = new utils_1.MongoDBNamespace("admin", "$cmd"); - } - get commandName() { - return "listDatabases"; - } - buildCommandDocument(connection, _session) { - const cmd = { listDatabases: 1 }; - if (typeof this.options.nameOnly === "boolean") { - cmd.nameOnly = this.options.nameOnly; + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); } - if (this.options.filter) { - cmd.filter = this.options.filter; + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); } - if (typeof this.options.authorizedDatabases === "boolean") { - cmd.authorizedDatabases = this.options.authorizedDatabases; + [SymbolAsyncIterator](options) { + return this.values(options); } - if ((0, utils_1.maxWireVersion)(connection) >= 9 && this.options.comment !== undefined) { - cmd.comment = this.options.comment; + static from(asyncIterable) { + return ReadableStreamFrom2(asyncIterable); } - return cmd; } - } - exports.ListDatabasesOperation = ListDatabasesOperation; - (0, operation_1.defineAspects)(ListDatabasesOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.RETRYABLE]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/remove_user.js -var require_remove_user = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RemoveUserOperation = undefined; - var responses_1 = require_responses(); - var command_1 = require_command(); - var operation_1 = require_operation(); - - class RemoveUserOperation extends command_1.CommandOperation { - constructor(db, username, options) { - super(db, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = options; - this.username = username; + Object.defineProperties(ReadableStream2, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream2.from, "from"); + setFunctionName(ReadableStream2.prototype.cancel, "cancel"); + setFunctionName(ReadableStream2.prototype.getReader, "getReader"); + setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough"); + setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo"); + setFunctionName(ReadableStream2.prototype.tee, "tee"); + setFunctionName(ReadableStream2.prototype.values, "values"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, { + value: "ReadableStream", + configurable: true + }); } - get commandName() { - return "dropUser"; + Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream2 = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream2); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream2; } - buildCommandDocument(_connection) { - return { dropUser: this.username }; + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream2 = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream2); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream2, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream2; } - handleOk(_response) { + function InitializeReadableStream(stream2) { + stream2._state = "readable"; + stream2._reader = undefined; + stream2._storedError = undefined; + stream2._disturbed = false; + } + function IsReadableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) { + return false; + } + return x2 instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream2) { + if (stream2._reader === undefined) { + return false; + } return true; } - } - exports.RemoveUserOperation = RemoveUserOperation; - (0, operation_1.defineAspects)(RemoveUserOperation, [operation_1.Aspect.WRITE_OPERATION]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/run_command.js -var require_run_command = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.RunCursorCommandOperation = exports.RunCommandOperation = undefined; - var responses_1 = require_responses(); - var operation_1 = require_operation(); - - class RunCommandOperation extends operation_1.AbstractOperation { - constructor(namespace, command, options) { - super(options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.command = command; - this.options = options; - this.ns = namespace.withCollection("$cmd"); + function ReadableStreamCancel(stream2, reason) { + stream2._disturbed = true; + if (stream2._state === "closed") { + return promiseResolvedWith(undefined); + } + if (stream2._state === "errored") { + return promiseRejectedWith(stream2._storedError); + } + ReadableStreamClose(stream2); + const reader = stream2._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue; + readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream2._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop2); } - get commandName() { - return "runCommand"; + function ReadableStreamClose(stream2) { + stream2._state = "closed"; + const reader = stream2._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue; + readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + } } - buildCommand(_connection, _session) { - return this.command; + function ReadableStreamError(stream2, e) { + stream2._state = "errored"; + stream2._storedError = e; + const reader = stream2._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } } - buildOptions(timeoutContext) { + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context2) { + assertDictionary(init, context2); + const highWaterMark = init === null || init === undefined ? undefined : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); return { - ...this.options, - session: this.session, - timeoutContext, - signal: this.options.signal, - readPreference: this.options.readPreference + highWaterMark: convertUnrestrictedDouble(highWaterMark) }; } - } - exports.RunCommandOperation = RunCommandOperation; - - class RunCursorCommandOperation extends RunCommandOperation { - constructor() { - super(...arguments); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; - } - handleOk(response) { - return response; - } - } - exports.RunCursorCommandOperation = RunCursorCommandOperation; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/validate_collection.js -var require_validate_collection = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValidateCollectionOperation = undefined; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var command_1 = require_command(); + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, "size"); - class ValidateCollectionOperation extends command_1.CommandOperation { - constructor(admin, collectionName, options) { - super(admin.s.db, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = options; - this.collectionName = collectionName; + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } } - get commandName() { - return "validate"; + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); } - buildCommandDocument(_connection, _session) { - return { - validate: this.collectionName, - ...Object.fromEntries(Object.entries(this.options).filter((entry) => entry[0] !== "session")) - }; + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); } - handleOk(response) { - const result = super.handleOk(response); - if (result.result != null && typeof result.result !== "string") - throw new error_1.MongoUnexpectedServerResponseError("Error with validation data"); - if (result.result != null && result.result.match(/exception|corrupt/) != null) - throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`); - if (result.valid != null && !result.valid) - throw new error_1.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`); - return response; + function IsByteLengthQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof ByteLengthQueuingStrategy; } - } - exports.ValidateCollectionOperation = ValidateCollectionOperation; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/admin.js -var require_admin = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Admin = undefined; - var bson_1 = require_bson2(); - var execute_operation_1 = require_execute_operation(); - var list_databases_1 = require_list_databases(); - var remove_user_1 = require_remove_user(); - var run_command_1 = require_run_command(); - var validate_collection_1 = require_validate_collection(); - var utils_1 = require_utils5(); + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, "size"); - class Admin { - constructor(db) { - this.s = { db }; - } - async command(command, options) { - return await (0, execute_operation_1.executeOperation)(this.s.db.client, new run_command_1.RunCommandOperation(new utils_1.MongoDBNamespace("admin"), command, { - ...(0, bson_1.resolveBSONOptions)(options), - session: options?.session, - readPreference: options?.readPreference, - timeoutMS: options?.timeoutMS ?? this.s.db.timeoutMS - })); + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } } - async buildInfo(options) { - return await this.command({ buildinfo: 1 }, options); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); } - async serverInfo(options) { - return await this.command({ buildinfo: 1 }, options); + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); } - async serverStatus(options) { - return await this.command({ serverStatus: 1 }, options); + function IsCountQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof CountQueuingStrategy; } - async ping(options) { - return await this.command({ ping: 1 }, options); + function convertTransformer(original, context2) { + assertDictionary(original, context2); + const cancel = original === null || original === undefined ? undefined : original.cancel; + const flush = original === null || original === undefined ? undefined : original.flush; + const readableType = original === null || original === undefined ? undefined : original.readableType; + const start = original === null || original === undefined ? undefined : original.start; + const transform3 = original === null || original === undefined ? undefined : original.transform; + const writableType = original === null || original === undefined ? undefined : original.writableType; + return { + cancel: cancel === undefined ? undefined : convertTransformerCancelCallback(cancel, original, `${context2} has member 'cancel' that`), + flush: flush === undefined ? undefined : convertTransformerFlushCallback(flush, original, `${context2} has member 'flush' that`), + readableType, + start: start === undefined ? undefined : convertTransformerStartCallback(start, original, `${context2} has member 'start' that`), + transform: transform3 === undefined ? undefined : convertTransformerTransformCallback(transform3, original, `${context2} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context2) { + assertFunction(fn, context2); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); + } + + class TransformStream2 { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== undefined) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== undefined) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve2) => { + startPromise_resolve = resolve2; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(undefined); + } + } + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } } - async removeUser(username, options) { - return await (0, execute_operation_1.executeOperation)(this.s.db.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: "admin", ...options })); + Object.defineProperties(TransformStream2.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(TransformStream2.prototype, Symbol.toStringTag, { + value: "TransformStream", + configurable: true + }); } - async validateCollection(collectionName, options = {}) { - return await (0, execute_operation_1.executeOperation)(this.s.db.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); + function InitializeTransformStream(stream2, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream2, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream2, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream2); + } + stream2._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream2); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream2, reason); + } + stream2._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream2._backpressure = undefined; + stream2._backpressureChangePromise = undefined; + stream2._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream2, true); + stream2._transformStreamController = undefined; } - async listDatabases(options) { - return await (0, execute_operation_1.executeOperation)(this.s.db.client, new list_databases_1.ListDatabasesOperation(this.s.db, { timeoutMS: this.s.db.timeoutMS, ...options })); + function IsTransformStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) { + return false; + } + return x2 instanceof TransformStream2; } - async replSetGetStatus(options) { - return await this.command({ replSetGetStatus: 1 }, options); + function TransformStreamError(stream2, e) { + ReadableStreamDefaultControllerError(stream2._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream2, e); } - } - exports.Admin = Admin; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/delete.js -var require_delete = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = undefined; - exports.makeDeleteStatement = makeDeleteStatement; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var utils_1 = require_utils5(); - var command_1 = require_command(); - var operation_1 = require_operation(); - - class DeleteOperation extends command_1.CommandOperation { - constructor(ns3, statements, options) { - super(undefined, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = options; - this.ns = ns3; - this.statements = statements; + function TransformStreamErrorWritableAndUnblockWrite(stream2, e) { + TransformStreamDefaultControllerClearAlgorithms(stream2._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream2._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream2); } - get commandName() { - return "delete"; + function TransformStreamUnblockWrite(stream2) { + if (stream2._backpressure) { + TransformStreamSetBackpressure(stream2, false); + } } - get canRetryWrite() { - if (super.canRetryWrite === false) { - return false; + function TransformStreamSetBackpressure(stream2, backpressure) { + if (stream2._backpressureChangePromise !== undefined) { + stream2._backpressureChangePromise_resolve(); } - return this.statements.every((op) => op.limit != null ? op.limit > 0 : true); + stream2._backpressureChangePromise = newPromise((resolve2) => { + stream2._backpressureChangePromise_resolve = resolve2; + }); + stream2._backpressure = backpressure; } - buildCommandDocument(connection, _session) { - const options = this.options; - const ordered = typeof options.ordered === "boolean" ? options.ordered : true; - const command = { - delete: this.ns.collection, - deletes: this.statements, - ordered - }; - if (options.let) { - command.let = options.let; + + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); } - if (options.comment !== undefined) { - command.comment = options.comment; + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); } - const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; - if (unacknowledgedWrite && (0, utils_1.maxWireVersion)(connection) < 9) { - if (this.statements.find((o2) => o2.hint)) { - throw new error_1.MongoCompatibilityError(`hint for the delete command is only supported on MongoDB 4.4+`); + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); } - return command; } - } - exports.DeleteOperation = DeleteOperation; - - class DeleteOneOperation extends DeleteOperation { - constructor(ns3, filter, options) { - super(ns3, [makeDeleteStatement(filter, { ...options, limit: 1 })], options); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue"); + setFunctionName(TransformStreamDefaultController.prototype.error, "error"); + setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); } - handleOk(response) { - const res = super.handleOk(response); - if (this.explain) - return res; - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) - throw new error_1.MongoServerError(res.writeErrors[0]); - return { - acknowledged: this.writeConcern?.w !== 0, - deletedCount: res.n - }; + function IsTransformStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) { + return false; + } + return x2 instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream2, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream2; + stream2._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream2, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } else { + transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = (reason) => transformer.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream2, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); } - } - exports.DeleteOneOperation = DeleteOneOperation; - - class DeleteManyOperation extends DeleteOperation { - constructor(ns3, filter, options) { - super(ns3, [makeDeleteStatement(filter, options)], options); + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; } - handleOk(response) { - const res = super.handleOk(response); - if (this.explain) - return res; - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) - throw new error_1.MongoServerError(res.writeErrors[0]); - return { - acknowledged: this.writeConcern?.w !== 0, - deletedCount: res.n - }; + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream2 = controller._controlledTransformStream; + const readableController = stream2._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e) { + TransformStreamErrorWritableAndUnblockWrite(stream2, e); + throw stream2._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream2._backpressure) { + TransformStreamSetBackpressure(stream2, true); + } } - } - exports.DeleteManyOperation = DeleteManyOperation; - function makeDeleteStatement(filter, options) { - const op = { - q: filter, - limit: typeof options.limit === "number" ? options.limit : 0 - }; - if (options.collation) { - op.collation = options.collation; + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); } - if (options.hint) { - op.hint = options.hint; + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, (r2) => { + TransformStreamError(controller._controlledTransformStream, r2); + throw r2; + }); } - return op; - } - (0, operation_1.defineAspects)(DeleteOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(DeleteOneOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.EXPLAINABLE, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(DeleteManyOperation, [ - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.EXPLAINABLE, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/insert.js -var require_insert = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InsertOneOperation = exports.InsertOperation = undefined; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var utils_1 = require_utils5(); - var command_1 = require_command(); - var operation_1 = require_operation(); - - class InsertOperation extends command_1.CommandOperation { - constructor(ns3, documents, options) { - super(undefined, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = { ...options, checkKeys: options.checkKeys ?? false }; - this.ns = ns3; - this.documents = documents; + function TransformStreamDefaultControllerTerminate(controller) { + const stream2 = controller._controlledTransformStream; + const readableController = stream2._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error91 = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream2, error91); } - get commandName() { - return "insert"; + function TransformStreamDefaultSinkWriteAlgorithm(stream2, chunk) { + const controller = stream2._transformStreamController; + if (stream2._backpressure) { + const backpressureChangePromise = stream2._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream2._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); } - buildCommandDocument(_connection, _session) { - const options = this.options ?? {}; - const ordered = typeof options.ordered === "boolean" ? options.ordered : true; - const command = { - insert: this.ns.collection, - documents: this.documents, - ordered - }; - if (typeof options.bypassDocumentValidation === "boolean") { - command.bypassDocumentValidation = options.bypassDocumentValidation; + function TransformStreamDefaultSinkAbortAlgorithm(stream2, reason) { + const controller = stream2._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; } - if (options.comment !== undefined) { - command.comment = options.comment; + const readable = stream2._readable; + controller._finishPromise = newPromise((resolve2, reject) => { + controller._finishPromise_resolve = resolve2; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === "errored") { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r2) => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r2); + defaultControllerFinishPromiseReject(controller, r2); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream2) { + const controller = stream2._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; } - return command; + const readable = stream2._readable; + controller._finishPromise = newPromise((resolve2, reject) => { + controller._finishPromise_resolve = resolve2; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === "errored") { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r2) => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r2); + defaultControllerFinishPromiseReject(controller, r2); + return null; + }); + return controller._finishPromise; } - } - exports.InsertOperation = InsertOperation; - - class InsertOneOperation extends InsertOperation { - constructor(collection, doc3, options) { - super(collection.s.namespace, [(0, utils_1.maybeAddIdToDocuments)(collection, doc3, options)], options); + function TransformStreamDefaultSourcePullAlgorithm(stream2) { + TransformStreamSetBackpressure(stream2, false); + return stream2._backpressureChangePromise; } - handleOk(response) { - const res = super.handleOk(response); - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) { - throw new error_1.MongoServerError(res.writeErrors[0]); + function TransformStreamDefaultSourceCancelAlgorithm(stream2, reason) { + const controller = stream2._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; } - return { - acknowledged: this.writeConcern?.w !== 0, - insertedId: this.documents[0]._id - }; + const writable = stream2._writable; + controller._finishPromise = newPromise((resolve2, reject) => { + controller._finishPromise_resolve = resolve2; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === "errored") { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream2); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r2) => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r2); + TransformStreamUnblockWrite(stream2); + defaultControllerFinishPromiseReject(controller, r2); + return null; + }); + return controller._finishPromise; } - } - exports.InsertOneOperation = InsertOneOperation; - (0, operation_1.defineAspects)(InsertOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(InsertOneOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/sort.js -var require_sort = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatSort = formatSort; - var error_1 = require_error2(); - function prepareDirection(direction = 1) { - const value = `${direction}`.toLowerCase(); - if (isMeta(direction)) - return direction; - switch (value) { - case "ascending": - case "asc": - case "1": - return 1; - case "descending": - case "desc": - case "-1": - return -1; - default: - throw new error_1.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`); + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); } - } - function isMeta(t2) { - return typeof t2 === "object" && t2 != null && "$meta" in t2 && typeof t2.$meta === "string"; - } - function isPair(t2) { - if (Array.isArray(t2) && t2.length === 2) { + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream2; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + }); +}); + +// ../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS(() => { + var POOL_SIZE = 65536; + if (!globalThis.ReadableStream) { + try { + const process3 = __require("node:process"); + const { emitWarning } = process3; try { - prepareDirection(t2[1]); - return true; - } catch { - return false; + process3.emitWarning = () => {}; + Object.assign(globalThis, __require("node:stream/web")); + process3.emitWarning = emitWarning; + } catch (error91) { + process3.emitWarning = emitWarning; + throw error91; } + } catch (error91) { + Object.assign(globalThis, require_ponyfill_es2018()); } - return false; - } - function isDeep(t2) { - return Array.isArray(t2) && Array.isArray(t2[0]); - } - function isMap(t2) { - return t2 instanceof Map && t2.size > 0; - } - function isReadonlyArray2(value) { - return Array.isArray(value); - } - function pairToMap(v) { - return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); - } - function deepToMap(t2) { - const sortEntries = t2.map(([k2, v]) => [`${k2}`, prepareDirection(v)]); - return new Map(sortEntries); - } - function stringsToMap(t2) { - const sortEntries = t2.map((key) => [`${key}`, 1]); - return new Map(sortEntries); - } - function objectToMap(t2) { - const sortEntries = Object.entries(t2).map(([k2, v]) => [ - `${k2}`, - prepareDirection(v) - ]); - return new Map(sortEntries); - } - function mapToMap(t2) { - const sortEntries = Array.from(t2).map(([k2, v]) => [ - `${k2}`, - prepareDirection(v) - ]); - return new Map(sortEntries); } - function formatSort(sort, direction) { - if (sort == null) - return; - if (typeof sort === "string") - return new Map([[sort, prepareDirection(direction)]]); - if (typeof sort !== "object") { - throw new error_1.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`); - } - if (!isReadonlyArray2(sort)) { - if (isMap(sort)) - return mapToMap(sort); - if (Object.keys(sort).length) - return objectToMap(sort); - return; + try { + const { Blob: Blob2 } = __require("buffer"); + if (Blob2 && !Blob2.prototype.stream) { + Blob2.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; } - if (!sort.length) - return; - if (isDeep(sort)) - return deepToMap(sort); - if (isPair(sort)) - return pairToMap(sort); - return stringsToMap(sort); - } + } catch (error91) {} }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/update.js -var require_update = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ReplaceOneOperation = exports.UpdateManyOperation = exports.UpdateOneOperation = exports.UpdateOperation = undefined; - exports.makeUpdateStatement = makeUpdateStatement; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var sort_1 = require_sort(); - var utils_1 = require_utils5(); - var command_1 = require_command(); - var operation_1 = require_operation(); - - class UpdateOperation extends command_1.CommandOperation { - constructor(ns3, statements, options) { - super(undefined, options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.options = options; - this.ns = ns3; - this.statements = statements; - } - get commandName() { - return "update"; - } - get canRetryWrite() { - if (super.canRetryWrite === false) { - return false; +// ../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/index.js +async function* toIterator(parts, clone3 = true) { + for (const part of parts) { + if ("stream" in part) { + yield* part.stream(); + } else if (ArrayBuffer.isView(part)) { + if (clone3) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b2 = part; + while (position !== b2.size) { + const chunk = b2.slice(position, Math.min(b2.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); } - return this.statements.every((op) => op.multi == null || op.multi === false); } - buildCommandDocument(_connection, _session) { - const options = this.options; - const command = { - update: this.ns.collection, - updates: this.statements, - ordered: options.ordered ?? true - }; - if (typeof options.bypassDocumentValidation === "boolean") { - command.bypassDocumentValidation = options.bypassDocumentValidation; + } +} +var import_streams, POOL_SIZE = 65536, _Blob, Blob3, fetch_blob_default; +var init_fetch_blob = __esm(() => { + import_streams = __toESM(require_streams(), 1); + /*! fetch-blob. MIT License. Jimmy Wärting */ + _Blob = class Blob2 { + #parts = []; + #type = ""; + #size = 0; + #endings = "transparent"; + constructor(blobParts = [], options = {}) { + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); } - if (options.let) { - command.let = options.let; + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); } - if (options.comment !== undefined) { - command.comment = options.comment; + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); } - return command; + if (options === null) + options = {}; + const encoder2 = new TextEncoder; + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof Blob2) { + part = element; + } else { + part = encoder2.encode(`${element}`); + } + this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size; + this.#parts.push(part); + } + this.#endings = `${options.endings === undefined ? "transparent" : options.endings}`; + const type = options.type === undefined ? "" : String(options.type); + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : ""; } - } - exports.UpdateOperation = UpdateOperation; - - class UpdateOneOperation extends UpdateOperation { - constructor(ns3, filter, update, options) { - super(ns3, [makeUpdateStatement(filter, update, { ...options, multi: false })], options); - if (!(0, utils_1.hasAtomicOperators)(update, options)) { - throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + get size() { + return this.#size; + } + get type() { + return this.#type; + } + async text() { + const decoder = new TextDecoder; + let str = ""; + for await (const part of toIterator(this.#parts, false)) { + str += decoder.decode(part, { stream: true }); } + str += decoder.decode(); + return str; } - handleOk(response) { - const res = super.handleOk(response); - if (this.explain != null) - return res; - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) - throw new error_1.MongoServerError(res.writeErrors[0]); - return { - acknowledged: this.writeConcern?.w !== 0, - modifiedCount: res.nModified ?? res.n, - upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, - upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, - matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n - }; + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(this.#parts, false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; } - } - exports.UpdateOneOperation = UpdateOneOperation; - - class UpdateManyOperation extends UpdateOperation { - constructor(ns3, filter, update, options) { - super(ns3, [makeUpdateStatement(filter, update, { ...options, multi: true })], options); - if (!(0, utils_1.hasAtomicOperators)(update, options)) { - throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + stream() { + const it = toIterator(this.#parts, true); + return new globalThis.ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = this.#parts; + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } } + const blob = new Blob2([], { type: String(type).toLowerCase() }); + blob.#size = span; + blob.#parts = blobParts; + return blob; } - handleOk(response) { - const res = super.handleOk(response); - if (this.explain != null) - return res; - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) - throw new error_1.MongoServerError(res.writeErrors[0]); - return { - acknowledged: this.writeConcern?.w !== 0, - modifiedCount: res.nModified ?? res.n, - upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, - upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, - matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n - }; + get [Symbol.toStringTag]() { + return "Blob"; } - } - exports.UpdateManyOperation = UpdateManyOperation; + static [Symbol.hasInstance](object3) { + return object3 && typeof object3 === "object" && typeof object3.constructor === "function" && (typeof object3.stream === "function" || typeof object3.arrayBuffer === "function") && /^(Blob|File)$/.test(object3[Symbol.toStringTag]); + } + }; + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob3 = _Blob; + fetch_blob_default = Blob3; +}); - class ReplaceOneOperation extends UpdateOperation { - constructor(ns3, filter, replacement, options) { - super(ns3, [makeUpdateStatement(filter, replacement, { ...options, multi: false })], options); - if ((0, utils_1.hasAtomicOperators)(replacement)) { - throw new error_1.MongoInvalidArgumentError("Replacement document must not contain atomic operators"); +// ../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/file.js +var _File, File3, file_default; +var init_file = __esm(() => { + init_fetch_blob(); + _File = class File2 extends fetch_blob_default { + #lastModified = 0; + #name = ""; + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + if (options === null) + options = {}; + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + this.#lastModified = lastModified; } + this.#name = String(fileName); } - handleOk(response) { - const res = super.handleOk(response); - if (this.explain != null) - return res; - if (res.code) - throw new error_1.MongoServerError(res); - if (res.writeErrors) - throw new error_1.MongoServerError(res.writeErrors[0]); - return { - acknowledged: this.writeConcern?.w !== 0, - modifiedCount: res.nModified ?? res.n, - upsertedId: Array.isArray(res.upserted) && res.upserted.length > 0 ? res.upserted[0]._id : null, - upsertedCount: Array.isArray(res.upserted) && res.upserted.length ? res.upserted.length : 0, - matchedCount: Array.isArray(res.upserted) && res.upserted.length > 0 ? 0 : res.n - }; + get name() { + return this.#name; } - } - exports.ReplaceOneOperation = ReplaceOneOperation; - function makeUpdateStatement(filter, update, options) { - if (filter == null || typeof filter !== "object") { - throw new error_1.MongoInvalidArgumentError("Selector must be a valid JavaScript object"); + get lastModified() { + return this.#lastModified; } - if (update == null || typeof update !== "object") { - throw new error_1.MongoInvalidArgumentError("Document must be a valid JavaScript object"); + get [Symbol.toStringTag]() { + return "File"; } - const op = { q: filter, u: update }; - if (typeof options.upsert === "boolean") { - op.upsert = options.upsert; + static [Symbol.hasInstance](object3) { + return !!object3 && object3 instanceof fetch_blob_default && /^(File)$/.test(object3[Symbol.toStringTag]); } - if (options.multi) { - op.multi = options.multi; + }; + File3 = _File; + file_default = File3; +}); + +// ../../node_modules/.pnpm/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F2, B2 = fetch_blob_default) { + var b2 = `${r2()}${r2()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c3 = [], p2 = `--${b2}\r +Content-Disposition: form-data; name="`; + F2.forEach((v, n4) => typeof v == "string" ? c3.push(p2 + e(n4) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b2 && b2[t2]) ? [(c3 = c3 !== undefined ? c3 + "" : b2[t2] == "File" ? b2.name : "blob", a), b2.name !== c3 || b2[t2] == "blob" ? new file_default([b2], c3, b2) : b2] : [a, b2 + ""]), e = (c3, f4) => (f4 ? c3 : c3.replace(/\r?\n|\r/g, `\r +`)).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), x2 = (n4, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n4}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } +}, FormData2; +var init_esm_min = __esm(() => { + init_fetch_blob(); + init_file(); + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + ({ toStringTag: t2, iterator: i2, hasInstance: h2 } = Symbol); + r2 = Math.random; + m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","); + FormData2 = class FormData3 { + #d = []; + constructor(...a) { + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t2]() { + return "FormData"; + } + [i2]() { + return this.entries(); + } + static [h2](o2) { + return o2 && typeof o2 === "object" && o2[t2] === "FormData" && !m.some((m2) => typeof o2[m2] != "function"); + } + append(...a) { + x2("append", arguments, 2); + this.#d.push(f3(...a)); + } + delete(a) { + x2("delete", arguments, 1); + a += ""; + this.#d = this.#d.filter(([b2]) => b2 !== a); + } + get(a) { + x2("get", arguments, 1); + a += ""; + for (var b2 = this.#d, l = b2.length, c3 = 0;c3 < l; c3++) + if (b2[c3][0] === a) + return b2[c3][1]; + return null; } - if (options.hint) { - op.hint = options.hint; + getAll(a, b2) { + x2("getAll", arguments, 1); + b2 = []; + a += ""; + this.#d.forEach((c3) => c3[0] === a && b2.push(c3[1])); + return b2; } - if (options.arrayFilters) { - op.arrayFilters = options.arrayFilters; + has(a) { + x2("has", arguments, 1); + a += ""; + return this.#d.some((b2) => b2[0] === a); } - if (options.collation) { - op.collation = options.collation; + forEach(a, b2) { + x2("forEach", arguments, 1); + for (var [c3, d] of this) + a.call(b2, d, c3, this); } - if (!options.multi && options.sort != null) { - op.sort = (0, sort_1.formatSort)(options.sort); + set(...a) { + x2("set", arguments, 2); + var b2 = [], c3 = true; + a = f3(...a); + this.#d.forEach((d) => { + d[0] === a[0] ? c3 && (c3 = !b2.push(a)) : b2.push(d); + }); + c3 && b2.push(a); + this.#d = b2; } - return op; - } - (0, operation_1.defineAspects)(UpdateOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(UpdateOneOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.EXPLAINABLE, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(UpdateManyOperation, [ - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.EXPLAINABLE, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); - (0, operation_1.defineAspects)(ReplaceOneOperation, [ - operation_1.Aspect.RETRYABLE, - operation_1.Aspect.WRITE_OPERATION, - operation_1.Aspect.SKIP_COLLATION, - operation_1.Aspect.SUPPORTS_RAW_DATA - ]); + *entries() { + yield* this.#d; + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/common.js -var require_common5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BulkOperationBase = exports.FindOperators = exports.MongoBulkWriteError = exports.WriteError = exports.WriteConcernError = exports.BulkWriteResult = exports.Batch = exports.BatchType = undefined; - exports.mergeBatchResults = mergeBatchResults; - var bson_1 = require_bson2(); - var error_1 = require_error2(); - var delete_1 = require_delete(); - var execute_operation_1 = require_execute_operation(); - var insert_1 = require_insert(); - var update_1 = require_update(); - var timeout_1 = require_timeout(); - var utils_1 = require_utils5(); - var write_concern_1 = require_write_concern(); - exports.BatchType = Object.freeze({ - INSERT: 1, - UPDATE: 2, - DELETE: 3 - }); +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/base.js +var FetchBaseError; +var init_base18 = __esm(() => { + FetchBaseError = class FetchBaseError extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + }; +}); - class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/fetch-error.js +var FetchError; +var init_fetch_error = __esm(() => { + init_base18(); + FetchError = class FetchError extends FetchBaseError { + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } } - } - exports.Batch = Batch; + }; +}); - class BulkWriteResult { - static generateIdMap(ids) { - const idMap = {}; - for (const doc3 of ids) { - idMap[doc3.index] = doc3._id; +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is.js +var NAME, isURLSearchParameters = (object3) => { + return typeof object3 === "object" && typeof object3.append === "function" && typeof object3.delete === "function" && typeof object3.get === "function" && typeof object3.getAll === "function" && typeof object3.has === "function" && typeof object3.set === "function" && typeof object3.sort === "function" && object3[NAME] === "URLSearchParams"; +}, isBlob = (object3) => { + return object3 && typeof object3 === "object" && typeof object3.arrayBuffer === "function" && typeof object3.type === "string" && typeof object3.stream === "function" && typeof object3.constructor === "function" && /^(Blob|File)$/.test(object3[NAME]); +}, isAbortSignal = (object3) => { + return typeof object3 === "object" && (object3[NAME] === "AbortSignal" || object3[NAME] === "EventTarget"); +}, isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}, isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; +var init_is2 = __esm(() => { + NAME = Symbol.toStringTag; +}); + +// ../../node_modules/.pnpm/node-domexception@1.0.0/node_modules/node-domexception/index.js +var require_node_domexception = __commonJS((exports, module) => { + /*! node-domexception. MIT License. Jimmy Wärting */ + if (!globalThis.DOMException) { + try { + const { MessageChannel: MessageChannel2 } = __require("worker_threads"), port = new MessageChannel2().port1, ab = new ArrayBuffer; + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module.exports = globalThis.DOMException; +}); + +// ../../node_modules/.pnpm/fetch-blob@3.2.0/node_modules/fetch-blob/from.js +import { statSync, createReadStream, promises as fs2 } from "node:fs"; +import { basename as basename2 } from "node:path"; +var import_node_domexception, stat6, blobFromSync = (path4, type) => fromBlob(statSync(path4), path4, type), blobFrom = (path4, type) => stat6(path4).then((stat7) => fromBlob(stat7, path4, type)), fileFrom = (path4, type) => stat6(path4).then((stat7) => fromFile(stat7, path4, type)), fileFromSync = (path4, type) => fromFile(statSync(path4), path4, type), fromBlob = (stat7, path4, type = "") => new fetch_blob_default([new BlobDataItem({ + path: path4, + size: stat7.size, + lastModified: stat7.mtimeMs, + start: 0 +})], { type }), fromFile = (stat7, path4, type = "") => new file_default([new BlobDataItem({ + path: path4, + size: stat7.size, + lastModified: stat7.mtimeMs, + start: 0 +})], basename2(path4), { type, lastModified: stat7.mtimeMs }), BlobDataItem; +var init_from = __esm(() => { + init_file(); + init_fetch_blob(); + import_node_domexception = __toESM(require_node_domexception(), 1); + ({ stat: stat6 } = fs2); + BlobDataItem = class BlobDataItem { + #path; + #start; + constructor(options) { + this.#path = options.path; + this.#start = options.start; + this.size = options.size; + this.lastModified = options.lastModified; + } + slice(start, end) { + return new BlobDataItem({ + path: this.#path, + lastModified: this.lastModified, + size: end - start, + start: this.#start + start + }); + } + async* stream() { + const { mtimeMs } = await stat6(this.#path); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); } - return idMap; + yield* createReadStream(this.#path, { + start: this.#start, + end: this.#start + this.size - 1 + }); } - constructor(bulkResult, isOrdered) { - this.result = bulkResult; - this.insertedCount = this.result.nInserted ?? 0; - this.matchedCount = this.result.nMatched ?? 0; - this.modifiedCount = this.result.nModified ?? 0; - this.deletedCount = this.result.nRemoved ?? 0; - this.upsertedCount = this.result.upserted.length ?? 0; - this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); - this.insertedIds = BulkWriteResult.generateIdMap(this.getSuccessfullyInsertedIds(bulkResult, isOrdered)); - Object.defineProperty(this, "result", { value: this.result, enumerable: false }); + get [Symbol.toStringTag]() { + return "Blob"; + } + }; +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/multipart-parser.js +var exports_multipart_parser = {}; +__export(exports_multipart_parser, { + toFormData: () => toFormData +}); + +class MultipartParser { + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop2; + this.onHeaderField = noop2; + this.onHeadersEnd = noop2; + this.onHeaderValue = noop2; + this.onPartBegin = noop2; + this.onPartData = noop2; + this.onPartEnd = noop2; + this.boundaryChars = {}; + boundary = `\r +--` + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i3 = 0;i3 < boundary.length; i3++) { + ui8a[i3] = boundary.charCodeAt(i3); + this.boundaryChars[ui8a[i3]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S2.START_BOUNDARY; + } + write(data) { + let i3 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index: index2, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c3; + let cl; + const mark = (name) => { + this[name + "Mark"] = i3; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i3, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i3 = 0;i3 < length_; i3++) { + c3 = data[i3]; + switch (state) { + case S2.START_BOUNDARY: + if (index2 === boundary.length - 2) { + if (c3 === HYPHEN) { + flags |= F2.LAST_BOUNDARY; + } else if (c3 !== CR2) { + return; + } + index2++; + break; + } else if (index2 - 1 === boundary.length - 2) { + if (flags & F2.LAST_BOUNDARY && c3 === HYPHEN) { + state = S2.END; + flags = 0; + } else if (!(flags & F2.LAST_BOUNDARY) && c3 === LF2) { + index2 = 0; + callback("onPartBegin"); + state = S2.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c3 !== boundary[index2 + 2]) { + index2 = -2; + } + if (c3 === boundary[index2 + 2]) { + index2++; + } + break; + case S2.HEADER_FIELD_START: + state = S2.HEADER_FIELD; + mark("onHeaderField"); + index2 = 0; + case S2.HEADER_FIELD: + if (c3 === CR2) { + clear("onHeaderField"); + state = S2.HEADERS_ALMOST_DONE; + break; + } + index2++; + if (c3 === HYPHEN) { + break; + } + if (c3 === COLON2) { + if (index2 === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S2.HEADER_VALUE_START; + break; + } + cl = lower(c3); + if (cl < A2 || cl > Z2) { + return; + } + break; + case S2.HEADER_VALUE_START: + if (c3 === SPACE2) { + break; + } + mark("onHeaderValue"); + state = S2.HEADER_VALUE; + case S2.HEADER_VALUE: + if (c3 === CR2) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S2.HEADER_VALUE_ALMOST_DONE; + } + break; + case S2.HEADER_VALUE_ALMOST_DONE: + if (c3 !== LF2) { + return; + } + state = S2.HEADER_FIELD_START; + break; + case S2.HEADERS_ALMOST_DONE: + if (c3 !== LF2) { + return; + } + callback("onHeadersEnd"); + state = S2.PART_DATA_START; + break; + case S2.PART_DATA_START: + state = S2.PART_DATA; + mark("onPartData"); + case S2.PART_DATA: + previousIndex = index2; + if (index2 === 0) { + i3 += boundaryEnd; + while (i3 < bufferLength && !(data[i3] in boundaryChars)) { + i3 += boundaryLength; + } + i3 -= boundaryEnd; + c3 = data[i3]; + } + if (index2 < boundary.length) { + if (boundary[index2] === c3) { + if (index2 === 0) { + dataCallback("onPartData", true); + } + index2++; + } else { + index2 = 0; + } + } else if (index2 === boundary.length) { + index2++; + if (c3 === CR2) { + flags |= F2.PART_BOUNDARY; + } else if (c3 === HYPHEN) { + flags |= F2.LAST_BOUNDARY; + } else { + index2 = 0; + } + } else if (index2 - 1 === boundary.length) { + if (flags & F2.PART_BOUNDARY) { + index2 = 0; + if (c3 === LF2) { + flags &= ~F2.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S2.HEADER_FIELD_START; + break; + } + } else if (flags & F2.LAST_BOUNDARY) { + if (c3 === HYPHEN) { + callback("onPartEnd"); + state = S2.END; + flags = 0; + } else { + index2 = 0; + } + } else { + index2 = 0; + } + } + if (index2 > 0) { + lookbehind[index2 - 1] = c3; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i3--; + } + break; + case S2.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } } - get ok() { - return this.result.ok; + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index2; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S2.HEADER_FIELD_START && this.index === 0 || this.state === S2.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S2.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); } - getSuccessfullyInsertedIds(bulkResult, isOrdered) { - if (bulkResult.writeErrors.length === 0) - return bulkResult.insertedIds; - if (isOrdered) { - return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index); + } +} +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match2 = m2[2] || m2[3] || ""; + let filename = match2.slice(match2.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser4 = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData2; + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file3 = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file3); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser4.onPartBegin = function() { + parser4.onPartData = onPartData; + parser4.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser4.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser4.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser4.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser4.onPartData = appendToFile; + parser4.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body) { + parser4.write(chunk); + } + parser4.end(); + return formData; +} +var s = 0, S2, f4 = 1, F2, LF2 = 10, CR2 = 13, SPACE2 = 32, HYPHEN = 45, COLON2 = 58, A2 = 97, Z2 = 122, lower = (c3) => c3 | 32, noop2 = () => {}; +var init_multipart_parser = __esm(() => { + init_from(); + init_esm_min(); + S2 = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + F2 = { + PART_BOUNDARY: f4, + LAST_BOUNDARY: f4 *= 2 + }; +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/body.js +import Stream2, { PassThrough } from "node:stream"; +import { types as types4, deprecate, promisify } from "node:util"; +import { Buffer as Buffer2 } from "node:buffer"; + +class Body { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = Buffer2.from(body.toString()); + } else if (isBlob(body)) {} else if (Buffer2.isBuffer(body)) {} else if (types4.isAnyArrayBuffer(body)) { + body = Buffer2.from(body); + } else if (ArrayBuffer.isView(body)) { + body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream2) {} else if (body instanceof FormData2) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = Buffer2.from(String(body)); + } + let stream2 = body; + if (Buffer2.isBuffer(body)) { + stream2 = Stream2.Readable.from(body); + } else if (isBlob(body)) { + stream2 = Stream2.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream: stream2, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof Stream2) { + body.on("error", (error_) => { + const error91 = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error91; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData2; + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); } - return bulkResult.insertedIds.filter(({ index: index2 }) => !bulkResult.writeErrors.some((writeError) => index2 === writeError.index)); + return formData; } - getUpsertedIdAt(index2) { - return this.result.upserted[index2]; + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), exports_multipart_parser)); + return toFormData2(this.body, ct); + } + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + async json() { + const text = await this.text(); + return JSON.parse(text); + } + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + buffer() { + return consumeBody(this); + } +} +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return Buffer2.alloc(0); + } + if (!(body instanceof Stream2)) { + return Buffer2.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error91 = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error91); + throw error91; + } + accumBytes += chunk.length; + accum.push(chunk); } - getRawResponse() { - return this.result; + } catch (error91) { + const error_ = error91 instanceof FetchBaseError ? error91 : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error91.message}`, "system", error91); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c3) => typeof c3 === "string")) { + return Buffer2.from(accum.join("")); + } + return Buffer2.concat(accum, accumBytes); + } catch (error91) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error91.message}`, "system", error91); } - hasWriteErrors() { - return this.result.writeErrors.length > 0; + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var pipeline, INTERNALS, clone3 = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof Stream2 && typeof body.getBoundary !== "function") { + p1 = new PassThrough({ highWaterMark }); + p2 = new PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}, getNonSpecFormDataBoundary, extractContentType = (body, request) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (Buffer2.isBuffer(body) || types4.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData2) { + return `multipart/form-data; boundary=${request[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof Stream2) { + return null; + } + return "text/plain;charset=UTF-8"; +}, getTotalBytes = (request) => { + const { body } = request[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (Buffer2.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}, writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; +var init_body = __esm(() => { + init_fetch_blob(); + init_esm_min(); + init_fetch_error(); + init_base18(); + init_is2(); + pipeline = promisify(Stream2.pipeline); + INTERNALS = Symbol("Body internals"); + Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); + Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: deprecate(() => {}, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)") } + }); + getNonSpecFormDataBoundary = deprecate((body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167"); +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/headers.js +import { types as types5 } from "node:util"; +import http from "node:http"; +function fromRawHeaders(headers = []) { + return new Headers2(headers.reduce((result, value, index2, array3) => { + if (index2 % 2 === 0) { + result.push(array3.slice(index2, index2 + 2)); } - getWriteErrorCount() { - return this.result.writeErrors.length; + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; } - getWriteErrorAt(index2) { - return index2 < this.result.writeErrors.length ? this.result.writeErrors[index2] : undefined; + })); +} +var validateHeaderName, validateHeaderValue, Headers2; +var init_headers2 = __esm(() => { + validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error91 = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error91, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error91; } - getWriteErrors() { - return this.result.writeErrors; + }; + validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error91 = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error91, "code", { value: "ERR_INVALID_CHAR" }); + throw error91; } - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return; - } else if (this.result.writeConcernErrors.length === 1) { - return this.result.writeConcernErrors[0]; + }; + Headers2 = class Headers2 extends URLSearchParams { + constructor(init) { + let result = []; + if (init instanceof Headers2) { + const raw2 = init.raw(); + for (const [name, values2] of Object.entries(raw2)) { + result.push(...values2.map((value) => [name, value])); + } + } else if (init == null) {} else if (typeof init === "object" && !types5.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || types5.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } } else { - let errmsg = ""; - for (let i2 = 0;i2 < this.result.writeConcernErrors.length; i2++) { - const err = this.result.writeConcernErrors[i2]; - errmsg = errmsg + err.errmsg; - if (i2 === 0) - errmsg = errmsg + " and "; + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : undefined; + super(result); + return new Proxy(this, { + get(target, p2, receiver) { + switch (p2) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p2].call(target, String(name).toLowerCase(), String(value)); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p2].call(target, String(name).toLowerCase()); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p2, receiver); + } } - return new WriteConcernError({ errmsg, code: error_1.MONGODB_ERROR_CODES.WriteConcernTimeout }); - } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; } toString() { - return `BulkWriteResult(${bson_1.EJSON.stringify(this.result)})`; + return Object.prototype.toString.call(this); } - isOk() { - return this.result.ok === 1; + get(name) { + const values2 = this.getAll(name); + if (values2.length === 0) { + return null; + } + let value = values2.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; } - } - exports.BulkWriteResult = BulkWriteResult; - - class WriteConcernError { - constructor(error91) { - this.serverError = error91; + forEach(callback, thisArg = undefined) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } } - get code() { - return this.serverError.code; + *values() { + for (const name of this.keys()) { + yield this.get(name); + } } - get errmsg() { - return this.serverError.errmsg; + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } } - get errInfo() { - return this.serverError.errInfo; + [Symbol.iterator]() { + return this.entries(); } - toJSON() { - return this.serverError; + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); } - toString() { - return `WriteConcernError(${this.errmsg})`; + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values2 = this.getAll(key); + if (key === "host") { + result[key] = values2[0]; + } else { + result[key] = values2.length > 1 ? values2 : values2[0]; + } + return result; + }, {}); } - } - exports.WriteConcernError = WriteConcernError; + }; + Object.defineProperties(Headers2.prototype, ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; + }, {})); +}); - class WriteError { - constructor(err) { - this.err = err; - } - get code() { - return this.err.code; - } - get index() { - return this.err.index; - } - get errmsg() { - return this.err.errmsg; +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus, isRedirect = (code) => { + return redirectStatus.has(code); +}; +var init_is_redirect = __esm(() => { + redirectStatus = new Set([301, 302, 303, 307, 308]); +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/response.js +var INTERNALS2, Response3; +var init_response = __esm(() => { + init_headers2(); + init_body(); + init_is_redirect(); + INTERNALS2 = Symbol("Response internals"); + Response3 = class Response3 extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers2(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; } - get errInfo() { - return this.err.errInfo; + get type() { + return this[INTERNALS2].type; } - getOperation() { - return this.err.op; + get url() { + return this[INTERNALS2].url || ""; } - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + get status() { + return this[INTERNALS2].status; } - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; } - } - exports.WriteError = WriteError; - function mergeBatchResults(batch, bulkResult, err, result) { - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; + get redirected() { + return this[INTERNALS2].counter > 0; } - if (result == null) { - return; + get statusText() { + return this[INTERNALS2].statusText; } - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - errInfo: result.errInfo, - op: batch.operations[0] - }; - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; + get headers() { + return this[INTERNALS2].headers; } - if (isInsertBatch(batch) && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; + get highWaterMark() { + return this[INTERNALS2].highWaterMark; } - if (isDeleteBatch(batch) && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; + clone() { + return new Response3(clone3(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); } - let nUpserted = 0; - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - for (let i2 = 0;i2 < result.upserted.length; i2++) { - bulkResult.upserted.push({ - index: result.upserted[i2].index + batch.originalZeroIndex, - _id: result.upserted[i2]._id - }); + static redirect(url3, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); } - } else if (result.upserted) { - nUpserted = 1; - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted + return new Response3(null, { + headers: { + location: new URL(url3).toString() + }, + status }); } - if (isUpdateBatch(batch) && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - if (typeof nModified === "number") { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = 0; - } + static error() { + const response = new Response3(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; } - if (Array.isArray(result.writeErrors)) { - for (let i2 = 0;i2 < result.writeErrors.length; i2++) { - const writeError = { - index: batch.originalIndexes[result.writeErrors[i2].index], - code: result.writeErrors[i2].code, - errmsg: result.writeErrors[i2].errmsg, - errInfo: result.writeErrors[i2].errInfo, - op: batch.operations[result.writeErrors[i2].index] - }; - bulkResult.writeErrors.push(new WriteError(writeError)); + static json(data = undefined, init = {}) { + const body = JSON.stringify(data); + if (body === undefined) { + throw new TypeError("data is not JSON serializable"); } + const headers = new Headers2(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response3(body, { + ...init, + headers + }); } - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + get [Symbol.toStringTag]() { + return "Response"; } + }; + Object.defineProperties(Response3.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } + }); +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; } - async function executeCommands(bulkOperation, options) { - if (bulkOperation.s.batches.length === 0) { - return new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); + const lastOffset = parsedURL.href.length - 1; + const hash2 = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash2.length] === "?" ? "?" : ""; +}; + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/utils/referrer.js +import { isIP as isIP2 } from "node:net"; +function stripURLForUseAsAReferrer(url3, originOnly = false) { + if (url3 == null) { + return "no-referrer"; + } + url3 = new URL(url3); + if (/^(about|blob|data):$/.test(url3.protocol)) { + return "no-referrer"; + } + url3.username = ""; + url3.password = ""; + url3.hash = ""; + if (originOnly) { + url3.pathname = ""; + url3.search = ""; + } + return url3; +} +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url3) { + if (/^(http|ws)s:$/.test(url3.protocol)) { + return true; + } + const hostIp = url3.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = isIP2(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url3.host === "localhost" || url3.host.endsWith(".localhost")) { + return false; + } + if (url3.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url3) { + if (/^about:(blank|srcdoc)$/.test(url3)) { + return true; + } + if (url3.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url3.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url3); +} +function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request.referrer === "no-referrer" || request.referrerPolicy === "") { + return null; + } + const policy2 = request.referrerPolicy; + if (request.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request.url); + switch (policy2) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy2}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy2 = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy2 = token; + } + } + return policy2; +} +var ReferrerPolicy, DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +var init_referrer = __esm(() => { + ReferrerPolicy = new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ]); +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/request.js +import { format as formatUrl } from "node:url"; +import { deprecate as deprecate2 } from "node:util"; +var INTERNALS3, isRequest = (object3) => { + return typeof object3 === "object" && typeof object3[INTERNALS3] === "object"; +}, doBadDataWarn, Request3, getNodeRequestOptions = (request) => { + const { parsedURL } = request[INTERNALS3]; + const headers = new Headers2(request[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request.body === null && /^(post|put)$/i.test(request.method)) { + contentLengthValue = "0"; + } + if (request.body !== null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); } - for (const batch of bulkOperation.s.batches) { - const finalOptions = (0, utils_1.resolveOptions)(bulkOperation, { - ...options, - ordered: bulkOperation.isOrdered - }); - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request.referrerPolicy === "") { + request.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request.referrer && request.referrer !== "no-referrer") { + request[INTERNALS3].referrer = determineRequestsReferrer(request); + } else { + request[INTERNALS3].referrer = "no-referrer"; + } + if (request[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + const search = getSearch(parsedURL); + const options = { + path: parsedURL.pathname + search, + method: request.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request.insecureHTTPParser, + agent + }; + return { + parsedURL, + options + }; +}; +var init_request = __esm(() => { + init_headers2(); + init_body(); + init_is2(); + init_referrer(); + INTERNALS3 = Symbol("Request internals"); + doBadDataWarn = deprecate2(() => {}, ".data is not a valid RequestInit property, use .body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (request)"); + Request3 = class Request3 extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; } - if (bulkOperation.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); } - if (bulkOperation.s.checkKeys === false) { - finalOptions.checkKeys = false; + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); } - if (finalOptions.retryWrites) { - if (isUpdateBatch(batch)) { - finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.multi); - } - if (isDeleteBatch(batch)) { - finalOptions.retryWrites = finalOptions.retryWrites && !batch.operations.some((op) => op.limit === 0); - } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); } - const operation = isInsertBatch(batch) ? new insert_1.InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isUpdateBatch(batch) ? new update_1.UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : isDeleteBatch(batch) ? new delete_1.DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions) : null; - if (operation == null) - throw new error_1.MongoRuntimeError(`Unknown batchType: ${batch.batchType}`); - let thrownError = null; - let result; - try { - result = await (0, execute_operation_1.executeOperation)(bulkOperation.s.collection.client, operation, finalOptions.timeoutContext); - } catch (error91) { - thrownError = error91; + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); } - if (thrownError != null) { - if (thrownError instanceof error_1.MongoWriteConcernError) { - mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); - const writeResult3 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); - throw new MongoBulkWriteError({ - message: thrownError.result.writeConcernError.errmsg, - code: thrownError.result.writeConcernError.code - }, writeResult3); - } else { - throw new MongoBulkWriteError(thrownError, new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)); + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone3(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers2(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); } } - mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result); - const writeResult2 = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); - bulkOperation.handleWriteError(writeResult2); - } - bulkOperation.s.batches.length = 0; - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered); - bulkOperation.handleWriteError(writeResult); - return writeResult; - } - - class MongoBulkWriteError extends error_1.MongoServerError { - constructor(error91, result) { - super(error91); - this.writeErrors = []; - if (error91 instanceof WriteConcernError) - this.err = error91; - else if (!(error91 instanceof Error)) { - this.message = error91.message; - this.code = error91.code; - this.writeErrors = error91.writeErrors ?? []; + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; } - this.result = result; - Object.assign(this, error91); - } - get name() { - return "MongoBulkWriteError"; + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = undefined; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === undefined ? input.follow === undefined ? 20 : input.follow : init.follow; + this.compress = init.compress === undefined ? input.compress === undefined ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + get method() { + return this[INTERNALS3].method; } - get insertedCount() { - return this.result.insertedCount; + get url() { + return formatUrl(this[INTERNALS3].parsedURL); } - get matchedCount() { - return this.result.matchedCount; + get headers() { + return this[INTERNALS3].headers; } - get modifiedCount() { - return this.result.modifiedCount; + get redirect() { + return this[INTERNALS3].redirect; } - get deletedCount() { - return this.result.deletedCount; + get signal() { + return this[INTERNALS3].signal; } - get upsertedCount() { - return this.result.upsertedCount; + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return; } - get insertedIds() { - return this.result.insertedIds; + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; } - get upsertedIds() { - return this.result.upsertedIds; + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); } - } - exports.MongoBulkWriteError = MongoBulkWriteError; - - class FindOperators { - constructor(bulkOperation) { - this.bulkOperation = bulkOperation; + clone() { + return new Request3(this); } - update(updateDocument) { - const currentOp = buildCurrentOp(this.bulkOperation); - return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { - ...currentOp, - multi: true - })); + get [Symbol.toStringTag]() { + return "Request"; + } + }; + Object.defineProperties(Request3.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } + }); +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/errors/abort-error.js +var AbortError4; +var init_abort_error = __esm(() => { + init_base18(); + AbortError4 = class AbortError4 extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } + }; +}); + +// ../../node_modules/.pnpm/node-fetch@3.3.2/node_modules/node-fetch/src/index.js +var exports_src2 = {}; +__export(exports_src2, { + isRedirect: () => isRedirect, + fileFromSync: () => fileFromSync, + fileFrom: () => fileFrom, + default: () => fetch2, + blobFromSync: () => blobFromSync, + blobFrom: () => blobFrom, + Response: () => Response3, + Request: () => Request3, + Headers: () => Headers2, + FormData: () => FormData2, + File: () => file_default, + FetchError: () => FetchError, + Blob: () => fetch_blob_default, + AbortError: () => AbortError4 +}); +import http2 from "node:http"; +import https from "node:https"; +import zlib from "node:zlib"; +import Stream3, { PassThrough as PassThrough2, pipeline as pump3 } from "node:stream"; +import { Buffer as Buffer3 } from "node:buffer"; +async function fetch2(url3, options_) { + return new Promise((resolve2, reject) => { + const request = new Request3(url3, options_); + const { parsedURL, options } = getNodeRequestOptions(request); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url3}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request.url); + const response2 = new Response3(data, { headers: { "Content-Type": data.typeFull } }); + resolve2(response2); + return; } - updateOne(updateDocument) { - if (!(0, utils_1.hasAtomicOperators)(updateDocument, this.bulkOperation.bsonOptions)) { - throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + const send = (parsedURL.protocol === "https:" ? https : http2).request; + const { signal } = request; + let response = null; + const abort = () => { + const error91 = new AbortError4("The operation was aborted."); + reject(error91); + if (request.body && request.body instanceof Stream3.Readable) { + request.body.destroy(error91); } - const currentOp = buildCurrentOp(this.bulkOperation); - return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, updateDocument, { ...currentOp, multi: false })); - } - replaceOne(replacement) { - if ((0, utils_1.hasAtomicOperators)(replacement)) { - throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); + if (!response || !response.body) { + return; } - const currentOp = buildCurrentOp(this.bulkOperation); - return this.bulkOperation.addToOperationsList(exports.BatchType.UPDATE, (0, update_1.makeUpdateStatement)(currentOp.selector, replacement, { ...currentOp, multi: false })); - } - deleteOne() { - const currentOp = buildCurrentOp(this.bulkOperation); - return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 1 })); + response.body.emit("error", error91); + }; + if (signal && signal.aborted) { + abort(); + return; } - delete() { - const currentOp = buildCurrentOp(this.bulkOperation); - return this.bulkOperation.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(currentOp.selector, { ...currentOp, limit: 0 })); + const abortAndFinalize = () => { + abort(); + finalize2(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); } - upsert() { - if (!this.bulkOperation.s.currentOp) { - this.bulkOperation.s.currentOp = {}; + const finalize2 = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); } - this.bulkOperation.s.currentOp.upsert = true; - return this; - } - collation(collation) { - if (!this.bulkOperation.s.currentOp) { - this.bulkOperation.s.currentOp = {}; + }; + request_.on("error", (error91) => { + reject(new FetchError(`request to ${request.url} failed, reason: ${error91.message}`, "system", error91)); + finalize2(); + }); + fixResponseChunkedTransferBadEnding(request_, (error91) => { + if (response && response.body) { + response.body.destroy(error91); } - this.bulkOperation.s.currentOp.collation = collation; - return this; + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error91 = new Error("Premature close"); + error91.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error91); + } + }); + }); } - arrayFilters(arrayFilters) { - if (!this.bulkOperation.s.currentOp) { - this.bulkOperation.s.currentOp = {}; + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location2 = headers.get("Location"); + let locationURL = null; + try { + locationURL = location2 === null ? null : new URL(location2, request.url); + } catch { + if (request.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location2}`, "invalid-redirect")); + finalize2(); + return; + } + } + switch (request.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, "no-redirect")); + finalize2(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, "max-redirect")); + finalize2(); + return; + } + const requestOptions = { + headers: new Headers2(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone3(request), + signal: request.signal, + size: request.size, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy + }; + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request.body && options_.body instanceof Stream3.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize2(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = undefined; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve2(fetch2(new Request3(locationURL, requestOptions))); + finalize2(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request.redirect}' is not a valid value of RequestRedirect`)); + } } - this.bulkOperation.s.currentOp.arrayFilters = arrayFilters; - return this; - } - hint(hint) { - if (!this.bulkOperation.s.currentOp) { - this.bulkOperation.s.currentOp = {}; + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); } - this.bulkOperation.s.currentOp.hint = hint; - return this; - } - } - exports.FindOperators = FindOperators; - - class BulkOperationBase { - constructor(collection, options, isOrdered) { - this.collection = collection; - this.isOrdered = isOrdered; - const topology = (0, utils_1.getTopology)(collection); - options = options == null ? {} : options; - const namespace = collection.s.namespace; - const executed = false; - const currentOp = undefined; - const hello = topology.lastHello(); - const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); - const maxBsonObjectSize = hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16; - const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; - const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000; - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - let finalOptions = Object.assign({}, options); - finalOptions = (0, utils_1.applyRetryableWrites)(finalOptions, collection.db); - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] + let body = pump3(response_, new PassThrough2, (error91) => { + if (error91) { + reject(error91); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request.size, + counter: request.counter, + highWaterMark: request.highWaterMark }; - this.s = { - bulkResult, - currentBatch: undefined, - currentIndex: 0, - currentBatchSize: 0, - currentBatchSizeBytes: 0, - currentInsertBatch: undefined, - currentUpdateBatch: undefined, - currentRemoveBatch: undefined, - batches: [], - writeConcern: write_concern_1.WriteConcern.fromOptions(options), - maxBsonObjectSize, - maxBatchSizeBytes, - maxWriteBatchSize, - maxKeySize, - namespace, - topology, - options: finalOptions, - bsonOptions: (0, bson_1.resolveBSONOptions)(options), - currentOp, - executed, - collection, - err: undefined, - checkKeys: typeof options.checkKeys === "boolean" ? options.checkKeys : false + const codings = headers.get("Content-Encoding"); + if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response3(body, responseOptions); + resolve2(response); + return; + } + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH }; - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; + if (codings === "gzip" || codings === "x-gzip") { + body = pump3(body, zlib.createGunzip(zlibOptions), (error91) => { + if (error91) { + reject(error91); + } + }); + response = new Response3(body, responseOptions); + resolve2(response); + return; } + if (codings === "deflate" || codings === "x-deflate") { + const raw2 = pump3(response_, new PassThrough2, (error91) => { + if (error91) { + reject(error91); + } + }); + raw2.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = pump3(body, zlib.createInflate(), (error91) => { + if (error91) { + reject(error91); + } + }); + } else { + body = pump3(body, zlib.createInflateRaw(), (error91) => { + if (error91) { + reject(error91); + } + }); + } + response = new Response3(body, responseOptions); + resolve2(response); + }); + raw2.once("end", () => { + if (!response) { + response = new Response3(body, responseOptions); + resolve2(response); + } + }); + return; + } + if (codings === "br") { + body = pump3(body, zlib.createBrotliDecompress(), (error91) => { + if (error91) { + reject(error91); + } + }); + response = new Response3(body, responseOptions); + resolve2(response); + return; + } + response = new Response3(body, responseOptions); + resolve2(response); + }); + writeToStream(request_, request).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + const LAST_CHUNK = Buffer3.from(`0\r +\r +`); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error91 = new Error("Premature close"); + error91.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error91); + } + }; + const onData = (buf) => { + properLastChunkReceived = Buffer3.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = Buffer3.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer3.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} +var supportedSchemas; +var init_src2 = __esm(() => { + init_dist11(); + init_body(); + init_response(); + init_headers2(); + init_request(); + init_fetch_error(); + init_abort_error(); + init_is_redirect(); + init_esm_min(); + init_is2(); + init_referrer(); + init_from(); + supportedSchemas = new Set(["data:", "http:", "https:"]); +}); + +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/gaxios.js +var require_gaxios = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + }; + var _a5; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Gaxios = undefined; + var extend_1 = __importDefault(require_extend()); + var https_1 = __require("https"); + var common_js_1 = require_common6(); + var retry_js_1 = require_retry(); + var stream_1 = __require("stream"); + var interceptor_js_1 = require_interceptor(); + var randomUUID2 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID(); + var HTTP_STATUS_NO_CONTENT = 204; + + class Gaxios { + agentCache = new Map; + defaults; + interceptors; + constructor(defaults2) { + this.defaults = defaults2 || {}; + this.interceptors = { + request: new interceptor_js_1.GaxiosInterceptorManager, + response: new interceptor_js_1.GaxiosInterceptorManager + }; + } + fetch(...args) { + const input = args[0]; + const init = args[1]; + let url3 = undefined; + const headers = new Headers; + if (typeof input === "string") { + url3 = new URL(input); + } else if (input instanceof URL) { + url3 = input; + } else if (input && input.url) { + url3 = new URL(input.url); + } + if (input && typeof input === "object" && "headers" in input) { + _a5.mergeHeaders(headers, input.headers); + } + if (init) { + _a5.mergeHeaders(headers, new Headers(init.headers)); + } + if (typeof input === "object" && !(input instanceof URL)) { + return this.request({ ...init, ...input, headers, url: url3 }); + } else { + return this.request({ ...init, headers, url: url3 }); + } + } + async request(opts = {}) { + let prepared = await this.#prepareRequest(opts); + prepared = await this.#applyRequestInterceptors(prepared); + return this.#applyResponseInterceptors(this._request(prepared)); + } + async _defaultAdapter(config3) { + const fetchImpl = config3.fetchImplementation || this.defaults.fetchImplementation || await _a5.#getFetch(); + const preparedOpts = { ...config3 }; + delete preparedOpts.data; + const res = await fetchImpl(config3.url, preparedOpts); + const data = await this.getResponseData(config3, res); + if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) { + Object.defineProperties(res, { + data: { + configurable: true, + writable: true, + enumerable: true, + value: data + } + }); + } + return Object.assign(res, { config: config3, data }); } - insert(document2) { - (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { - forceServerObjectId: this.shouldForceServerObjectId() - }); - return this.addToOperationsList(exports.BatchType.INSERT, document2); - } - find(selector) { - if (!selector) { - throw new error_1.MongoInvalidArgumentError("Bulk find operation must specify a selector"); + async _request(opts) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); + } else { + translatedResponse = await this._defaultAdapter(opts); + } + if (!opts.validateStatus(translatedResponse.status)) { + if (opts.responseType === "stream") { + const response = []; + for await (const chunk of translatedResponse.data) { + response.push(chunk); + } + translatedResponse.data = response.toString(); + } + const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`); + throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo); + } + return translatedResponse; + } catch (e2) { + let err; + if (e2 instanceof common_js_1.GaxiosError) { + err = e2; + } else if (e2 instanceof Error) { + err = new common_js_1.GaxiosError(e2.message, opts, undefined, e2); + } else { + err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, undefined, e2); + } + const { shouldRetry, config: config3 } = await (0, retry_js_1.getRetryConfig)(err); + if (shouldRetry && config3) { + err.config.retryConfig.currentRetryAttempt = config3.retryConfig.currentRetryAttempt; + opts.retryConfig = err.config?.retryConfig; + this.#appendTimeoutToSignal(opts); + return this._request(opts); + } + if (opts.errorRedactor) { + opts.errorRedactor(err); + } + throw err; } - this.s.currentOp = { - selector - }; - return new FindOperators(this); } - raw(op) { - if (op == null || typeof op !== "object") { - throw new error_1.MongoInvalidArgumentError("Operation must be an object with an operation key"); + async getResponseData(opts, res) { + if (res.status === HTTP_STATUS_NO_CONTENT) { + return ""; } - if ("insertOne" in op) { - const forceServerObjectId = this.shouldForceServerObjectId(); - const document2 = op.insertOne && op.insertOne.document == null ? op.insertOne : op.insertOne.document; - (0, utils_1.maybeAddIdToDocuments)(this.collection, document2, { forceServerObjectId }); - return this.addToOperationsList(exports.BatchType.INSERT, document2); + if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) { + throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts })); } - if ("replaceOne" in op || "updateOne" in op || "updateMany" in op) { - if ("replaceOne" in op) { - if ("q" in op.replaceOne) { - throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); - } - const updateStatement = (0, update_1.makeUpdateStatement)(op.replaceOne.filter, op.replaceOne.replacement, { ...op.replaceOne, multi: false }); - if ((0, utils_1.hasAtomicOperators)(updateStatement.u)) { - throw new error_1.MongoInvalidArgumentError("Replacement document must not use atomic operators"); + switch (opts.responseType) { + case "stream": + return res.body; + case "json": { + const data = await res.text(); + try { + return JSON.parse(data); + } catch { + return data; } - return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); } - if ("updateOne" in op) { - if ("q" in op.updateOne) { - throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); - } - const updateStatement = (0, update_1.makeUpdateStatement)(op.updateOne.filter, op.updateOne.update, { - ...op.updateOne, - multi: false - }); - if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { - throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + case "arraybuffer": + return res.arrayBuffer(); + case "blob": + return res.blob(); + case "text": + return res.text(); + default: + return this.getResponseDataFromContentType(res); + } + } + #urlMayUseProxy(url3, noProxy = []) { + const candidate = new URL(url3); + const noProxyList = [...noProxy]; + const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(",") || []; + for (const rule of noProxyEnvList) { + noProxyList.push(rule.trim()); + } + for (const rule of noProxyList) { + if (rule instanceof RegExp) { + if (rule.test(candidate.toString())) { + return false; } - return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); - } - if ("updateMany" in op) { - if ("q" in op.updateMany) { - throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + } else if (rule instanceof URL) { + if (rule.origin === candidate.origin) { + return false; } - const updateStatement = (0, update_1.makeUpdateStatement)(op.updateMany.filter, op.updateMany.update, { - ...op.updateMany, - multi: true - }); - if (!(0, utils_1.hasAtomicOperators)(updateStatement.u, this.bsonOptions)) { - throw new error_1.MongoInvalidArgumentError("Update document requires atomic operators"); + } else if (rule.startsWith("*.") || rule.startsWith(".")) { + const cleanedRule = rule.replace(/^\*\./, "."); + if (candidate.hostname.endsWith(cleanedRule)) { + return false; } - return this.addToOperationsList(exports.BatchType.UPDATE, updateStatement); + } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) { + return false; } } - if ("deleteOne" in op) { - if ("q" in op.deleteOne) { - throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + return true; + } + async#applyRequestInterceptors(options) { + let promiseChain = Promise.resolve(options); + for (const interceptor of this.interceptors.request.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); } - return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })); } - if ("deleteMany" in op) { - if ("q" in op.deleteMany) { - throw new error_1.MongoInvalidArgumentError("Raw operations are not allowed"); + return promiseChain; + } + async#applyResponseInterceptors(response) { + let promiseChain = Promise.resolve(response); + for (const interceptor of this.interceptors.response.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); } - return this.addToOperationsList(exports.BatchType.DELETE, (0, delete_1.makeDeleteStatement)(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })); } - throw new error_1.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany"); + return promiseChain; } - get length() { - return this.s.currentIndex; - } - get bsonOptions() { - return this.s.bsonOptions; - } - get writeConcern() { - return this.s.writeConcern; - } - get batches() { - const batches = [...this.s.batches]; - if (this.isOrdered) { - if (this.s.currentBatch) - batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) - batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) - batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) - batches.push(this.s.currentRemoveBatch); + async#prepareRequest(options) { + const preparedHeaders = new Headers(this.defaults.headers); + _a5.mergeHeaders(preparedHeaders, options.headers); + const opts = (0, extend_1.default)(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error("URL is required."); } - return batches; - } - async execute(options = {}) { - if (this.s.executed) { - throw new error_1.MongoBatchReExecutionError; + if (opts.baseURL) { + opts.url = new URL(opts.url, opts.baseURL); } - const writeConcern = write_concern_1.WriteConcern.fromOptions(options); - if (writeConcern) { - this.s.writeConcern = writeConcern; + opts.url = new URL(opts.url); + if (opts.params) { + if (opts.paramsSerializer) { + let additionalQueryParams = opts.paramsSerializer(opts.params); + if (additionalQueryParams.startsWith("?")) { + additionalQueryParams = additionalQueryParams.slice(1); + } + const prefix = opts.url.toString().includes("?") ? "&" : "?"; + opts.url = opts.url + prefix + additionalQueryParams; + } else { + const url3 = opts.url instanceof URL ? opts.url : new URL(opts.url); + for (const [key, value] of new URLSearchParams(opts.params)) { + url3.searchParams.append(key, value); + } + opts.url = url3; + } } - if (this.isOrdered) { - if (this.s.currentBatch) - this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) - this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) - this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) - this.s.batches.push(this.s.currentRemoveBatch); + if (typeof options.maxContentLength === "number") { + opts.size = options.maxContentLength; } - if (this.s.batches.length === 0) { - throw new error_1.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty"); + if (typeof options.maxRedirects === "number") { + opts.follow = options.maxRedirects; } - this.s.executed = true; - const finalOptions = (0, utils_1.resolveOptions)(this.collection, { ...this.s.options, ...options }); - finalOptions.timeoutContext ??= timeout_1.TimeoutContext.create({ - session: finalOptions.session, - timeoutMS: finalOptions.timeoutMS, - serverSelectionTimeoutMS: this.collection.client.s.options.serverSelectionTimeoutMS, - waitQueueTimeoutMS: this.collection.client.s.options.waitQueueTimeoutMS + const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || ""); + if (opts.multipart?.length) { + const boundary = await randomUUID2(); + preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`); + opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary)); + } else if (shouldDirectlyPassData) { + opts.body = opts.data; + } else if (typeof opts.data === "object") { + if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") { + opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data); + } else { + if (!preparedHeaders.has("content-type")) { + preparedHeaders.set("content-type", "application/json"); + } + opts.body = JSON.stringify(opts.data); + } + } else if (opts.data) { + opts.body = opts.data; + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || "unknown"; + if (!preparedHeaders.has("accept") && opts.responseType === "json") { + preparedHeaders.set("accept", "application/json"); + } + const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy; + if (opts.agent) {} else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) { + const HttpsProxyAgent = await _a5.#getProxyAgent(); + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } else { + opts.agent = new HttpsProxyAgent(proxy, { + cert: opts.cert, + key: opts.key + }); + this.agentCache.set(proxy, opts.agent); + } + } else if (opts.cert && opts.key) { + if (this.agentCache.has(opts.key)) { + opts.agent = this.agentCache.get(opts.key); + } else { + opts.agent = new https_1.Agent({ + cert: opts.cert, + key: opts.key + }); + this.agentCache.set(opts.key, opts.agent); + } + } + if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) { + opts.errorRedactor = common_js_1.defaultErrorRedactor; + } + if (opts.body && !("duplex" in opts)) { + opts.duplex = "half"; + } + this.#appendTimeoutToSignal(opts); + return Object.assign(opts, { + headers: preparedHeaders, + url: opts.url instanceof URL ? opts.url : new URL(opts.url) }); - if (finalOptions.session == null) { - return await this.collection.client.withSession({ explicit: false }, async (session) => { - return await executeCommands(this, { ...finalOptions, session }); - }); + } + #appendTimeoutToSignal(opts) { + if (opts.timeout) { + const timeoutSignal = AbortSignal.timeout(opts.timeout); + if (opts.signal && !opts.signal.aborted) { + opts.signal = AbortSignal.any([opts.signal, timeoutSignal]); + } else { + opts.signal = timeoutSignal; + } } - return await executeCommands(this, { ...finalOptions }); } - handleWriteError(writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - const msg = this.s.bulkResult.writeErrors[0].errmsg ? this.s.bulkResult.writeErrors[0].errmsg : "write operation failed"; - throw new MongoBulkWriteError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }, writeResult); + validateStatus(status) { + return status >= 200 && status < 300; + } + async getResponseDataFromContentType(response) { + let contentType = response.headers.get("Content-Type"); + if (contentType === null) { + return response.text(); } - const writeConcernError = writeResult.getWriteConcernError(); - if (writeConcernError) { - throw new MongoBulkWriteError(writeConcernError, writeResult); + contentType = contentType.toLowerCase(); + if (contentType.includes("application/json")) { + let data = await response.text(); + try { + data = JSON.parse(data); + } catch {} + return data; + } else if (contentType.match(/^text\//)) { + return response.text(); + } else { + return response.blob(); } } - shouldForceServerObjectId() { - return this.s.options.forceServerObjectId === true || this.s.collection.db.options?.forceServerObjectId === true; + async* getMultipartRequest(multipartOptions, boundary) { + const finale = `--${boundary}--`; + for (const currentPart of multipartOptions) { + const partContentType = currentPart.headers.get("Content-Type") || "application/octet-stream"; + const preamble = `--${boundary}\r +Content-Type: ${partContentType}\r +\r +`; + yield preamble; + if (typeof currentPart.content === "string") { + yield currentPart.content; + } else { + yield* currentPart.content; + } + yield `\r +`; + } + yield finale; + } + static #proxyAgent; + static #fetch; + static async#getProxyAgent() { + this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist8()))).HttpsProxyAgent; + return this.#proxyAgent; + } + static async#getFetch() { + const hasWindow = typeof window !== "undefined" && !!window; + this.#fetch ||= hasWindow ? window.fetch : (await Promise.resolve().then(() => (init_src2(), exports_src2))).default; + return this.#fetch; + } + static mergeHeaders(base, ...append2) { + base = base instanceof Headers ? base : new Headers(base); + for (const headers of append2) { + const add = headers instanceof Headers ? headers : new Headers(headers); + add.forEach((value, key) => { + key === "set-cookie" ? base.append(key, value) : base.set(key, value); + }); + } + return base; } } - exports.BulkOperationBase = BulkOperationBase; - function isInsertBatch(batch) { - return batch.batchType === exports.BatchType.INSERT; - } - function isUpdateBatch(batch) { - return batch.batchType === exports.BatchType.UPDATE; - } - function isDeleteBatch(batch) { - return batch.batchType === exports.BatchType.DELETE; - } - function buildCurrentOp(bulkOp) { - let { currentOp } = bulkOp.s; - bulkOp.s.currentOp = undefined; - if (!currentOp) - currentOp = {}; - return currentOp; - } + exports.Gaxios = Gaxios; + _a5 = Gaxios; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/ordered.js -var require_ordered = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OrderedBulkOperation = undefined; - var BSON = require_bson2(); - var error_1 = require_error2(); - var common_1 = require_common5(); - - class OrderedBulkOperation extends common_1.BulkOperationBase { - constructor(collection, options) { - super(collection, options, true); +// ../../node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/index.js +var require_src3 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - addToOperationsList(batchType, document2) { - const bsonSize = BSON.calculateObjectSize(document2, { - checkKeys: false, - ignoreUndefined: false - }); - if (bsonSize >= this.s.maxBsonObjectSize) - throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); - if (this.s.currentBatch == null) { - this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + Object.defineProperty(o2, k22, desc); + } : function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m2[k2]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.instance = exports.Gaxios = exports.GaxiosError = undefined; + exports.request = request; + var gaxios_js_1 = require_gaxios(); + Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function() { + return gaxios_js_1.Gaxios; + } }); + var common_js_1 = require_common6(); + Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function() { + return common_js_1.GaxiosError; + } }); + __exportStar(require_interceptor(), exports); + exports.instance = new gaxios_js_1.Gaxios; + async function request(opts) { + return exports.instance.request(opts); + } +}); + +// ../../node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js +var require_bignumber = __commonJS((exports, module) => { + (function(globalObject) { + var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = "[BigNumber Error] ", tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ", BASE = 100000000000000, LOG_BASE = 14, MAX_SAFE_INTEGER = 9007199254740991, POWS_TEN = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000], SQRT_BASE = 1e7, MAX3 = 1e9; + function clone4(configObject) { + var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: " ", + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber2(v, b2) { + var alphabet, c3, caseChanged, e2, i3, isNum, len, str, x3 = this; + if (!(x3 instanceof BigNumber2)) + return new BigNumber2(v, b2); + if (b2 == null) { + if (v && v._isBigNumber === true) { + x3.s = v.s; + if (!v.c || v.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (v.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = v.e; + x3.c = v.c.slice(); + } + return; + } + if ((isNum = typeof v == "number") && v * 0 == 0) { + x3.s = 1 / v < 0 ? (v = -v, -1) : 1; + if (v === ~~v) { + for (e2 = 0, i3 = v;i3 >= 10; i3 /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x3.c = x3.e = null; + } else { + x3.e = e2; + x3.c = [v]; + } + return; + } + str = String(v); + } else { + if (!isNumeric.test(str = String(v))) + return parseNumeric(x3, str, isNum); + x3.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i3 = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i3; + e2 += +str.slice(i3 + 1); + str = str.substring(0, i3); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck(b2, 2, ALPHABET.length, "Base"); + if (b2 == 10 && alphabetHasNormalDecimalDigits) { + x3 = new BigNumber2(v); + return round(x3, DECIMAL_PLACES + x3.e + 1, ROUNDING_MODE); + } + str = String(v); + if (isNum = typeof v == "number") { + if (v * 0 != 0) + return parseNumeric(x3, str, isNum, b2); + x3.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits + v); + } + } else { + x3.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet = ALPHABET.slice(0, b2); + e2 = i3 = 0; + for (len = str.length;i3 < len; i3++) { + if (alphabet.indexOf(c3 = str.charAt(i3)) < 0) { + if (c3 == ".") { + if (i3 > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i3 = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x3, String(v), isNum, b2); + } + } + isNum = false; + str = convertBase(str, b2, 10, x3.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i3 = 0;str.charCodeAt(i3) === 48; i3++) + ; + for (len = str.length;str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i3, ++len)) { + len -= i3; + if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error(tooManyDigits + x3.s * v); + } + if ((e2 = e2 - i3 - 1) > MAX_EXP) { + x3.c = x3.e = null; + } else if (e2 < MIN_EXP) { + x3.c = [x3.e = 0]; + } else { + x3.e = e2; + x3.c = []; + i3 = (e2 + 1) % LOG_BASE; + if (e2 < 0) + i3 += LOG_BASE; + if (i3 < len) { + if (i3) + x3.c.push(+str.slice(0, i3)); + for (len -= LOG_BASE;i3 < len; ) { + x3.c.push(+str.slice(i3, i3 += LOG_BASE)); + } + i3 = LOG_BASE - (str = str.slice(i3)).length; + } else { + i3 -= len; + } + for (;i3--; str += "0") + ; + x3.c.push(+str); + } + } else { + x3.c = [x3.e = 0]; + } + } + BigNumber2.clone = clone4; + BigNumber2.ROUND_UP = 0; + BigNumber2.ROUND_DOWN = 1; + BigNumber2.ROUND_CEIL = 2; + BigNumber2.ROUND_FLOOR = 3; + BigNumber2.ROUND_HALF_UP = 4; + BigNumber2.ROUND_HALF_DOWN = 5; + BigNumber2.ROUND_HALF_EVEN = 6; + BigNumber2.ROUND_HALF_CEIL = 7; + BigNumber2.ROUND_HALF_FLOOR = 8; + BigNumber2.EUCLID = 9; + BigNumber2.config = BigNumber2.set = function(obj) { + var p2, v; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p2 = "DECIMAL_PLACES")) { + v = obj[p2]; + intCheck(v, 0, MAX3, p2); + DECIMAL_PLACES = v; + } + if (obj.hasOwnProperty(p2 = "ROUNDING_MODE")) { + v = obj[p2]; + intCheck(v, 0, 8, p2); + ROUNDING_MODE = v; + } + if (obj.hasOwnProperty(p2 = "EXPONENTIAL_AT")) { + v = obj[p2]; + if (v && v.pop) { + intCheck(v[0], -MAX3, 0, p2); + intCheck(v[1], 0, MAX3, p2); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX3, MAX3, p2); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + if (obj.hasOwnProperty(p2 = "RANGE")) { + v = obj[p2]; + if (v && v.pop) { + intCheck(v[0], -MAX3, -1, p2); + intCheck(v[1], 1, MAX3, p2); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX3, MAX3, p2); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error(bignumberError + p2 + " cannot be zero: " + v); + } + } + } + if (obj.hasOwnProperty(p2 = "CRYPTO")) { + v = obj[p2]; + if (v === !!v) { + if (v) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error(bignumberError + "crypto unavailable"); + } + } else { + CRYPTO = v; + } + } else { + throw Error(bignumberError + p2 + " not true or false: " + v); + } + } + if (obj.hasOwnProperty(p2 = "MODULO_MODE")) { + v = obj[p2]; + intCheck(v, 0, 9, p2); + MODULO_MODE = v; + } + if (obj.hasOwnProperty(p2 = "POW_PRECISION")) { + v = obj[p2]; + intCheck(v, 0, MAX3, p2); + POW_PRECISION = v; + } + if (obj.hasOwnProperty(p2 = "FORMAT")) { + v = obj[p2]; + if (typeof v == "object") + FORMAT = v; + else + throw Error(bignumberError + p2 + " not an object: " + v); + } + if (obj.hasOwnProperty(p2 = "ALPHABET")) { + v = obj[p2]; + if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; + ALPHABET = v; + } else { + throw Error(bignumberError + p2 + " invalid: " + v); + } + } + } else { + throw Error(bignumberError + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber2.isBigNumber = function(v) { + if (!v || v._isBigNumber !== true) + return false; + if (!BigNumber2.DEBUG) + return true; + var i3, n4, c3 = v.c, e2 = v.e, s2 = v.s; + out: + if ({}.toString.call(c3) == "[object Array]") { + if ((s2 === 1 || s2 === -1) && e2 >= -MAX3 && e2 <= MAX3 && e2 === mathfloor(e2)) { + if (c3[0] === 0) { + if (e2 === 0 && c3.length === 1) + return true; + break out; + } + i3 = (e2 + 1) % LOG_BASE; + if (i3 < 1) + i3 += LOG_BASE; + if (String(c3[0]).length == i3) { + for (i3 = 0;i3 < c3.length; i3++) { + n4 = c3[i3]; + if (n4 < 0 || n4 >= BASE || n4 !== mathfloor(n4)) + break out; + } + if (n4 !== 0) + return true; + } + } + } else if (c3 === null && e2 === null && (s2 === null || s2 === 1 || s2 === -1)) { + return true; + } + throw Error(bignumberError + "Invalid BigNumber: " + v); + }; + BigNumber2.maximum = BigNumber2.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber2.minimum = BigNumber2.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber2.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a, b2, e2, k2, v, i3 = 0, c3 = [], rand = new BigNumber2(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck(dp, 0, MAX3); + k2 = mathceil(dp / LOG_BASE); + if (CRYPTO) { + if (crypto.getRandomValues) { + a = crypto.getRandomValues(new Uint32Array(k2 *= 2)); + for (;i3 < k2; ) { + v = a[i3] * 131072 + (a[i3 + 1] >>> 11); + if (v >= 9000000000000000) { + b2 = crypto.getRandomValues(new Uint32Array(2)); + a[i3] = b2[0]; + a[i3 + 1] = b2[1]; + } else { + c3.push(v % 100000000000000); + i3 += 2; + } + } + i3 = k2 / 2; + } else if (crypto.randomBytes) { + a = crypto.randomBytes(k2 *= 7); + for (;i3 < k2; ) { + v = (a[i3] & 31) * 281474976710656 + a[i3 + 1] * 1099511627776 + a[i3 + 2] * 4294967296 + a[i3 + 3] * 16777216 + (a[i3 + 4] << 16) + (a[i3 + 5] << 8) + a[i3 + 6]; + if (v >= 9000000000000000) { + crypto.randomBytes(7).copy(a, i3); + } else { + c3.push(v % 100000000000000); + i3 += 7; + } + } + i3 = k2 / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + "crypto unavailable"); + } + } + if (!CRYPTO) { + for (;i3 < k2; ) { + v = random53bitInt(); + if (v < 9000000000000000) + c3[i3++] = v % 100000000000000; + } + } + k2 = c3[--i3]; + dp %= LOG_BASE; + if (k2 && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c3[i3] = mathfloor(k2 / v) * v; + } + for (;c3[i3] === 0; c3.pop(), i3--) + ; + if (i3 < 0) { + c3 = [e2 = 0]; + } else { + for (e2 = -1;c3[0] === 0; c3.splice(0, 1), e2 -= LOG_BASE) + ; + for (i3 = 1, v = c3[0];v >= 10; v /= 10, i3++) + ; + if (i3 < LOG_BASE) + e2 -= LOG_BASE - i3; + } + rand.e = e2; + rand.c = c3; + return rand; + }; + }(); + BigNumber2.sum = function() { + var i3 = 1, args = arguments, sum = new BigNumber2(args[0]); + for (;i3 < args.length; ) + sum = sum.plus(args[i3++]); + return sum; + }; + convertBase = function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j2, arr3 = [0], arrL, i3 = 0, len = str.length; + for (;i3 < len; ) { + for (arrL = arr3.length;arrL--; arr3[arrL] *= baseIn) + ; + arr3[0] += alphabet.indexOf(str.charAt(i3++)); + for (j2 = 0;j2 < arr3.length; j2++) { + if (arr3[j2] > baseOut - 1) { + if (arr3[j2 + 1] == null) + arr3[j2 + 1] = 0; + arr3[j2 + 1] += arr3[j2] / baseOut | 0; + arr3[j2] %= baseOut; + } + } + } + return arr3.reverse(); + } + return function(str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e2, k2, r3, x3, xc, y2, i3 = str.indexOf("."), dp = DECIMAL_PLACES, rm2 = ROUNDING_MODE; + if (i3 >= 0) { + k2 = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y2 = new BigNumber2(baseIn); + x3 = y2.pow(str.length - i3); + POW_PRECISION = k2; + y2.c = toBaseOut(toFixedPoint(coeffToString(x3.c), x3.e, "0"), 10, baseOut, decimal); + y2.e = y2.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); + e2 = k2 = xc.length; + for (;xc[--k2] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet.charAt(0); + if (i3 < 0) { + --e2; + } else { + x3.c = xc; + x3.e = e2; + x3.s = sign; + x3 = div(x3, y2, dp, rm2, baseOut); + xc = x3.c; + r3 = x3.r; + e2 = x3.e; + } + d = e2 + dp + 1; + i3 = xc[d]; + k2 = baseOut / 2; + r3 = r3 || d < 0 || xc[d + 1] != null; + r3 = rm2 < 4 ? (i3 != null || r3) && (rm2 == 0 || rm2 == (x3.s < 0 ? 3 : 2)) : i3 > k2 || i3 == k2 && (rm2 == 4 || r3 || rm2 == 6 && xc[d - 1] & 1 || rm2 == (x3.s < 0 ? 8 : 7)); + if (d < 1 || !xc[0]) { + str = r3 ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + xc.length = d; + if (r3) { + for (--baseOut;++xc[--d] > baseOut; ) { + xc[d] = 0; + if (!d) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k2 = xc.length;!xc[--k2]; ) + ; + for (i3 = 0, str = "";i3 <= k2; str += alphabet.charAt(xc[i3++])) + ; + str = toFixedPoint(str, e2, alphabet.charAt(0)); + } + return str; + }; + }(); + div = function() { + function multiply(x3, k2, base) { + var m2, temp, xlo, xhi, carry = 0, i3 = x3.length, klo = k2 % SQRT_BASE, khi = k2 / SQRT_BASE | 0; + for (x3 = x3.slice();i3--; ) { + xlo = x3[i3] % SQRT_BASE; + xhi = x3[i3] / SQRT_BASE | 0; + m2 = khi * xlo + xhi * klo; + temp = klo * xlo + m2 % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base | 0) + (m2 / SQRT_BASE | 0) + khi * xhi; + x3[i3] = temp % base; + } + if (carry) + x3 = [carry].concat(x3); + return x3; + } + function compare3(a, b2, aL, bL) { + var i3, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i3 = cmp = 0;i3 < aL; i3++) { + if (a[i3] != b2[i3]) { + cmp = a[i3] > b2[i3] ? 1 : -1; + break; + } + } + } + return cmp; + } + function subtract(a, b2, aL, base) { + var i3 = 0; + for (;aL--; ) { + a[aL] -= i3; + i3 = a[aL] < b2[aL] ? 1 : 0; + a[aL] = i3 * base + a[aL] - b2[aL]; + } + for (;!a[0] && a.length > 1; a.splice(0, 1)) + ; + } + return function(x3, y2, dp, rm2, base) { + var cmp, e2, i3, more, n4, prod, prodL, q2, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s2 = x3.s == y2.s ? 1 : -1, xc = x3.c, yc = y2.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber2(!x3.s || !y2.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s2 * 0 : s2 / 0); + } + q2 = new BigNumber2(s2); + qc = q2.c = []; + e2 = x3.e - y2.e; + s2 = dp + e2 + 1; + if (!base) { + base = BASE; + e2 = bitFloor(x3.e / LOG_BASE) - bitFloor(y2.e / LOG_BASE); + s2 = s2 / LOG_BASE | 0; + } + for (i3 = 0;yc[i3] == (xc[i3] || 0); i3++) + ; + if (yc[i3] > (xc[i3] || 0)) + e2--; + if (s2 < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i3 = 0; + s2 += 2; + n4 = mathfloor(base / (yc[0] + 1)); + if (n4 > 1) { + yc = multiply(yc, n4, base); + xc = multiply(xc, n4, base); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (;remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) + yc0++; + do { + n4 = 0; + cmp = compare3(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base + (rem[1] || 0); + n4 = mathfloor(rem0 / yc0); + if (n4 > 1) { + if (n4 >= base) + n4 = base - 1; + prod = multiply(yc, n4, base); + prodL = prod.length; + remL = rem.length; + while (compare3(prod, rem, prodL, remL) == 1) { + n4--; + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + if (n4 == 0) { + cmp = n4 = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base); + remL = rem.length; + if (cmp == -1) { + while (compare3(yc, rem, yL, remL) < 1) { + n4++; + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n4++; + rem = [0]; + } + qc[i3++] = n4; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s2--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base == BASE) { + for (i3 = 1, s2 = qc[0];s2 >= 10; s2 /= 10, i3++) + ; + round(q2, dp + (q2.e = i3 + e2 * LOG_BASE - 1) + 1, rm2, more); + } else { + q2.e = e2; + q2.r = +more; + } + return q2; + }; + }(); + function format3(n4, i3, rm2, id) { + var c0, e2, ne2, len, str; + if (rm2 == null) + rm2 = ROUNDING_MODE; + else + intCheck(rm2, 0, 8); + if (!n4.c) + return n4.toString(); + c0 = n4.c[0]; + ne2 = n4.e; + if (i3 == null) { + str = coeffToString(n4.c); + str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str, ne2) : toFixedPoint(str, ne2, "0"); + } else { + n4 = round(new BigNumber2(n4), i3, rm2); + e2 = n4.e; + str = coeffToString(n4.c); + len = str.length; + if (id == 1 || id == 2 && (i3 <= e2 || e2 <= TO_EXP_NEG)) { + for (;len < i3; str += "0", len++) + ; + str = toExponential(str, e2); + } else { + i3 -= ne2 + (id === 2 && e2 > ne2); + str = toFixedPoint(str, e2, "0"); + if (e2 + 1 > len) { + if (--i3 > 0) + for (str += ".";i3--; str += "0") + ; + } else { + i3 += e2 - len; + if (i3 > 0) { + if (e2 + 1 == len) + str += "."; + for (;i3--; str += "0") + ; + } + } + } + } + return n4.s < 0 && c0 ? "-" + str : str; } - const maxKeySize = this.s.maxKeySize; - if (this.s.currentBatchSize + 1 >= this.s.maxWriteBatchSize || this.s.currentBatchSize > 0 && this.s.currentBatchSizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || this.s.currentBatch.batchType !== batchType) { - this.s.batches.push(this.s.currentBatch); - this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); - this.s.currentBatchSize = 0; - this.s.currentBatchSizeBytes = 0; + function maxOrMin(args, n4) { + var k2, y2, i3 = 1, x3 = new BigNumber2(args[0]); + for (;i3 < args.length; i3++) { + y2 = new BigNumber2(args[i3]); + if (!y2.s || (k2 = compare2(x3, y2)) === n4 || k2 === 0 && x3.s === n4) { + x3 = y2; + } + } + return x3; } - if (batchType === common_1.BatchType.INSERT) { - this.s.bulkResult.insertedIds.push({ - index: this.s.currentIndex, - _id: document2._id - }); + function normalise(n4, c3, e2) { + var i3 = 1, j2 = c3.length; + for (;!c3[--j2]; c3.pop()) + ; + for (j2 = c3[0];j2 >= 10; j2 /= 10, i3++) + ; + if ((e2 = i3 + e2 * LOG_BASE - 1) > MAX_EXP) { + n4.c = n4.e = null; + } else if (e2 < MIN_EXP) { + n4.c = [n4.e = 0]; + } else { + n4.e = e2; + n4.c = c3; + } + return n4; } - if (Array.isArray(document2)) { - throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); + parseNumeric = function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x3, str, isNum, b2) { + var base, s2 = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s2)) { + x3.s = isNaN(s2) ? null : s2 < 0 ? -1 : 1; + } else { + if (!isNum) { + s2 = s2.replace(basePrefix, function(m2, p1, p2) { + base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; + return !b2 || b2 == base ? p1 : m2; + }); + if (b2) { + base = b2; + s2 = s2.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s2) + return new BigNumber2(s2, base); + } + if (BigNumber2.DEBUG) { + throw Error(bignumberError + "Not a" + (b2 ? " base " + b2 : "") + " number: " + str); + } + x3.s = null; + } + x3.c = x3.e = null; + }; + }(); + function round(x3, sd, rm2, r3) { + var d, i3, j2, k2, n4, ni, rd, xc = x3.c, pows10 = POWS_TEN; + if (xc) { + out: { + for (d = 1, k2 = xc[0];k2 >= 10; k2 /= 10, d++) + ; + i3 = sd - d; + if (i3 < 0) { + i3 += LOG_BASE; + j2 = sd; + n4 = xc[ni = 0]; + rd = mathfloor(n4 / pows10[d - j2 - 1] % 10); + } else { + ni = mathceil((i3 + 1) / LOG_BASE); + if (ni >= xc.length) { + if (r3) { + for (;xc.length <= ni; xc.push(0)) + ; + n4 = rd = 0; + d = 1; + i3 %= LOG_BASE; + j2 = i3 - LOG_BASE + 1; + } else { + break out; + } + } else { + n4 = k2 = xc[ni]; + for (d = 1;k2 >= 10; k2 /= 10, d++) + ; + i3 %= LOG_BASE; + j2 = i3 - LOG_BASE + d; + rd = j2 < 0 ? 0 : mathfloor(n4 / pows10[d - j2 - 1] % 10); + } + } + r3 = r3 || sd < 0 || xc[ni + 1] != null || (j2 < 0 ? n4 : n4 % pows10[d - j2 - 1]); + r3 = rm2 < 4 ? (rd || r3) && (rm2 == 0 || rm2 == (x3.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm2 == 4 || r3 || rm2 == 6 && (i3 > 0 ? j2 > 0 ? n4 / pows10[d - j2] : 0 : xc[ni - 1]) % 10 & 1 || rm2 == (x3.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r3) { + sd -= x3.e + 1; + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x3.e = -sd || 0; + } else { + xc[0] = x3.e = 0; + } + return x3; + } + if (i3 == 0) { + xc.length = ni; + k2 = 1; + ni--; + } else { + xc.length = ni + 1; + k2 = pows10[LOG_BASE - i3]; + xc[ni] = j2 > 0 ? mathfloor(n4 / pows10[d - j2] % pows10[j2]) * k2 : 0; + } + if (r3) { + for (;; ) { + if (ni == 0) { + for (i3 = 1, j2 = xc[0];j2 >= 10; j2 /= 10, i3++) + ; + j2 = xc[0] += k2; + for (k2 = 1;j2 >= 10; j2 /= 10, k2++) + ; + if (i3 != k2) { + x3.e++; + if (xc[0] == BASE) + xc[0] = 1; + } + break; + } else { + xc[ni] += k2; + if (xc[ni] != BASE) + break; + xc[ni--] = 0; + k2 = 1; + } + } + } + for (i3 = xc.length;xc[--i3] === 0; xc.pop()) + ; + } + if (x3.e > MAX_EXP) { + x3.c = x3.e = null; + } else if (x3.e < MIN_EXP) { + x3.c = [x3.e = 0]; + } + } + return x3; + } + function valueOf(n4) { + var str, e2 = n4.e; + if (e2 === null) + return n4.toString(); + str = coeffToString(n4.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); + return n4.s < 0 ? "-" + str : str; + } + P2.absoluteValue = P2.abs = function() { + var x3 = new BigNumber2(this); + if (x3.s < 0) + x3.s = 1; + return x3; + }; + P2.comparedTo = function(y2, b2) { + return compare2(this, new BigNumber2(y2, b2)); + }; + P2.decimalPlaces = P2.dp = function(dp, rm2) { + var c3, n4, v, x3 = this; + if (dp != null) { + intCheck(dp, 0, MAX3); + if (rm2 == null) + rm2 = ROUNDING_MODE; + else + intCheck(rm2, 0, 8); + return round(new BigNumber2(x3), dp + x3.e + 1, rm2); + } + if (!(c3 = x3.c)) + return null; + n4 = ((v = c3.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + if (v = c3[v]) + for (;v % 10 == 0; v /= 10, n4--) + ; + if (n4 < 0) + n4 = 0; + return n4; + }; + P2.dividedBy = P2.div = function(y2, b2) { + return div(this, new BigNumber2(y2, b2), DECIMAL_PLACES, ROUNDING_MODE); + }; + P2.dividedToIntegerBy = P2.idiv = function(y2, b2) { + return div(this, new BigNumber2(y2, b2), 0, 1); + }; + P2.exponentiatedBy = P2.pow = function(n4, m2) { + var half, isModExp, i3, k2, more, nIsBig, nIsNeg, nIsOdd, y2, x3 = this; + n4 = new BigNumber2(n4); + if (n4.c && !n4.isInteger()) { + throw Error(bignumberError + "Exponent not an integer: " + valueOf(n4)); + } + if (m2 != null) + m2 = new BigNumber2(m2); + nIsBig = n4.e > 14; + if (!x3.c || !x3.c[0] || x3.c[0] == 1 && !x3.e && x3.c.length == 1 || !n4.c || !n4.c[0]) { + y2 = new BigNumber2(Math.pow(+valueOf(x3), nIsBig ? n4.s * (2 - isOdd(n4)) : +valueOf(n4))); + return m2 ? y2.mod(m2) : y2; + } + nIsNeg = n4.s < 0; + if (m2) { + if (m2.c ? !m2.c[0] : !m2.s) + return new BigNumber2(NaN); + isModExp = !nIsNeg && x3.isInteger() && m2.isInteger(); + if (isModExp) + x3 = x3.mod(m2); + } else if (n4.e > 9 && (x3.e > 0 || x3.e < -1 || (x3.e == 0 ? x3.c[0] > 1 || nIsBig && x3.c[1] >= 240000000 : x3.c[0] < 80000000000000 || nIsBig && x3.c[0] <= 99999750000000))) { + k2 = x3.s < 0 && isOdd(n4) ? -0 : 0; + if (x3.e > -1) + k2 = 1 / k2; + return new BigNumber2(nIsNeg ? 1 / k2 : k2); + } else if (POW_PRECISION) { + k2 = mathceil(POW_PRECISION / LOG_BASE + 2); + } + if (nIsBig) { + half = new BigNumber2(0.5); + if (nIsNeg) + n4.s = 1; + nIsOdd = isOdd(n4); + } else { + i3 = Math.abs(+valueOf(n4)); + nIsOdd = i3 % 2; + } + y2 = new BigNumber2(ONE); + for (;; ) { + if (nIsOdd) { + y2 = y2.times(x3); + if (!y2.c) + break; + if (k2) { + if (y2.c.length > k2) + y2.c.length = k2; + } else if (isModExp) { + y2 = y2.mod(m2); + } + } + if (i3) { + i3 = mathfloor(i3 / 2); + if (i3 === 0) + break; + nIsOdd = i3 % 2; + } else { + n4 = n4.times(half); + round(n4, n4.e + 1, 1); + if (n4.e > 14) { + nIsOdd = isOdd(n4); + } else { + i3 = +valueOf(n4); + if (i3 === 0) + break; + nIsOdd = i3 % 2; + } + } + x3 = x3.times(x3); + if (k2) { + if (x3.c && x3.c.length > k2) + x3.c.length = k2; + } else if (isModExp) { + x3 = x3.mod(m2); + } + } + if (isModExp) + return y2; + if (nIsNeg) + y2 = ONE.div(y2); + return m2 ? y2.mod(m2) : k2 ? round(y2, POW_PRECISION, ROUNDING_MODE, more) : y2; + }; + P2.integerValue = function(rm2) { + var n4 = new BigNumber2(this); + if (rm2 == null) + rm2 = ROUNDING_MODE; + else + intCheck(rm2, 0, 8); + return round(n4, n4.e + 1, rm2); + }; + P2.isEqualTo = P2.eq = function(y2, b2) { + return compare2(this, new BigNumber2(y2, b2)) === 0; + }; + P2.isFinite = function() { + return !!this.c; + }; + P2.isGreaterThan = P2.gt = function(y2, b2) { + return compare2(this, new BigNumber2(y2, b2)) > 0; + }; + P2.isGreaterThanOrEqualTo = P2.gte = function(y2, b2) { + return (b2 = compare2(this, new BigNumber2(y2, b2))) === 1 || b2 === 0; + }; + P2.isInteger = function() { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + P2.isLessThan = P2.lt = function(y2, b2) { + return compare2(this, new BigNumber2(y2, b2)) < 0; + }; + P2.isLessThanOrEqualTo = P2.lte = function(y2, b2) { + return (b2 = compare2(this, new BigNumber2(y2, b2))) === -1 || b2 === 0; + }; + P2.isNaN = function() { + return !this.s; + }; + P2.isNegative = function() { + return this.s < 0; + }; + P2.isPositive = function() { + return this.s > 0; + }; + P2.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P2.minus = function(y2, b2) { + var i3, j2, t3, xLTy, x3 = this, a = x3.s; + y2 = new BigNumber2(y2, b2); + b2 = y2.s; + if (!a || !b2) + return new BigNumber2(NaN); + if (a != b2) { + y2.s = -b2; + return x3.plus(y2); + } + var xe = x3.e / LOG_BASE, ye = y2.e / LOG_BASE, xc = x3.c, yc = y2.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y2.s = -b2, y2) : new BigNumber2(yc ? x3 : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y2.s = -b2, y2) : new BigNumber2(xc[0] ? x3 : ROUNDING_MODE == 3 ? -0 : 0); + } + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (xLTy = a < 0) { + a = -a; + t3 = xc; + } else { + ye = xe; + t3 = yc; + } + t3.reverse(); + for (b2 = a;b2--; t3.push(0)) + ; + t3.reverse(); + } else { + j2 = (xLTy = (a = xc.length) < (b2 = yc.length)) ? a : b2; + for (a = b2 = 0;b2 < j2; b2++) { + if (xc[b2] != yc[b2]) { + xLTy = xc[b2] < yc[b2]; + break; + } + } + } + if (xLTy) { + t3 = xc; + xc = yc; + yc = t3; + y2.s = -y2.s; + } + b2 = (j2 = yc.length) - (i3 = xc.length); + if (b2 > 0) + for (;b2--; xc[i3++] = 0) + ; + b2 = BASE - 1; + for (;j2 > a; ) { + if (xc[--j2] < yc[j2]) { + for (i3 = j2;i3 && !xc[--i3]; xc[i3] = b2) + ; + --xc[i3]; + xc[j2] += BASE; + } + xc[j2] -= yc[j2]; + } + for (;xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y2.s = ROUNDING_MODE == 3 ? -1 : 1; + y2.c = [y2.e = 0]; + return y2; + } + return normalise(y2, xc, ye); + }; + P2.modulo = P2.mod = function(y2, b2) { + var q2, s2, x3 = this; + y2 = new BigNumber2(y2, b2); + if (!x3.c || !y2.s || y2.c && !y2.c[0]) { + return new BigNumber2(NaN); + } else if (!y2.c || x3.c && !x3.c[0]) { + return new BigNumber2(x3); + } + if (MODULO_MODE == 9) { + s2 = y2.s; + y2.s = 1; + q2 = div(x3, y2, 0, 3); + y2.s = s2; + q2.s *= s2; + } else { + q2 = div(x3, y2, 0, MODULO_MODE); + } + y2 = x3.minus(q2.times(y2)); + if (!y2.c[0] && MODULO_MODE == 1) + y2.s = x3.s; + return y2; + }; + P2.multipliedBy = P2.times = function(y2, b2) { + var c3, e2, i3, j2, k2, m2, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x3 = this, xc = x3.c, yc = (y2 = new BigNumber2(y2, b2)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x3.s || !y2.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y2.c = y2.e = y2.s = null; + } else { + y2.s *= x3.s; + if (!xc || !yc) { + y2.c = y2.e = null; + } else { + y2.c = [0]; + y2.e = 0; + } + } + return y2; + } + e2 = bitFloor(x3.e / LOG_BASE) + bitFloor(y2.e / LOG_BASE); + y2.s *= x3.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i3 = xcL; + xcL = ycL; + ycL = i3; + } + for (i3 = xcL + ycL, zc = [];i3--; zc.push(0)) + ; + base = BASE; + sqrtBase = SQRT_BASE; + for (i3 = ycL;--i3 >= 0; ) { + c3 = 0; + ylo = yc[i3] % sqrtBase; + yhi = yc[i3] / sqrtBase | 0; + for (k2 = xcL, j2 = i3 + k2;j2 > i3; ) { + xlo = xc[--k2] % sqrtBase; + xhi = xc[k2] / sqrtBase | 0; + m2 = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m2 % sqrtBase * sqrtBase + zc[j2] + c3; + c3 = (xlo / base | 0) + (m2 / sqrtBase | 0) + yhi * xhi; + zc[j2--] = xlo % base; + } + zc[j2] = c3; + } + if (c3) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y2, zc, e2); + }; + P2.negated = function() { + var x3 = new BigNumber2(this); + x3.s = -x3.s || null; + return x3; + }; + P2.plus = function(y2, b2) { + var t3, x3 = this, a = x3.s; + y2 = new BigNumber2(y2, b2); + b2 = y2.s; + if (!a || !b2) + return new BigNumber2(NaN); + if (a != b2) { + y2.s = -b2; + return x3.minus(y2); + } + var xe = x3.e / LOG_BASE, ye = y2.e / LOG_BASE, xc = x3.c, yc = y2.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber2(a / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y2 : new BigNumber2(xc[0] ? x3 : a * 0); + } + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t3 = yc; + } else { + a = -a; + t3 = xc; + } + t3.reverse(); + for (;a--; t3.push(0)) + ; + t3.reverse(); + } + a = xc.length; + b2 = yc.length; + if (a - b2 < 0) { + t3 = yc; + yc = xc; + xc = t3; + b2 = a; + } + for (a = 0;b2; ) { + a = (xc[--b2] = xc[b2] + yc[b2] + a) / BASE | 0; + xc[b2] = BASE === xc[b2] ? 0 : xc[b2] % BASE; + } + if (a) { + xc = [a].concat(xc); + ++ye; + } + return normalise(y2, xc, ye); + }; + P2.precision = P2.sd = function(sd, rm2) { + var c3, n4, v, x3 = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX3); + if (rm2 == null) + rm2 = ROUNDING_MODE; + else + intCheck(rm2, 0, 8); + return round(new BigNumber2(x3), sd, rm2); + } + if (!(c3 = x3.c)) + return null; + v = c3.length - 1; + n4 = v * LOG_BASE + 1; + if (v = c3[v]) { + for (;v % 10 == 0; v /= 10, n4--) + ; + for (v = c3[0];v >= 10; v /= 10, n4++) + ; + } + if (sd && x3.e + 1 > n4) + n4 = x3.e + 1; + return n4; + }; + P2.shiftedBy = function(k2) { + intCheck(k2, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times("1e" + k2); + }; + P2.squareRoot = P2.sqrt = function() { + var m2, n4, r3, rep, t3, x3 = this, c3 = x3.c, s2 = x3.s, e2 = x3.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); + if (s2 !== 1 || !c3 || !c3[0]) { + return new BigNumber2(!s2 || s2 < 0 && (!c3 || c3[0]) ? NaN : c3 ? x3 : 1 / 0); + } + s2 = Math.sqrt(+valueOf(x3)); + if (s2 == 0 || s2 == 1 / 0) { + n4 = coeffToString(c3); + if ((n4.length + e2) % 2 == 0) + n4 += "0"; + s2 = Math.sqrt(+n4); + e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s2 == 1 / 0) { + n4 = "5e" + e2; + } else { + n4 = s2.toExponential(); + n4 = n4.slice(0, n4.indexOf("e") + 1) + e2; + } + r3 = new BigNumber2(n4); + } else { + r3 = new BigNumber2(s2 + ""); + } + if (r3.c[0]) { + e2 = r3.e; + s2 = e2 + dp; + if (s2 < 3) + s2 = 0; + for (;; ) { + t3 = r3; + r3 = half.times(t3.plus(div(x3, t3, dp, 1))); + if (coeffToString(t3.c).slice(0, s2) === (n4 = coeffToString(r3.c)).slice(0, s2)) { + if (r3.e < e2) + --s2; + n4 = n4.slice(s2 - 3, s2 + 1); + if (n4 == "9999" || !rep && n4 == "4999") { + if (!rep) { + round(t3, t3.e + DECIMAL_PLACES + 2, 0); + if (t3.times(t3).eq(x3)) { + r3 = t3; + break; + } + } + dp += 4; + s2 += 4; + rep = 1; + } else { + if (!+n4 || !+n4.slice(1) && n4.charAt(0) == "5") { + round(r3, r3.e + DECIMAL_PLACES + 2, 1); + m2 = !r3.times(r3).eq(x3); + } + break; + } + } + } + } + return round(r3, r3.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m2); + }; + P2.toExponential = function(dp, rm2) { + if (dp != null) { + intCheck(dp, 0, MAX3); + dp++; + } + return format3(this, dp, rm2, 1); + }; + P2.toFixed = function(dp, rm2) { + if (dp != null) { + intCheck(dp, 0, MAX3); + dp = dp + this.e + 1; + } + return format3(this, dp, rm2); + }; + P2.toFormat = function(dp, rm2, format4) { + var str, x3 = this; + if (format4 == null) { + if (dp != null && rm2 && typeof rm2 == "object") { + format4 = rm2; + rm2 = null; + } else if (dp && typeof dp == "object") { + format4 = dp; + dp = rm2 = null; + } else { + format4 = FORMAT; + } + } else if (typeof format4 != "object") { + throw Error(bignumberError + "Argument not an object: " + format4); + } + str = x3.toFixed(dp, rm2); + if (x3.c) { + var i3, arr3 = str.split("."), g1 = +format4.groupSize, g2 = +format4.secondaryGroupSize, groupSeparator = format4.groupSeparator || "", intPart = arr3[0], fractionPart = arr3[1], isNeg = x3.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g2) { + i3 = g1; + g1 = g2; + g2 = i3; + len -= i3; + } + if (g1 > 0 && len > 0) { + i3 = len % g1 || g1; + intPart = intDigits.substr(0, i3); + for (;i3 < len; i3 += g1) + intPart += groupSeparator + intDigits.substr(i3, g1); + if (g2 > 0) + intPart += groupSeparator + intDigits.slice(i3); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format4.decimalSeparator || "") + ((g2 = +format4.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g2 + "}\\B", "g"), "$&" + (format4.fractionGroupSeparator || "")) : fractionPart) : intPart; + } + return (format4.prefix || "") + str + (format4.suffix || ""); + }; + P2.toFraction = function(md) { + var d, d0, d1, d2, e2, exp, n4, n0, n1, q2, r3, s2, x3 = this, xc = x3.c; + if (md != null) { + n4 = new BigNumber2(md); + if (!n4.isInteger() && (n4.c || n4.s !== 1) || n4.lt(ONE)) { + throw Error(bignumberError + "Argument " + (n4.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n4)); + } + } + if (!xc) + return new BigNumber2(x3); + d = new BigNumber2(ONE); + n1 = d0 = new BigNumber2(ONE); + d1 = n0 = new BigNumber2(ONE); + s2 = coeffToString(xc); + e2 = d.e = s2.length - x3.e - 1; + d.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n4.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n4; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n4 = new BigNumber2(s2); + n0.c[0] = 0; + for (;; ) { + q2 = div(n4, d, 0, 1); + d2 = d0.plus(q2.times(d1)); + if (d2.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q2.times(d2 = n1)); + n0 = d2; + d = n4.minus(q2.times(d2 = d)); + n4 = d2; + } + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x3.s; + e2 = e2 * 2; + r3 = div(n1, d1, e2, ROUNDING_MODE).minus(x3).abs().comparedTo(div(n0, d0, e2, ROUNDING_MODE).minus(x3).abs()) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r3; + }; + P2.toNumber = function() { + return +valueOf(this); + }; + P2.toPrecision = function(sd, rm2) { + if (sd != null) + intCheck(sd, 1, MAX3); + return format3(this, sd, rm2, 2); + }; + P2.toString = function(b2) { + var str, n4 = this, s2 = n4.s, e2 = n4.e; + if (e2 === null) { + if (s2) { + str = "Infinity"; + if (s2 < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b2 == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n4.c), e2) : toFixedPoint(coeffToString(n4.c), e2, "0"); + } else if (b2 === 10 && alphabetHasNormalDecimalDigits) { + n4 = round(new BigNumber2(n4), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n4.c), n4.e, "0"); + } else { + intCheck(b2, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint(coeffToString(n4.c), e2, "0"), 10, b2, s2, true); + } + if (s2 < 0 && n4.c[0]) + str = "-" + str; + } + return str; + }; + P2.valueOf = P2.toJSON = function() { + return valueOf(this); + }; + P2._isBigNumber = true; + if (configObject != null) + BigNumber2.set(configObject); + return BigNumber2; + } + function bitFloor(n4) { + var i3 = n4 | 0; + return n4 > 0 || n4 === i3 ? i3 : i3 - 1; + } + function coeffToString(a) { + var s2, z3, i3 = 1, j2 = a.length, r3 = a[0] + ""; + for (;i3 < j2; ) { + s2 = a[i3++] + ""; + z3 = LOG_BASE - s2.length; + for (;z3--; s2 = "0" + s2) + ; + r3 += s2; + } + for (j2 = r3.length;r3.charCodeAt(--j2) === 48; ) + ; + return r3.slice(0, j2 + 1 || 1); + } + function compare2(x3, y2) { + var a, b2, xc = x3.c, yc = y2.c, i3 = x3.s, j2 = y2.s, k2 = x3.e, l = y2.e; + if (!i3 || !j2) + return null; + a = xc && !xc[0]; + b2 = yc && !yc[0]; + if (a || b2) + return a ? b2 ? 0 : -j2 : i3; + if (i3 != j2) + return i3; + a = i3 < 0; + b2 = k2 == l; + if (!xc || !yc) + return b2 ? 0 : !xc ^ a ? 1 : -1; + if (!b2) + return k2 > l ^ a ? 1 : -1; + j2 = (k2 = xc.length) < (l = yc.length) ? k2 : l; + for (i3 = 0;i3 < j2; i3++) + if (xc[i3] != yc[i3]) + return xc[i3] > yc[i3] ^ a ? 1 : -1; + return k2 == l ? 0 : k2 > l ^ a ? 1 : -1; + } + function intCheck(n4, min, max, name) { + if (n4 < min || n4 > max || n4 !== mathfloor(n4)) { + throw Error(bignumberError + (name || "Argument") + (typeof n4 == "number" ? n4 < min || n4 > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n4)); + } + } + function isOdd(n4) { + var k2 = n4.c.length - 1; + return bitFloor(n4.e / LOG_BASE) == k2 && n4.c[k2] % 2 != 0; + } + function toExponential(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint(str, e2, z3) { + var len, zs; + if (e2 < 0) { + for (zs = z3 + ".";++e2; zs += z3) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z3, e2 -= len;--e2; zs += z3) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } + } + return str; + } + BigNumber = clone4(); + BigNumber["default"] = BigNumber.BigNumber = BigNumber; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber; + }); + } else if (typeof module != "undefined" && module.exports) { + module.exports = BigNumber; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; + } + globalObject.BigNumber = BigNumber; + } + })(exports); +}); + +// ../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js +var require_stringify4 = __commonJS((exports, module) => { + var BigNumber = require_bignumber(); + var JSON2 = exports; + (function() { + function f5(n4) { + return n4 < 10 ? "0" + n4 : n4; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta3 = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': "\\\"", + "\\": "\\\\" + }, rep; + function quote(string7) { + escapable.lastIndex = 0; + return escapable.test(string7) ? '"' + string7.replace(escapable, function(a) { + var c3 = meta3[a]; + return typeof c3 === "string" ? c3 : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string7 + '"'; + } + function str(key, holder) { + var i3, k2, v, length, mind = gap, partial3, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value)); + if (value && typeof value === "object" && typeof value.toJSON === "function") { + value = value.toJSON(key); + } + if (typeof rep === "function") { + value = rep.call(holder, key, value); + } + switch (typeof value) { + case "string": + if (isBigNumber) { + return value; + } else { + return quote(value); + } + case "number": + return isFinite(value) ? String(value) : "null"; + case "boolean": + case "null": + case "bigint": + return String(value); + case "object": + if (!value) { + return "null"; + } + gap += indent; + partial3 = []; + if (Object.prototype.toString.apply(value) === "[object Array]") { + length = value.length; + for (i3 = 0;i3 < length; i3 += 1) { + partial3[i3] = str(i3, value) || "null"; + } + v = partial3.length === 0 ? "[]" : gap ? `[ +` + gap + partial3.join(`, +` + gap) + ` +` + mind + "]" : "[" + partial3.join(",") + "]"; + gap = mind; + return v; + } + if (rep && typeof rep === "object") { + length = rep.length; + for (i3 = 0;i3 < length; i3 += 1) { + if (typeof rep[i3] === "string") { + k2 = rep[i3]; + v = str(k2, value); + if (v) { + partial3.push(quote(k2) + (gap ? ": " : ":") + v); + } + } + } + } else { + Object.keys(value).forEach(function(k3) { + var v2 = str(k3, value); + if (v2) { + partial3.push(quote(k3) + (gap ? ": " : ":") + v2); + } + }); + } + v = partial3.length === 0 ? "{}" : gap ? `{ +` + gap + partial3.join(`, +` + gap) + ` +` + mind + "}" : "{" + partial3.join(",") + "}"; + gap = mind; + return v; } - this.s.currentBatch.originalIndexes.push(this.s.currentIndex); - this.s.currentBatch.operations.push(document2); - this.s.currentBatchSize += 1; - this.s.currentBatchSizeBytes += maxKeySize + bsonSize; - this.s.currentIndex += 1; - return this; } - } - exports.OrderedBulkOperation = OrderedBulkOperation; + if (typeof JSON2.stringify !== "function") { + JSON2.stringify = function(value, replacer, space) { + var i3; + gap = ""; + indent = ""; + if (typeof space === "number") { + for (i3 = 0;i3 < space; i3 += 1) { + indent += " "; + } + } else if (typeof space === "string") { + indent = space; + } + rep = replacer; + if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { + throw new Error("JSON.stringify"); + } + return str("", { "": value }); + }; + } + })(); }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/bulk/unordered.js -var require_unordered = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.UnorderedBulkOperation = undefined; - var BSON = require_bson2(); - var error_1 = require_error2(); - var common_1 = require_common5(); - - class UnorderedBulkOperation extends common_1.BulkOperationBase { - constructor(collection, options) { - super(collection, options, false); - } - handleWriteError(writeResult) { - if (this.s.batches.length) { - return; +// ../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js +var require_parse4 = __commonJS((exports, module) => { + var BigNumber = null; + var suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; + var suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + var json_parse = function(options) { + var _options = { + strict: false, + storeAsString: false, + alwaysParseAsBig: false, + useNativeBigInt: false, + protoAction: "error", + constructorAction: "error" + }; + if (options !== undefined && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; + if (typeof options.constructorAction !== "undefined") { + if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { + _options.constructorAction = options.constructorAction; + } else { + throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`); + } + } + if (typeof options.protoAction !== "undefined") { + if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { + _options.protoAction = options.protoAction; + } else { + throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`); + } } - return super.handleWriteError(writeResult); } - addToOperationsList(batchType, document2) { - const bsonSize = BSON.calculateObjectSize(document2, { - checkKeys: false, - ignoreUndefined: false - }); - if (bsonSize >= this.s.maxBsonObjectSize) { - throw new error_1.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`); + var at, ch, escapee = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: ` +`, + r: "\r", + t: "\t" + }, text, error91 = function(m2) { + throw { + name: "SyntaxError", + message: m2, + at, + text + }; + }, next = function(c3) { + if (c3 && c3 !== ch) { + error91("Expected '" + c3 + "' instead of '" + ch + "'"); + } + ch = text.charAt(at); + at += 1; + return ch; + }, number7 = function() { + var number8, string8 = ""; + if (ch === "-") { + string8 = "-"; + next("-"); + } + while (ch >= "0" && ch <= "9") { + string8 += ch; + next(); + } + if (ch === ".") { + string8 += "."; + while (next() && ch >= "0" && ch <= "9") { + string8 += ch; + } + } + if (ch === "e" || ch === "E") { + string8 += ch; + next(); + if (ch === "-" || ch === "+") { + string8 += ch; + next(); + } + while (ch >= "0" && ch <= "9") { + string8 += ch; + next(); + } } - this.s.currentBatch = undefined; - if (batchType === common_1.BatchType.INSERT) { - this.s.currentBatch = this.s.currentInsertBatch; - } else if (batchType === common_1.BatchType.UPDATE) { - this.s.currentBatch = this.s.currentUpdateBatch; - } else if (batchType === common_1.BatchType.DELETE) { - this.s.currentBatch = this.s.currentRemoveBatch; + number8 = +string8; + if (!isFinite(number8)) { + error91("Bad number"); + } else { + if (BigNumber == null) + BigNumber = require_bignumber(); + if (string8.length > 15) + return _options.storeAsString ? string8 : _options.useNativeBigInt ? BigInt(string8) : new BigNumber(string8); + else + return !_options.alwaysParseAsBig ? number8 : _options.useNativeBigInt ? BigInt(number8) : new BigNumber(number8); } - const maxKeySize = this.s.maxKeySize; - if (this.s.currentBatch == null) { - this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + }, string7 = function() { + var hex3, i3, string8 = "", uffff; + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) + string8 += text.substring(startAt, at - 1); + next(); + return string8; + } + if (ch === "\\") { + if (at - 1 > startAt) + string8 += text.substring(startAt, at - 1); + next(); + if (ch === "u") { + uffff = 0; + for (i3 = 0;i3 < 4; i3 += 1) { + hex3 = parseInt(next(), 16); + if (!isFinite(hex3)) { + break; + } + uffff = uffff * 16 + hex3; + } + string8 += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === "string") { + string8 += escapee[ch]; + } else { + break; + } + startAt = at; + } + } } - if (this.s.currentBatch.size + 1 >= this.s.maxWriteBatchSize || this.s.currentBatch.size > 0 && this.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= this.s.maxBatchSizeBytes || this.s.currentBatch.batchType !== batchType) { - this.s.batches.push(this.s.currentBatch); - this.s.currentBatch = new common_1.Batch(batchType, this.s.currentIndex); + error91("Bad string"); + }, white = function() { + while (ch && ch <= " ") { + next(); } - if (Array.isArray(document2)) { - throw new error_1.MongoInvalidArgumentError("Operation passed in cannot be an Array"); + }, word = function() { + switch (ch) { + case "t": + next("t"); + next("r"); + next("u"); + next("e"); + return true; + case "f": + next("f"); + next("a"); + next("l"); + next("s"); + next("e"); + return false; + case "n": + next("n"); + next("u"); + next("l"); + next("l"); + return null; } - this.s.currentBatch.operations.push(document2); - this.s.currentBatch.originalIndexes.push(this.s.currentIndex); - this.s.currentIndex = this.s.currentIndex + 1; - if (batchType === common_1.BatchType.INSERT) { - this.s.currentInsertBatch = this.s.currentBatch; - this.s.bulkResult.insertedIds.push({ - index: this.s.bulkResult.insertedIds.length, - _id: document2._id - }); - } else if (batchType === common_1.BatchType.UPDATE) { - this.s.currentUpdateBatch = this.s.currentBatch; - } else if (batchType === common_1.BatchType.DELETE) { - this.s.currentRemoveBatch = this.s.currentBatch; + error91("Unexpected '" + ch + "'"); + }, value, array3 = function() { + var array4 = []; + if (ch === "[") { + next("["); + white(); + if (ch === "]") { + next("]"); + return array4; + } + while (ch) { + array4.push(value()); + white(); + if (ch === "]") { + next("]"); + return array4; + } + next(","); + white(); + } + } + error91("Bad array"); + }, object3 = function() { + var key, object4 = Object.create(null); + if (ch === "{") { + next("{"); + white(); + if (ch === "}") { + next("}"); + return object4; + } + while (ch) { + key = string7(); + white(); + next(":"); + if (_options.strict === true && Object.hasOwnProperty.call(object4, key)) { + error91('Duplicate key "' + key + '"'); + } + if (suspectProtoRx.test(key) === true) { + if (_options.protoAction === "error") { + error91("Object contains forbidden prototype property"); + } else if (_options.protoAction === "ignore") { + value(); + } else { + object4[key] = value(); + } + } else if (suspectConstructorRx.test(key) === true) { + if (_options.constructorAction === "error") { + error91("Object contains forbidden constructor property"); + } else if (_options.constructorAction === "ignore") { + value(); + } else { + object4[key] = value(); + } + } else { + object4[key] = value(); + } + white(); + if (ch === "}") { + next("}"); + return object4; + } + next(","); + white(); + } } - this.s.currentBatch.size += 1; - this.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - return this; - } - } - exports.UnorderedBulkOperation = UnorderedBulkOperation; + error91("Bad object"); + }; + value = function() { + white(); + switch (ch) { + case "{": + return object3(); + case "[": + return array3(); + case '"': + return string7(); + case "-": + return number7(); + default: + return ch >= "0" && ch <= "9" ? number7() : word(); + } + }; + return function(source, reviver2) { + var result; + text = source + ""; + at = 0; + ch = " "; + result = value(); + white(); + if (ch) { + error91("Syntax error"); + } + return typeof reviver2 === "function" ? function walk(holder, key) { + var k2, v, value2 = holder[key]; + if (value2 && typeof value2 === "object") { + Object.keys(value2).forEach(function(k3) { + v = walk(value2, k3); + if (v !== undefined) { + value2[k3] = v; + } else { + delete value2[k3]; + } + }); + } + return reviver2.call(holder, key, value2); + }({ "": result }, "") : result; + }; + }; + module.exports = json_parse; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/mongo_logger.js -var require_mongo_logger = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MongoLogger = exports.MongoLoggableComponent = exports.SEVERITY_LEVEL_MAP = exports.DEFAULT_MAX_DOCUMENT_LENGTH = exports.SeverityLevel = undefined; - exports.parseSeverityFromString = parseSeverityFromString; - exports.createStdioLogger = createStdioLogger; - exports.stringifyWithMaxLen = stringifyWithMaxLen; - exports.defaultLogTransform = defaultLogTransform; - var util_1 = __require("util"); - var bson_1 = require_bson2(); - var constants_1 = require_constants6(); - var utils_1 = require_utils5(); - exports.SeverityLevel = Object.freeze({ - EMERGENCY: "emergency", - ALERT: "alert", - CRITICAL: "critical", - ERROR: "error", - WARNING: "warn", - NOTICE: "notice", - INFORMATIONAL: "info", - DEBUG: "debug", - TRACE: "trace", - OFF: "off" - }); - exports.DEFAULT_MAX_DOCUMENT_LENGTH = 1000; +// ../../node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js +var require_json_bigint = __commonJS((exports, module) => { + var json_stringify = require_stringify4().stringify; + var json_parse = require_parse4(); + module.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + }; + }; + module.exports.parse = json_parse(); + module.exports.stringify = json_stringify; +}); - class SeverityLevelMap extends Map { - constructor(entries) { - const newEntries = []; - for (const [level, value] of entries) { - newEntries.push([value, level]); - } - newEntries.push(...entries); - super(newEntries); - } - getNumericSeverityLevel(severity) { - return this.get(severity); - } - getSeverityLevelName(level) { - return this.get(level); +// ../../node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/gcp-residency.js +var require_gcp_residency = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GCE_LINUX_BIOS_PATHS = undefined; + exports.isGoogleCloudServerless = isGoogleCloudServerless; + exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; + exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; + exports.isGoogleComputeEngine = isGoogleComputeEngine; + exports.detectGCPResidency = detectGCPResidency; + var fs_1 = __require("fs"); + var os_1 = __require("os"); + exports.GCE_LINUX_BIOS_PATHS = { + BIOS_DATE: "/sys/class/dmi/id/bios_date", + BIOS_VENDOR: "/sys/class/dmi/id/bios_vendor" + }; + var GCE_MAC_ADDRESS_REGEX = /^42:01/; + function isGoogleCloudServerless() { + const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE; + return !!isGFEnvironment; + } + function isGoogleComputeEngineLinux() { + if ((0, os_1.platform)() !== "linux") + return false; + try { + (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); + const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, "utf8"); + return /Google/.test(biosVendor); + } catch { + return false; } } - exports.SEVERITY_LEVEL_MAP = new SeverityLevelMap([ - [exports.SeverityLevel.OFF, -Infinity], - [exports.SeverityLevel.EMERGENCY, 0], - [exports.SeverityLevel.ALERT, 1], - [exports.SeverityLevel.CRITICAL, 2], - [exports.SeverityLevel.ERROR, 3], - [exports.SeverityLevel.WARNING, 4], - [exports.SeverityLevel.NOTICE, 5], - [exports.SeverityLevel.INFORMATIONAL, 6], - [exports.SeverityLevel.DEBUG, 7], - [exports.SeverityLevel.TRACE, 8] - ]); - exports.MongoLoggableComponent = Object.freeze({ - COMMAND: "command", - TOPOLOGY: "topology", - SERVER_SELECTION: "serverSelection", - CONNECTION: "connection", - CLIENT: "client" - }); - function parseSeverityFromString(s) { - const validSeverities = Object.values(exports.SeverityLevel); - const lowerSeverity = s?.toLowerCase(); - if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { - return lowerSeverity; + function isGoogleComputeEngineMACAddress() { + const interfaces = (0, os_1.networkInterfaces)(); + for (const item of Object.values(interfaces)) { + if (!item) + continue; + for (const { mac: mac3 } of item) { + if (GCE_MAC_ADDRESS_REGEX.test(mac3)) { + return true; + } + } } - return null; + return false; } - function createStdioLogger(stream2) { - return { - write: (0, util_1.promisify)((log2, cb) => { - const logLine = (0, util_1.inspect)(log2, { compact: true, breakLength: Infinity }); - stream2.write(`${logLine} -`, "utf-8", cb); - return; - }) - }; + function isGoogleComputeEngine() { + return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); } - function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { - if (typeof mongodbLogPath === "string" && /^stderr$/i.test(mongodbLogPath)) { - return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; - } - if (typeof mongodbLogPath === "string" && /^stdout$/i.test(mongodbLogPath)) { - return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; - } - if (typeof mongodbLogPath === "object" && typeof mongodbLogPath?.write === "function") { - return { mongodbLogPath, mongodbLogPathIsStdErr: false }; + function detectGCPResidency() { + return isGoogleCloudServerless() || isGoogleComputeEngine(); + } +}); + +// ../../node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/colours.js +var require_colours = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Colours = undefined; + + class Colours { + static isEnabled(stream2) { + return stream2 && stream2.isTTY && (typeof stream2.getColorDepth === "function" ? stream2.getColorDepth() > 2 : true); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process === null || process === undefined ? undefined : process.stderr); + if (!this.enabled) { + Colours.reset = ""; + Colours.bright = ""; + Colours.dim = ""; + Colours.red = ""; + Colours.green = ""; + Colours.yellow = ""; + Colours.blue = ""; + Colours.magenta = ""; + Colours.cyan = ""; + Colours.white = ""; + Colours.grey = ""; + } else { + Colours.reset = "\x1B[0m"; + Colours.bright = "\x1B[1m"; + Colours.dim = "\x1B[2m"; + Colours.red = "\x1B[31m"; + Colours.green = "\x1B[32m"; + Colours.yellow = "\x1B[33m"; + Colours.blue = "\x1B[34m"; + Colours.magenta = "\x1B[35m"; + Colours.cyan = "\x1B[36m"; + Colours.white = "\x1B[37m"; + Colours.grey = "\x1B[90m"; + } + } + } + exports.Colours = Colours; + Colours.enabled = false; + Colours.reset = ""; + Colours.bright = ""; + Colours.dim = ""; + Colours.red = ""; + Colours.green = ""; + Colours.yellow = ""; + Colours.blue = ""; + Colours.magenta = ""; + Colours.cyan = ""; + Colours.white = ""; + Colours.grey = ""; + Colours.refresh(); +}); + +// ../../node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/logging-utils.js +var require_logging_utils = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - if (MONGODB_LOG_PATH && /^stderr$/i.test(MONGODB_LOG_PATH)) { - return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; + Object.defineProperty(o2, k22, desc); + } : function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m2[k2]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { + Object.defineProperty(o2, "default", { enumerable: true, value: v }); + } : function(o2, v) { + o2["default"] = v; + }); + var __importStar = exports && exports.__importStar || function() { + var ownKeys = function(o2) { + ownKeys = Object.getOwnPropertyNames || function(o3) { + var ar = []; + for (var k2 in o3) + if (Object.prototype.hasOwnProperty.call(o3, k2)) + ar[ar.length] = k2; + return ar; + }; + return ownKeys(o2); + }; + return function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i3 = 0;i3 < k2.length; i3++) + if (k2[i3] !== "default") + __createBinding(result, mod, k2[i3]); + } + __setModuleDefault(result, mod); + return result; + }; + }(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = undefined; + exports.getNodeBackend = getNodeBackend; + exports.getDebugBackend = getDebugBackend; + exports.getStructuredBackend = getStructuredBackend; + exports.setBackend = setBackend; + exports.log = log2; + var events_1 = __require("events"); + var process3 = __importStar(__require("process")); + var util5 = __importStar(__require("util")); + var colours_1 = require_colours(); + var LogSeverity; + (function(LogSeverity2) { + LogSeverity2["DEFAULT"] = "DEFAULT"; + LogSeverity2["DEBUG"] = "DEBUG"; + LogSeverity2["INFO"] = "INFO"; + LogSeverity2["WARNING"] = "WARNING"; + LogSeverity2["ERROR"] = "ERROR"; + })(LogSeverity || (exports.LogSeverity = LogSeverity = {})); + + class AdhocDebugLogger extends events_1.EventEmitter { + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + instance: this, + on: (event, listener) => this.on(event, listener) + }); + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace2) => log2(namespace2, this.func); + } + invoke(fields, ...args) { + if (this.upstream) { + try { + this.upstream(fields, ...args); + } catch (e2) {} + } + try { + this.emit("log", fields, args); + } catch (e2) {} } - if (MONGODB_LOG_PATH && /^stdout$/i.test(MONGODB_LOG_PATH)) { - return { mongodbLogPath: createStdioLogger(process.stdout), mongodbLogPathIsStdErr: false }; + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); } - return { mongodbLogPath: createStdioLogger(process.stderr), mongodbLogPathIsStdErr: true }; - } - function resolveSeverityConfiguration(clientOption, environmentOption, defaultSeverity) { - return parseSeverityFromString(clientOption) ?? parseSeverityFromString(environmentOption) ?? defaultSeverity; } - function compareSeverity(s0, s1) { - const s0Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s0); - const s1Num = exports.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(s1); - return s0Num < s1Num ? -1 : s0Num > s1Num ? 1 : 0; - } - function stringifyWithMaxLen(value, maxDocumentLength, options = {}) { - let strToTruncate = ""; - let currentLength = 0; - const maxDocumentLengthEnsurer = function maxDocumentLengthEnsurer2(key, value2) { - if (currentLength >= maxDocumentLength) { - return; - } - if (key === "") { - currentLength += 1; - return value2; - } - currentLength += key.length + 4; - if (value2 == null) - return value2; - switch (typeof value2) { - case "string": - currentLength += value2.length + 2; - break; - case "number": - case "bigint": - currentLength += String(value2).length; - break; - case "boolean": - currentLength += value2 ? 4 : 5; - break; - case "object": - if ((0, utils_1.isUint8Array)(value2)) { - currentLength += 22 + value2.byteLength + value2.byteLength * 0.33 + 18 | 0; - } else if ("_bsontype" in value2) { - const v = value2; - switch (v._bsontype) { - case "Int32": - currentLength += String(v.value).length; - break; - case "Double": - currentLength += (v.value | 0) === v.value ? String(v.value).length + 2 : String(v.value).length; - break; - case "Long": - currentLength += v.toString().length; - break; - case "ObjectId": - currentLength += 35; - break; - case "MaxKey": - case "MinKey": - currentLength += 13; - break; - case "Binary": - currentLength += 22 + value2.position + value2.position * 0.33 + 18 | 0; - break; - case "Timestamp": - currentLength += 19 + String(v.t).length + 5 + String(v.i).length + 2; - break; - case "Code": - if (v.scope == null) { - currentLength += v.code.length + 10 + 2; - } else { - currentLength += v.code.length + 10 + 11; - } - break; - case "BSONRegExp": - currentLength += 34 + v.pattern.length + 13 + v.options.length + 3; - break; - } - } + exports.AdhocDebugLogger = AdhocDebugLogger; + exports.placeholder = new AdhocDebugLogger("", () => {}).func; + + class DebugLogBackendBase { + constructor() { + var _a5; + this.cached = new Map; + this.filters = []; + this.filtersSet = false; + let nodeFlag = (_a5 = process3.env[exports.env.nodeEnables]) !== null && _a5 !== undefined ? _a5 : "*"; + if (nodeFlag === "all") { + nodeFlag = "*"; } - return value2; - }; - if (typeof value === "string") { - strToTruncate = value; - } else if (typeof value === "function") { - strToTruncate = value.name; - } else { + this.filters = nodeFlag.split(","); + } + log(namespace, fields, ...args) { try { - if (maxDocumentLength !== 0) { - strToTruncate = bson_1.EJSON.stringify(value, maxDocumentLengthEnsurer, 0, options); - } else { - strToTruncate = bson_1.EJSON.stringify(value, options); + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; } - } catch (e) { - strToTruncate = `Extended JSON serialization failed with: ${e.message}`; - } - } - if (maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength && strToTruncate.charCodeAt(maxDocumentLength - 1) !== strToTruncate.codePointAt(maxDocumentLength - 1)) { - maxDocumentLength--; - if (maxDocumentLength === 0) { - return ""; + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); + } + logger(fields, ...args); + } catch (e2) { + console.error(e2); } } - return maxDocumentLength !== 0 && strToTruncate.length > maxDocumentLength ? `${strToTruncate.slice(0, maxDocumentLength)}...` : strToTruncate; - } - function isLogConvertible(obj) { - const objAsLogConvertible = obj; - return objAsLogConvertible.toLog !== undefined && typeof objAsLogConvertible.toLog === "function"; - } - function attachServerSelectionFields(log2, serverSelectionEvent, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { - const { selector, operation, topologyDescription, message } = serverSelectionEvent; - log2.selector = stringifyWithMaxLen(selector, maxDocumentLength); - log2.operation = operation; - log2.topologyDescription = stringifyWithMaxLen(topologyDescription, maxDocumentLength); - log2.message = message; - return log2; - } - function attachCommandFields(log2, commandEvent) { - log2.commandName = commandEvent.commandName; - log2.requestId = commandEvent.requestId; - log2.driverConnectionId = commandEvent.connectionId; - const { host, port } = utils_1.HostAddress.fromString(commandEvent.address).toHostPort(); - log2.serverHost = host; - log2.serverPort = port; - if (commandEvent?.serviceId) { - log2.serviceId = commandEvent.serviceId.toHexString(); - } - log2.databaseName = commandEvent.databaseName; - log2.serverConnectionId = commandEvent.serverConnectionId; - return log2; - } - function attachConnectionFields(log2, event) { - const { host, port } = utils_1.HostAddress.fromString(event.address).toHostPort(); - log2.serverHost = host; - log2.serverPort = port; - return log2; - } - function attachSDAMFields(log2, sdamEvent) { - log2.topologyId = sdamEvent.topologyId; - return log2; - } - function attachServerHeartbeatFields(log2, serverHeartbeatEvent) { - const { awaited, connectionId } = serverHeartbeatEvent; - log2.awaited = awaited; - log2.driverConnectionId = serverHeartbeatEvent.connectionId; - const { host, port } = utils_1.HostAddress.fromString(connectionId).toHostPort(); - log2.serverHost = host; - log2.serverPort = port; - return log2; } - function defaultLogTransform(logObject, maxDocumentLength = exports.DEFAULT_MAX_DOCUMENT_LENGTH) { - let log2 = Object.create(null); - switch (logObject.name) { - case constants_1.SERVER_SELECTION_STARTED: - log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); - return log2; - case constants_1.SERVER_SELECTION_FAILED: - log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); - log2.failure = logObject.failure?.message; - return log2; - case constants_1.SERVER_SELECTION_SUCCEEDED: - log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); - log2.serverHost = logObject.serverHost; - log2.serverPort = logObject.serverPort; - return log2; - case constants_1.WAITING_FOR_SUITABLE_SERVER: - log2 = attachServerSelectionFields(log2, logObject, maxDocumentLength); - log2.remainingTimeMS = logObject.remainingTimeMS; - return log2; - case constants_1.COMMAND_STARTED: - log2 = attachCommandFields(log2, logObject); - log2.message = "Command started"; - log2.command = stringifyWithMaxLen(logObject.command, maxDocumentLength, { relaxed: true }); - log2.databaseName = logObject.databaseName; - return log2; - case constants_1.COMMAND_SUCCEEDED: - log2 = attachCommandFields(log2, logObject); - log2.message = "Command succeeded"; - log2.durationMS = logObject.duration; - log2.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); - return log2; - case constants_1.COMMAND_FAILED: - log2 = attachCommandFields(log2, logObject); - log2.message = "Command failed"; - log2.durationMS = logObject.duration; - log2.failure = logObject.failure?.message ?? "(redacted)"; - return log2; - case constants_1.CONNECTION_POOL_CREATED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection pool created"; - if (logObject.options) { - const { maxIdleTimeMS, minPoolSize, maxPoolSize, maxConnecting, waitQueueTimeoutMS } = logObject.options; - log2 = { - ...log2, - maxIdleTimeMS, - minPoolSize, - maxPoolSize, - maxConnecting, - waitQueueTimeoutMS - }; - } - return log2; - case constants_1.CONNECTION_POOL_READY: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection pool ready"; - return log2; - case constants_1.CONNECTION_POOL_CLEARED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection pool cleared"; - if (logObject.serviceId?._bsontype === "ObjectId") { - log2.serviceId = logObject.serviceId?.toHexString(); - } - return log2; - case constants_1.CONNECTION_POOL_CLOSED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection pool closed"; - return log2; - case constants_1.CONNECTION_CREATED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection created"; - log2.driverConnectionId = logObject.connectionId; - return log2; - case constants_1.CONNECTION_READY: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection ready"; - log2.driverConnectionId = logObject.connectionId; - log2.durationMS = logObject.durationMS; - return log2; - case constants_1.CONNECTION_CLOSED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection closed"; - log2.driverConnectionId = logObject.connectionId; - switch (logObject.reason) { - case "stale": - log2.reason = "Connection became stale because the pool was cleared"; - break; - case "idle": - log2.reason = "Connection has been available but unused for longer than the configured max idle time"; + exports.DebugLogBackendBase = DebugLogBackendBase; + + class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => {}; + } + return (fields, ...args) => { + var _a5; + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process3.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; break; - case "error": - log2.reason = "An error occurred while using the connection"; - if (logObject.error) { - log2.error = logObject.error; - } + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; break; - case "poolClosed": - log2.reason = "Connection pool was closed"; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; break; default: - log2.reason = `Unknown close reason: ${logObject.reason}`; - } - return log2; - case constants_1.CONNECTION_CHECK_OUT_STARTED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection checkout started"; - return log2; - case constants_1.CONNECTION_CHECK_OUT_FAILED: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection checkout failed"; - switch (logObject.reason) { - case "poolClosed": - log2.reason = "Connection pool was closed"; - break; - case "timeout": - log2.reason = "Wait queue timeout elapsed without a connection becoming available"; - break; - case "connectionError": - log2.reason = "An error occurred while trying to establish a new connection"; - if (logObject.error) { - log2.error = logObject.error; - } + level = (_a5 = fields.severity) !== null && _a5 !== undefined ? _a5 : LogSeverity.DEFAULT; break; - default: - log2.reason = `Unknown close reason: ${logObject.reason}`; - } - log2.durationMS = logObject.durationMS; - return log2; - case constants_1.CONNECTION_CHECKED_OUT: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection checked out"; - log2.driverConnectionId = logObject.connectionId; - log2.durationMS = logObject.durationMS; - return log2; - case constants_1.CONNECTION_CHECKED_IN: - log2 = attachConnectionFields(log2, logObject); - log2.message = "Connection checked in"; - log2.driverConnectionId = logObject.connectionId; - return log2; - case constants_1.SERVER_OPENING: - log2 = attachSDAMFields(log2, logObject); - log2 = attachConnectionFields(log2, logObject); - log2.message = "Starting server monitoring"; - return log2; - case constants_1.SERVER_CLOSED: - log2 = attachSDAMFields(log2, logObject); - log2 = attachConnectionFields(log2, logObject); - log2.message = "Stopped server monitoring"; - return log2; - case constants_1.SERVER_HEARTBEAT_STARTED: - log2 = attachSDAMFields(log2, logObject); - log2 = attachServerHeartbeatFields(log2, logObject); - log2.message = "Server heartbeat started"; - return log2; - case constants_1.SERVER_HEARTBEAT_SUCCEEDED: - log2 = attachSDAMFields(log2, logObject); - log2 = attachServerHeartbeatFields(log2, logObject); - log2.message = "Server heartbeat succeeded"; - log2.durationMS = logObject.duration; - log2.serverConnectionId = logObject.serverConnectionId; - log2.reply = stringifyWithMaxLen(logObject.reply, maxDocumentLength, { relaxed: true }); - return log2; - case constants_1.SERVER_HEARTBEAT_FAILED: - log2 = attachSDAMFields(log2, logObject); - log2 = attachServerHeartbeatFields(log2, logObject); - log2.message = "Server heartbeat failed"; - log2.durationMS = logObject.duration; - log2.failure = logObject.failure?.message; - return log2; - case constants_1.TOPOLOGY_OPENING: - log2 = attachSDAMFields(log2, logObject); - log2.message = "Starting topology monitoring"; - return log2; - case constants_1.TOPOLOGY_CLOSED: - log2 = attachSDAMFields(log2, logObject); - log2.message = "Stopped topology monitoring"; - return log2; - case constants_1.TOPOLOGY_DESCRIPTION_CHANGED: - log2 = attachSDAMFields(log2, logObject); - log2.message = "Topology description changed"; - log2.previousDescription = log2.reply = stringifyWithMaxLen(logObject.previousDescription, maxDocumentLength); - log2.newDescription = log2.reply = stringifyWithMaxLen(logObject.newDescription, maxDocumentLength); - return log2; - default: - for (const [key, value] of Object.entries(logObject)) { - if (value != null) - log2[key] = value; } + const msg = util5.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : ""; + const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : ""; + console.error("%s [%s|%s] %s%s", pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ""); + }; } - return log2; + setFilters() { + const totalFilters = this.filters.join(","); + const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^"); + this.enabledRegexp = new RegExp(`^${regexp}$`, "i"); + } + } + function getNodeBackend() { + return new NodeBackend; } - class MongoLogger { - constructor(options) { - this.pendingLog = null; - this.error = this.log.bind(this, "error"); - this.warn = this.log.bind(this, "warn"); - this.info = this.log.bind(this, "info"); - this.debug = this.log.bind(this, "debug"); - this.trace = this.log.bind(this, "trace"); - this.componentSeverities = options.componentSeverities; - this.maxDocumentLength = options.maxDocumentLength; - this.logDestination = options.logDestination; - this.logDestinationIsStdErr = options.logDestinationIsStdErr; - this.severities = this.createLoggingSeverities(); - } - createLoggingSeverities() { - const severities = Object(); - for (const component of Object.values(exports.MongoLoggableComponent)) { - severities[component] = {}; - for (const severityLevel of Object.values(exports.SeverityLevel)) { - severities[component][severityLevel] = compareSeverity(severityLevel, this.componentSeverities[component]) <= 0; - } - } - return severities; - } - turnOffSeverities() { - for (const component of Object.values(exports.MongoLoggableComponent)) { - this.componentSeverities[component] = exports.SeverityLevel.OFF; - for (const severityLevel of Object.values(exports.SeverityLevel)) { - this.severities[component][severityLevel] = false; - } - } + class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; } - logWriteFailureHandler(error91) { - if (this.logDestinationIsStdErr) { - this.turnOffSeverities(); - this.clearPendingLog(); - return; - } - this.logDestination = createStdioLogger(process.stderr); - this.logDestinationIsStdErr = true; - this.clearPendingLog(); - this.error(exports.MongoLoggableComponent.CLIENT, { - toLog: function() { - return { - message: "User input for mongodbLogPath is now invalid. Logging is halted.", - error: error91.message - }; - } - }); - this.turnOffSeverities(); - this.clearPendingLog(); + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + debugLogger(args[0], ...args.slice(1)); + }; } - clearPendingLog() { - this.pendingLog = null; + setFilters() { + var _a5; + const existingFilters = (_a5 = process3.env["NODE_DEBUG"]) !== null && _a5 !== undefined ? _a5 : ""; + process3.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`; } - willLog(component, severity) { - if (severity === exports.SeverityLevel.OFF) - return false; - return this.severities[component][severity]; + } + function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); + } + + class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a5; + super(); + this.upstream = (_a5 = upstream) !== null && _a5 !== undefined ? _a5 : undefined; } - log(severity, component, message) { - if (!this.willLog(component, severity)) - return; - let logMessage = { t: new Date, c: component, s: severity }; - if (typeof message === "string") { - logMessage.message = message; - } else if (typeof message === "object") { - if (isLogConvertible(message)) { - logMessage = { ...logMessage, ...message.toLog() }; + makeLogger(namespace) { + var _a5; + const debugLogger = (_a5 = this.upstream) === null || _a5 === undefined ? undefined : _a5.makeLogger(namespace); + return (fields, ...args) => { + var _a6; + const severity = (_a6 = fields.severity) !== null && _a6 !== undefined ? _a6 : LogSeverity.INFO; + const json3 = Object.assign({ + severity, + message: util5.format(...args) + }, fields); + const jsonString = JSON.stringify(json3); + if (debugLogger) { + debugLogger(fields, jsonString); } else { - logMessage = { ...logMessage, ...defaultLogTransform(message, this.maxDocumentLength) }; - } - } - if ((0, utils_1.isPromiseLike)(this.pendingLog)) { - this.pendingLog = this.pendingLog.then(() => this.logDestination.write(logMessage)).then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); - return; - } - try { - const logResult = this.logDestination.write(logMessage); - if ((0, utils_1.isPromiseLike)(logResult)) { - this.pendingLog = logResult.then(this.clearPendingLog.bind(this), this.logWriteFailureHandler.bind(this)); + console.log("%s", jsonString); } - } catch (error91) { - this.logWriteFailureHandler(error91); + }; + } + setFilters() { + var _a5; + (_a5 = this.upstream) === null || _a5 === undefined || _a5.setFilters(); + } + } + function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); + } + exports.env = { + nodeEnables: "GOOGLE_SDK_NODE_LOGGING" + }; + var loggerCache = new Map; + var cachedBackend = undefined; + function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); + } + function log2(namespace, parent) { + if (!cachedBackend) { + const enablesFlag = process3.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; } } - static resolveOptions(envOptions, clientOptions) { - const resolvedLogPath = resolveLogPath(envOptions, clientOptions); - const combinedOptions = { - ...envOptions, - ...clientOptions, - mongodbLogPath: resolvedLogPath.mongodbLogPath, - mongodbLogPathIsStdErr: resolvedLogPath.mongodbLogPathIsStdErr - }; - const defaultSeverity = resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.default, combinedOptions.MONGODB_LOG_ALL, exports.SeverityLevel.OFF); - return { - componentSeverities: { - command: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.command, combinedOptions.MONGODB_LOG_COMMAND, defaultSeverity), - topology: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.topology, combinedOptions.MONGODB_LOG_TOPOLOGY, defaultSeverity), - serverSelection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.serverSelection, combinedOptions.MONGODB_LOG_SERVER_SELECTION, defaultSeverity), - connection: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.connection, combinedOptions.MONGODB_LOG_CONNECTION, defaultSeverity), - client: resolveSeverityConfiguration(combinedOptions.mongodbLogComponentSeverities?.client, combinedOptions.MONGODB_LOG_CLIENT, defaultSeverity), - default: defaultSeverity - }, - maxDocumentLength: combinedOptions.mongodbLogMaxDocumentLength ?? (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, - logDestination: combinedOptions.mongodbLogPath, - logDestinationIsStdErr: combinedOptions.mongodbLogPathIsStdErr - }; + if (!namespace) { + return exports.placeholder; } + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; + } + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; + } + if (cachedBackend === null) { + return exports.placeholder; + } else if (cachedBackend === undefined) { + cachedBackend = getNodeBackend(); + } + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + if (cachedBackend === null) { + return; + } else if (cachedBackend === undefined) { + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === undefined || cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; } - exports.MongoLogger = MongoLogger; }); -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/mongo_types.js -var require_mongo_types = __commonJS((exports) => { +// ../../node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/index.js +var require_src4 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; + } + Object.defineProperty(o2, k22, desc); + } : function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m2[k2]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.CancellationToken = exports.TypedEventEmitter = undefined; - var events_1 = __require("events"); - var mongo_logger_1 = require_mongo_logger(); - var utils_1 = require_utils5(); + __exportStar(require_logging_utils(), exports); +}); - class TypedEventEmitter extends events_1.EventEmitter { - emitAndLog(event, ...args) { - this.emit(event, ...args); - if (this.component) - this.mongoLogger?.debug(this.component, args[0]); +// ../../node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/index.js +var require_src5 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k2]; + } }; } - emitAndLogHeartbeat(event, topologyId, serverConnectionId, ...args) { - this.emit(event, ...args); - if (this.component) { - const loggableHeartbeatEvent = { - topologyId, - serverConnectionId: serverConnectionId ?? null, - ...args[0] - }; - this.mongoLogger?.debug(this.component, loggableHeartbeatEvent); + Object.defineProperty(o2, k22, desc); + } : function(o2, m2, k2, k22) { + if (k22 === undefined) + k22 = k2; + o2[k22] = m2[k2]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { + Object.defineProperty(o2, "default", { enumerable: true, value: v }); + } : function(o2, v) { + o2["default"] = v; + }); + var __importStar = exports && exports.__importStar || function() { + var ownKeys = function(o2) { + ownKeys = Object.getOwnPropertyNames || function(o3) { + var ar = []; + for (var k2 in o3) + if (Object.prototype.hasOwnProperty.call(o3, k2)) + ar[ar.length] = k2; + return ar; + }; + return ownKeys(o2); + }; + return function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i3 = 0;i3 < k2.length; i3++) + if (k2[i3] !== "default") + __createBinding(result, mod, k2[i3]); + } + __setModuleDefault(result, mod); + return result; + }; + }(); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) + if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) + __createBinding(exports2, m2, p2); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = undefined; + exports.instance = instance; + exports.project = project; + exports.universe = universe; + exports.bulk = bulk; + exports.isAvailable = isAvailable; + exports.resetIsAvailableCache = resetIsAvailableCache; + exports.getGCPResidency = getGCPResidency; + exports.setGCPResidency = setGCPResidency; + exports.requestTimeout = requestTimeout; + var gaxios_1 = require_src3(); + var jsonBigint = require_json_bigint(); + var gcp_residency_1 = require_gcp_residency(); + var logger = __importStar(require_src4()); + exports.BASE_PATH = "/computeMetadata/v1"; + exports.HOST_ADDRESS = "http://169.254.169.254"; + exports.SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; + exports.HEADER_NAME = "Metadata-Flavor"; + exports.HEADER_VALUE = "Google"; + exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); + var log2 = logger.log("gcp-metadata"); + exports.METADATA_SERVER_DETECTION = Object.freeze({ + "assume-present": "don't try to ping the metadata server, but assume it's present", + none: "don't try to ping the metadata server, but don't try to use it either", + "bios-only": "treat the result of a BIOS probe as canonical (don't fall back to pinging)", + "ping-only": "skip the BIOS probe, and go straight to pinging" + }); + function getBaseUrl(baseUrl) { + if (!baseUrl) { + baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS; + } + if (!/^https?:\/\//.test(baseUrl)) { + baseUrl = `http://${baseUrl}`; + } + return new URL(exports.BASE_PATH, baseUrl).href; + } + function validate9(options) { + Object.keys(options).forEach((key) => { + switch (key) { + case "params": + case "property": + case "headers": + break; + case "qs": + throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); + default: + throw new Error(`'${key}' is not a valid configuration option.`); } + }); + } + async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { + const headers = new Headers(exports.HEADERS); + let metadataKey = ""; + let params = {}; + if (typeof type === "object") { + const metadataAccessor2 = type; + new Headers(metadataAccessor2.headers).forEach((value, key) => headers.set(key, value)); + metadataKey = metadataAccessor2.metadataKey; + params = metadataAccessor2.params || params; + noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries; + fastFail = metadataAccessor2.fastFail || fastFail; + } else { + metadataKey = type; } - emitAndLogCommand(monitorCommands, event, databaseName, connectionEstablished, ...args) { - if (monitorCommands) { - this.emit(event, ...args); - } - if (connectionEstablished) { - const loggableCommandEvent = { - databaseName, - ...args[0] - }; - this.mongoLogger?.debug(mongo_logger_1.MongoLoggableComponent.COMMAND, loggableCommandEvent); + if (typeof options === "string") { + metadataKey += `/${options}`; + } else { + validate9(options); + if (options.property) { + metadataKey += `/${options.property}`; } + new Headers(options.headers).forEach((value, key) => headers.set(key, value)); + params = options.params || params; } - } - exports.TypedEventEmitter = TypedEventEmitter; - - class CancellationToken extends TypedEventEmitter { - constructor(...args) { - super(...args); - this.on("error", utils_1.noop); + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const req = { + url: `${getBaseUrl()}/${metadataKey}`, + headers, + retryConfig: { noResponseRetries }, + params, + responseType: "text", + timeout: requestTimeout() + }; + log2.info("instance request %j", req); + const res = await requestMethod(req); + log2.info("instance metadata is %s", res.data); + const metadataFlavor = res.headers.get(exports.HEADER_NAME); + if (metadataFlavor !== exports.HEADER_VALUE) { + throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`); + } + if (typeof res.data === "string") { + try { + return jsonBigint.parse(res.data); + } catch {} } + return res.data; } - exports.CancellationToken = CancellationToken; -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/get_more.js -var require_get_more = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GetMoreOperation = undefined; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var utils_1 = require_utils5(); - var operation_1 = require_operation(); - - class GetMoreOperation extends operation_1.AbstractOperation { - constructor(ns3, cursorId, server, options) { - super(options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.CursorResponse; - this.options = options; - this.ns = ns3; - this.cursorId = cursorId; - this.server = server; - } - get commandName() { - return "getMore"; - } - buildCommand(connection) { - if (this.cursorId == null || this.cursorId.isZero()) { - throw new error_1.MongoRuntimeError("Unable to iterate cursor with no id"); + async function fastFailMetadataRequest(options) { + const secondaryOptions = { + ...options, + url: options.url?.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)) + }; + const r1 = (0, gaxios_1.request)(options); + const r22 = (0, gaxios_1.request)(secondaryOptions); + return Promise.any([r1, r22]); + } + function instance(options) { + return metadataAccessor("instance", options); + } + function project(options) { + return metadataAccessor("project", options); + } + function universe(options) { + return metadataAccessor("universe", options); + } + async function bulk(properties) { + const r3 = {}; + await Promise.all(properties.map((item) => { + return (async () => { + const res = await metadataAccessor(item); + const key = item.metadataKey; + r3[key] = res; + })(); + })); + return r3; + } + function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0; + } + var cachedIsAvailableResponse; + async function isAvailable() { + if (process.env.METADATA_SERVER_DETECTION) { + const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); + if (!(value in exports.METADATA_SERVER_DETECTION)) { + throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`); } - const collection = this.ns.collection; - if (collection == null) { - throw new error_1.MongoRuntimeError("A collection name must be determined before getMore"); + switch (value) { + case "assume-present": + return true; + case "none": + return false; + case "bios-only": + return getGCPResidency(); + case "ping-only": } - const getMoreCmd = { - getMore: this.cursorId, - collection - }; - if (typeof this.options.batchSize === "number") { - getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + try { + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor("instance", undefined, detectGCPAvailableRetries(), !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); } - if (typeof this.options.maxAwaitTimeMS === "number") { - getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + await cachedIsAvailableResponse; + return true; + } catch (e2) { + const err = e2; + if (process.env.DEBUG_AUTH) { + console.info(err); } - if (this.options.comment !== undefined && (0, utils_1.maxWireVersion)(connection) >= 9) { - getMoreCmd.comment = this.options.comment; + if (err.type === "request-timeout") { + return false; } - return getMoreCmd; - } - buildOptions(timeoutContext) { - return { - returnFieldSelector: null, - documentsReturnedIn: "nextBatch", - timeoutContext, - ...this.options - }; - } - handleOk(response) { - return response; - } - } - exports.GetMoreOperation = GetMoreOperation; - (0, operation_1.defineAspects)(GetMoreOperation, [operation_1.Aspect.READ_OPERATION, operation_1.Aspect.MUST_SELECT_SAME_SERVER]); -}); - -// ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/operations/kill_cursors.js -var require_kill_cursors = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.KillCursorsOperation = undefined; - var responses_1 = require_responses(); - var error_1 = require_error2(); - var operation_1 = require_operation(); - - class KillCursorsOperation extends operation_1.AbstractOperation { - constructor(cursorId, ns3, server, options) { - super(options); - this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse; - this.ns = ns3; - this.cursorId = cursorId; - this.server = server; - } - get commandName() { - return "killCursors"; - } - buildCommand(_connection, _session) { - const killCursors = this.ns.collection; - if (killCursors == null) { - throw new error_1.MongoRuntimeError("A collection name must be determined before killCursors"); + if (err.response && err.response.status === 404) { + return false; + } else { + if (!(err.response && err.response.status === 404) && (!err.code || ![ + "EHOSTDOWN", + "EHOSTUNREACH", + "ENETUNREACH", + "ENOENT", + "ENOTFOUND", + "ECONNREFUSED" + ].includes(err.code.toString()))) { + let code = "UNKNOWN"; + if (err.code) + code = err.code.toString(); + process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, "MetadataLookupWarning"); + } + return false; } - const killCursorsCommand = { - killCursors, - cursors: [this.cursorId] - }; - return killCursorsCommand; } - buildOptions(timeoutContext) { - return { - session: this.session, - timeoutContext - }; + } + function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; + } + exports.gcpResidencyCache = null; + function getGCPResidency() { + if (exports.gcpResidencyCache === null) { + setGCPResidency(); } - handleError(_error) {} + return exports.gcpResidencyCache; } - exports.KillCursorsOperation = KillCursorsOperation; - (0, operation_1.defineAspects)(KillCursorsOperation, [operation_1.Aspect.MUST_SELECT_SAME_SERVER]); + function setGCPResidency(value = null) { + exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); + } + function requestTimeout() { + return getGCPResidency() ? 0 : 3000; + } + __exportStar(require_gcp_residency(), exports); }); // ../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js @@ -139967,9 +151369,9 @@ var require_smartbuffer = __commonJS((exports) => { utils_1.checkEncoding(encoding); } let nullPos = this.length; - for (let i2 = this._readOffset;i2 < this.length; i2++) { - if (this._buff[i2] === 0) { - nullPos = i2; + for (let i3 = this._readOffset;i3 < this.length; i3++) { + if (this._buff[i3] === 0) { + nullPos = i3; break; } } @@ -140007,9 +151409,9 @@ var require_smartbuffer = __commonJS((exports) => { } readBufferNT() { let nullPos = this.length; - for (let i2 = this._readOffset;i2 < this.length; i2++) { - if (this._buff[i2] === 0) { - nullPos = i2; + for (let i3 = this._readOffset;i3 < this.length; i3++) { + if (this._buff[i3] === 0) { + nullPos = i3; break; } } @@ -140313,7 +151715,7 @@ var require_constants7 = __commonJS((exports) => { }); // ../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/util.js -var require_util = __commonJS((exports) => { +var require_util2 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.shuffleArray = exports.SocksClientError = undefined; @@ -140325,9 +151727,9 @@ var require_util = __commonJS((exports) => { } exports.SocksClientError = SocksClientError; function shuffleArray(array3) { - for (let i2 = array3.length - 1;i2 > 0; i2--) { - const j2 = Math.floor(Math.random() * (i2 + 1)); - [array3[i2], array3[j2]] = [array3[j2], array3[i2]]; + for (let i3 = array3.length - 1;i3 > 0; i3--) { + const j2 = Math.floor(Math.random() * (i3 + 1)); + [array3[i3], array3[j2]] = [array3[j2], array3[i3]]; } } exports.shuffleArray = shuffleArray; @@ -140349,7 +151751,7 @@ var require_address_error = __commonJS((exports) => { }); // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/common.js -var require_common6 = __commonJS((exports) => { +var require_common7 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.isInSubnet = isInSubnet; exports.isCorrect = isCorrect; @@ -140420,20 +151822,20 @@ var require_constants8 = __commonJS((exports) => { // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv4.js var require_ipv4 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { Object.defineProperty(o2, "default", { enumerable: true, value: v }); @@ -140454,7 +151856,7 @@ var require_ipv4 = __commonJS((exports) => { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address4 = undefined; - var common = __importStar(require_common6()); + var common = __importStar(require_common7()); var constants = __importStar(require_constants8()); var address_error_1 = require_address_error(); var isCorrect4 = common.isCorrect(constants.BITS); @@ -140487,7 +151889,7 @@ var require_ipv4 = __commonJS((exports) => { try { new Address4(address); return true; - } catch (e) { + } catch (e2) { return false; } } @@ -140518,10 +151920,10 @@ var require_ipv4 = __commonJS((exports) => { throw new address_error_1.AddressError("Wildcard pattern must have 4 octets"); } let firstWildcard = -1; - for (let i2 = 0;i2 < groups.length; i2++) { - if (groups[i2] === "*") { + for (let i3 = 0;i3 < groups.length; i3++) { + if (groups[i3] === "*") { if (firstWildcard === -1) { - firstWildcard = i2; + firstWildcard = i3; } } else if (firstWildcard !== -1) { throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)"); @@ -140538,8 +151940,8 @@ var require_ipv4 = __commonJS((exports) => { throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits"); } const groups = []; - for (let i2 = 0;i2 < 8; i2 += 2) { - groups.push(parseInt(stripped.slice(i2, i2 + 2), 16)); + for (let i3 = 0;i3 < 8; i3 += 2) { + groups.push(parseInt(stripped.slice(i3, i3 + 2), 16)); } return new Address4(groups.join(".")); } @@ -140562,9 +151964,9 @@ var require_ipv4 = __commonJS((exports) => { } toGroup6() { const output = []; - let i2; - for (i2 = 0;i2 < constants.GROUPS; i2 += 2) { - output.push(`${common.stringToPaddedHex(this.parsedAddress[i2])}${common.stringToPaddedHex(this.parsedAddress[i2 + 1])}`); + let i3; + for (i3 = 0;i3 < constants.GROUPS; i3 += 2) { + output.push(`${common.stringToPaddedHex(this.parsedAddress[i3])}${common.stringToPaddedHex(this.parsedAddress[i3 + 1])}`); } return output.join(":"); } @@ -140610,8 +152012,8 @@ var require_ipv4 = __commonJS((exports) => { if (bytes.length !== 4) { throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes"); } - for (let i2 = 0;i2 < bytes.length; i2++) { - if (!Number.isInteger(bytes[i2]) || bytes[i2] < 0 || bytes[i2] > 255) { + for (let i3 = 0;i3 < bytes.length; i3++) { + if (!Number.isInteger(bytes[i3]) || bytes[i3] < 0 || bytes[i3] > 255) { throw new address_error_1.AddressError("All bytes must be integers between 0 and 255"); } } @@ -140743,22 +152145,22 @@ var require_constants9 = __commonJS((exports) => { }); // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/helpers.js -var require_helpers = __commonJS((exports) => { +var require_helpers2 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.escapeHtml = escapeHtml2; exports.spanAllZeroes = spanAllZeroes; exports.spanAll = spanAll; exports.spanLeadingZeroes = spanLeadingZeroes; exports.simpleGroup = simpleGroup; - function escapeHtml2(s) { - return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); + function escapeHtml2(s2) { + return s2.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } - function spanAllZeroes(s) { - return escapeHtml2(s).replace(/(0+)/g, '$1'); + function spanAllZeroes(s2) { + return escapeHtml2(s2).replace(/(0+)/g, '$1'); } - function spanAll(s, offset = 0) { - const letters = s.split(""); - return letters.map((n4, i2) => `${spanAllZeroes(n4)}`).join(""); + function spanAll(s2, offset = 0) { + const letters = s2.split(""); + return letters.map((n4, i3) => `${spanAllZeroes(n4)}`).join(""); } function spanLeadingZeroesSimple(group) { return escapeHtml2(group).replace(/^(0+)/, '$1'); @@ -140769,31 +152171,31 @@ var require_helpers = __commonJS((exports) => { } function simpleGroup(addressString, offset = 0) { const groups = addressString.split(":"); - return groups.map((g, i2) => { + return groups.map((g, i3) => { if (/group-v4/.test(g)) { return g; } - return `${spanLeadingZeroesSimple(g)}`; + return `${spanLeadingZeroesSimple(g)}`; }); } }); // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/v6/regular-expressions.js var require_regular_expressions = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { Object.defineProperty(o2, "default", { enumerable: true, value: v }); @@ -140818,7 +152220,7 @@ var require_regular_expressions = __commonJS((exports) => { exports.padGroup = padGroup; exports.simpleRegularExpression = simpleRegularExpression; exports.possibleElisions = possibleElisions; - var v62 = __importStar(require_constants9()); + var v64 = __importStar(require_constants9()); function groupPossibilities(possibilities) { return `(${possibilities.join("|")})`; } @@ -140831,15 +152233,15 @@ var require_regular_expressions = __commonJS((exports) => { exports.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]"; function simpleRegularExpression(groups) { const zeroIndexes = []; - groups.forEach((group, i2) => { + groups.forEach((group, i3) => { const groupInteger = parseInt(group, 16); if (groupInteger === 0) { - zeroIndexes.push(i2); + zeroIndexes.push(i3); } }); - const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i2) => { - if (i2 === zeroIndex) { - const elision = i2 === 0 || i2 === v62.GROUPS - 1 ? ":" : ""; + const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i3) => { + if (i3 === zeroIndex) { + const elision = i3 === 0 || i3 === v64.GROUPS - 1 ? ":" : ""; return groupPossibilities([padGroup(group), elision]); } return padGroup(group); @@ -140874,20 +152276,20 @@ var require_regular_expressions = __commonJS((exports) => { // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ipv6.js var require_ipv6 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { Object.defineProperty(o2, "default", { enumerable: true, value: v }); @@ -140908,14 +152310,14 @@ var require_ipv6 = __commonJS((exports) => { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Address6 = undefined; - var common = __importStar(require_common6()); + var common = __importStar(require_common7()); var constants4 = __importStar(require_constants8()); var constants6 = __importStar(require_constants9()); - var helpers = __importStar(require_helpers()); + var helpers = __importStar(require_helpers2()); var ipv4_1 = require_ipv4(); var regular_expressions_1 = require_regular_expressions(); var address_error_1 = require_address_error(); - var common_1 = require_common6(); + var common_1 = require_common7(); var isCorrect6 = common.isCorrect(constants6.BITS); function assert6(condition) { if (!condition) { @@ -140923,9 +152325,9 @@ var require_ipv6 = __commonJS((exports) => { } } function addCommas(number7) { - const r2 = /(\d+)(\d{3})/; - while (r2.test(number7)) { - number7 = number7.replace(r2, "$1,$2"); + const r3 = /(\d+)(\d{3})/; + while (r3.test(number7)) { + number7 = number7.replace(r3, "$1,$2"); } return number7; } @@ -140937,12 +152339,12 @@ var require_ipv6 = __commonJS((exports) => { function compact(address, slice) { const s1 = []; const s2 = []; - let i2; - for (i2 = 0;i2 < address.length; i2++) { - if (i2 < slice[0]) { - s1.push(address[i2]); - } else if (i2 > slice[1]) { - s2.push(address[i2]); + let i3; + for (i3 = 0;i3 < address.length; i3++) { + if (i3 < slice[0]) { + s1.push(address[i3]); + } else if (i3 > slice[1]) { + s2.push(address[i3]); } } return s1.concat(["compact"]).concat(s2); @@ -140994,7 +152396,7 @@ var require_ipv6 = __commonJS((exports) => { try { new Address6(address); return true; - } catch (e) { + } catch (e2) { return false; } } @@ -141004,8 +152406,8 @@ var require_ipv6 = __commonJS((exports) => { } const hex3 = bigInt.toString(16).padStart(32, "0"); const groups = []; - for (let i2 = 0;i2 < constants6.GROUPS; i2++) { - groups.push(hex3.slice(i2 * 4, (i2 + 1) * 4)); + for (let i3 = 0;i3 < constants6.GROUPS; i3++) { + groups.push(hex3.slice(i3 * 4, (i3 + 1) * 4)); } return new Address6(groups.join(":")); } @@ -141086,10 +152488,10 @@ var require_ipv6 = __commonJS((exports) => { throw new address_error_1.AddressError("Wildcard pattern must have 8 groups"); } let firstWildcard = -1; - for (let i2 = 0;i2 < groups.length; i2++) { - if (groups[i2] === "*") { + for (let i3 = 0;i3 < groups.length; i3++) { + if (groups[i3] === "*") { if (firstWildcard === -1) { - firstWildcard = i2; + firstWildcard = i3; } } else if (firstWildcard !== -1) { throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)"); @@ -141112,8 +152514,8 @@ var require_ipv6 = __commonJS((exports) => { throw new address_error_1.AddressError("Invalid 'ip6.arpa' form."); } const parts = address.split(".").reverse(); - for (let i2 = semicolonAmount;i2 > 0; i2--) { - const insertIndex = i2 * 4; + for (let i3 = semicolonAmount;i3 > 0; i3--) { + const insertIndex = i3 * 4; parts.splice(insertIndex, 0, ":"); } address = parts.join(""); @@ -141178,8 +152580,8 @@ var require_ipv6 = __commonJS((exports) => { return "Global"; } getType() { - for (let i2 = 0;i2 < TYPE_SUBNETS.length; i2++) { - const entry = TYPE_SUBNETS[i2]; + for (let i3 = 0;i3 < TYPE_SUBNETS.length; i3++) { + const entry = TYPE_SUBNETS[i3]; if (this.isInSubnet(entry[0])) { return entry[1]; } @@ -141220,18 +152622,18 @@ var require_ipv6 = __commonJS((exports) => { return "ip6.arpa."; } correctForm() { - let i2; + let i3; let groups = []; let zeroCounter = 0; const zeroes = []; - for (i2 = 0;i2 < this.parsedAddress.length; i2++) { - const value = parseInt(this.parsedAddress[i2], 16); + for (i3 = 0;i3 < this.parsedAddress.length; i3++) { + const value = parseInt(this.parsedAddress[i3], 16); if (value === 0) { zeroCounter++; } if (value !== 0 && zeroCounter > 0) { if (zeroCounter > 1) { - zeroes.push([i2 - zeroCounter, i2 - 1]); + zeroes.push([i3 - zeroCounter, i3 - 1]); } zeroCounter = 0; } @@ -141246,9 +152648,9 @@ var require_ipv6 = __commonJS((exports) => { } else { groups = this.parsedAddress; } - for (i2 = 0;i2 < groups.length; i2++) { - if (groups[i2] !== "compact") { - groups[i2] = parseInt(groups[i2], 16).toString(16); + for (i3 = 0;i3 < groups.length; i3++) { + if (groups[i3] !== "compact") { + groups[i3] = parseInt(groups[i3], 16).toString(16); } } let correct = groups.join(":"); @@ -141273,8 +152675,8 @@ var require_ipv6 = __commonJS((exports) => { if (address4) { this.parsedAddress4 = address4[0]; this.address4 = new ipv4_1.Address4(this.parsedAddress4); - for (let i2 = 0;i2 < this.address4.groups; i2++) { - if (/^0[0-9]+/.test(this.address4.parsedAddress[i2])) { + for (let i3 = 0;i3 < this.address4.groups; i3++) { + if (/^0[0-9]+/.test(this.address4.parsedAddress[i3])) { const highlighted = this.address4.parsedAddress.map(spanLeadingZeroes4).join("."); const prefix = groups.slice(0, -1).map(helpers.escapeHtml).join(":"); const separator = groups.length > 1 ? ":" : ""; @@ -141316,7 +152718,7 @@ var require_ipv6 = __commonJS((exports) => { this.elisionBegin = first2.length; this.elisionEnd = first2.length + this.elidedGroups; groups = groups.concat(first2); - for (let i2 = 0;i2 < remaining; i2++) { + for (let i3 = 0;i3 < remaining; i3++) { groups.push("0"); } groups = groups.concat(last2); @@ -141405,14 +152807,14 @@ var require_ipv6 = __commonJS((exports) => { return new Address6(addr6to4); } static fromAddress4Nat64(address, prefix = "64:ff9b::/96") { - const v44 = new ipv4_1.Address4(address); + const v45 = new ipv4_1.Address4(address); const prefix6 = new Address6(prefix); const pl = prefix6.subnetMask; if (pl !== 32 && pl !== 40 && pl !== 48 && pl !== 56 && pl !== 64 && pl !== 96) { throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96"); } const prefixBits = prefix6.binaryZeroPad(); - const v4Bits = v44.binaryZeroPad(); + const v4Bits = v45.binaryZeroPad(); let bits; if (pl === 96) { bits = prefixBits.slice(0, 96) + v4Bits; @@ -141422,8 +152824,8 @@ var require_ipv6 = __commonJS((exports) => { } const hex3 = BigInt(`0b${bits}`).toString(16).padStart(32, "0"); const groups = []; - for (let i2 = 0;i2 < 8; i2++) { - groups.push(hex3.slice(i2 * 4, (i2 + 1) * 4)); + for (let i3 = 0;i3 < 8; i3++) { + groups.push(hex3.slice(i3 * 4, (i3 + 1) * 4)); } return new Address6(groups.join(":")); } @@ -141445,8 +152847,8 @@ var require_ipv6 = __commonJS((exports) => { v4Bits = bits.slice(pl, pl + beforeU) + bits.slice(72, 72 + (32 - beforeU)); } const octets = []; - for (let i2 = 0;i2 < 4; i2++) { - octets.push(parseInt(v4Bits.slice(i2 * 8, (i2 + 1) * 8), 2).toString()); + for (let i3 = 0;i3 < 4; i3++) { + octets.push(parseInt(v4Bits.slice(i3 * 8, (i3 + 1) * 8), 2).toString()); } return new ipv4_1.Address4(octets.join(".")); } @@ -141455,8 +152857,8 @@ var require_ipv6 = __commonJS((exports) => { const leadingPad = "0".repeat(valueWithoutPadding.length % 2); const value = `${leadingPad}${valueWithoutPadding}`; const bytes = []; - for (let i2 = 0, length = value.length;i2 < length; i2 += 2) { - bytes.push(parseInt(value.substring(i2, i2 + 2), 16)); + for (let i3 = 0, length = value.length;i3 < length; i3 += 2) { + bytes.push(parseInt(value.substring(i3, i3 + 2), 16)); } return bytes; } @@ -141470,8 +152872,8 @@ var require_ipv6 = __commonJS((exports) => { const BYTE_MAX = BigInt("256"); let result = BigInt("0"); let multiplier = BigInt("1"); - for (let i2 = bytes.length - 1;i2 >= 0; i2--) { - result += multiplier * BigInt(bytes[i2].toString(10)); + for (let i3 = bytes.length - 1;i3 >= 0; i3--) { + result += multiplier * BigInt(bytes[i3].toString(10)); multiplier *= BYTE_MAX; } return Address6.fromBigInt(result); @@ -141561,8 +152963,8 @@ var require_ipv6 = __commonJS((exports) => { output.push(""); } const classes = ["hover-group"]; - for (let i2 = this.elisionBegin;i2 < this.elisionBegin + this.elidedGroups; i2++) { - classes.push(`group-${i2}`); + for (let i3 = this.elisionBegin;i3 < this.elisionBegin + this.elidedGroups; i3++) { + classes.push(`group-${i3}`); } output.push(``); if (right.length) { @@ -141627,20 +153029,20 @@ var require_ipv6 = __commonJS((exports) => { // ../../node_modules/.pnpm/ip-address@10.2.0/node_modules/ip-address/dist/ip-address.js var require_ip_address = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { Object.defineProperty(o2, "default", { enumerable: true, value: v }); @@ -141673,15 +153075,15 @@ var require_ip_address = __commonJS((exports) => { Object.defineProperty(exports, "AddressError", { enumerable: true, get: function() { return address_error_1.AddressError; } }); - var helpers = __importStar(require_helpers()); + var helpers = __importStar(require_helpers2()); exports.v6 = { helpers }; }); // ../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/helpers.js -var require_helpers2 = __commonJS((exports) => { +var require_helpers3 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.ipToBuffer = exports.int32ToIpv4 = exports.ipv4ToInt32 = exports.validateSocksClientChainOptions = exports.validateSocksClientOptions = undefined; - var util_1 = require_util(); + var util_1 = require_util2(); var constants_1 = require_constants7(); var stream2 = __require("stream"); var ip_address_1 = require_ip_address(); @@ -141839,15 +153241,15 @@ var require_socksclient = __commonJS((exports) => { function fulfilled(value) { try { step(generator.next(value)); - } catch (e) { - reject(e); + } catch (e2) { + reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); - } catch (e) { - reject(e); + } catch (e2) { + reject(e2); } } function step(result) { @@ -141862,9 +153264,9 @@ var require_socksclient = __commonJS((exports) => { var net = __require("net"); var smart_buffer_1 = require_smartbuffer(); var constants_1 = require_constants7(); - var helpers_1 = require_helpers2(); + var helpers_1 = require_helpers3(); var receivebuffer_1 = require_receivebuffer(); - var util_1 = require_util(); + var util_1 = require_util2(); Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function() { return util_1.SocksClientError; } }); @@ -141928,11 +153330,11 @@ var require_socksclient = __commonJS((exports) => { } try { let sock; - for (let i2 = 0;i2 < options.proxies.length; i2++) { - const nextProxy = options.proxies[i2]; - const nextDestination = i2 === options.proxies.length - 1 ? options.destination : { - host: options.proxies[i2 + 1].host || options.proxies[i2 + 1].ipaddress, - port: options.proxies[i2 + 1].port + for (let i3 = 0;i3 < options.proxies.length; i3++) { + const nextProxy = options.proxies[i3]; + const nextDestination = i3 === options.proxies.length - 1 ? options.destination : { + host: options.proxies[i3 + 1].host || options.proxies[i3 + 1].ipaddress, + port: options.proxies[i3 + 1].port }; const result = yield SocksClient.createConnection({ command: "connect", @@ -142407,25 +153809,25 @@ var require_socksclient = __commonJS((exports) => { // ../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/index.js var require_build = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p2 in m) + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p2 in m2) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) - __createBinding(exports2, m, p2); + __createBinding(exports2, m2, p2); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require_socksclient(), exports); @@ -142485,7 +153887,7 @@ var require_deps = __commonJS((exports) => { } function getGcpMetadata() { try { - const credentialProvider = (()=>{throw new Error("Cannot require module "+"gcp-metadata");})(); + const credentialProvider = require_src5(); return credentialProvider; } catch (error91) { return makeErrorModule(new error_1.MongoMissingDependencyError("Optional module `gcp-metadata` not found." + " Please install it to enable getting gcp credentials via the official sdk.", { cause: error91, dependencyName: "gcp-metadata" })); @@ -142869,7 +154271,7 @@ var require_mongo_credentials = __commonJS((exports) => { }); // ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/package.json -var require_package = __commonJS((exports, module) => { +var require_package2 = __commonJS((exports, module) => { module.exports = { name: "mongodb", version: "6.21.0", @@ -143063,7 +154465,7 @@ var require_client_metadata = __commonJS((exports) => { var bson_1 = require_bson2(); var error_1 = require_error2(); var utils_1 = require_utils5(); - var NODE_DRIVER_VERSION = require_package().version; + var NODE_DRIVER_VERSION = require_package2().version; function isDriverInfoEqual(info1, info2) { const nonEmptyCmp = (s1, s2) => { s1 ||= undefined; @@ -143230,12 +154632,12 @@ var require_client_metadata = __commonJS((exports) => { } function getRuntimeInfo() { if ("Deno" in globalThis) { - const version5 = typeof Deno?.version?.deno === "string" ? Deno?.version?.deno : "0.0.0-unknown"; - return `Deno v${version5}, ${os2.endianness()}`; + const version6 = typeof Deno?.version?.deno === "string" ? Deno?.version?.deno : "0.0.0-unknown"; + return `Deno v${version6}, ${os2.endianness()}`; } if ("Bun" in globalThis) { - const version5 = typeof Bun?.version === "string" ? Bun?.version : "0.0.0-unknown"; - return `Bun v${version5}, ${os2.endianness()}`; + const version6 = typeof Bun?.version === "string" ? Bun?.version : "0.0.0-unknown"; + return `Bun v${version6}, ${os2.endianness()}`; } return `Node.js ${process3.version}, ${os2.endianness()}`; } @@ -143258,27 +154660,27 @@ var require_lib = __commonJS((exports) => { } return options.globals.Number(value); } - function evenRound(x2) { - if (x2 > 0 && x2 % 1 === 0.5 && (x2 & 1) === 0 || x2 < 0 && x2 % 1 === -0.5 && (x2 & 1) === 1) { - return censorNegativeZero(Math.floor(x2)); + function evenRound(x3) { + if (x3 > 0 && x3 % 1 === 0.5 && (x3 & 1) === 0 || x3 < 0 && x3 % 1 === -0.5 && (x3 & 1) === 1) { + return censorNegativeZero(Math.floor(x3)); } - return censorNegativeZero(Math.round(x2)); + return censorNegativeZero(Math.round(x3)); } function integerPart(n4) { return censorNegativeZero(Math.trunc(n4)); } - function sign(x2) { - return x2 < 0 ? -1 : 1; + function sign(x3) { + return x3 < 0 ? -1 : 1; } - function modulo(x2, y2) { - const signMightNotMatch = x2 % y2; + function modulo(x3, y2) { + const signMightNotMatch = x3 % y2; if (sign(y2) !== sign(signMightNotMatch)) { return signMightNotMatch + y2; } return signMightNotMatch; } - function censorNegativeZero(x2) { - return x2 === 0 ? 0 : x2; + function censorNegativeZero(x3) { + return x3 === 0 ? 0 : x3; } function createIntegerConversion(bitLength, { unsigned }) { let lowerBound2, upperBound; @@ -143292,35 +154694,35 @@ var require_lib = __commonJS((exports) => { const twoToTheBitLength = 2 ** bitLength; const twoToOneLessThanTheBitLength = 2 ** (bitLength - 1); return (value, options = {}) => { - let x2 = toNumber2(value, options); - x2 = censorNegativeZero(x2); + let x3 = toNumber2(value, options); + x3 = censorNegativeZero(x3); if (options.enforceRange) { - if (!Number.isFinite(x2)) { + if (!Number.isFinite(x3)) { throw makeException(TypeError, "is not a finite number", options); } - x2 = integerPart(x2); - if (x2 < lowerBound2 || x2 > upperBound) { + x3 = integerPart(x3); + if (x3 < lowerBound2 || x3 > upperBound) { throw makeException(TypeError, `is outside the accepted range of ${lowerBound2} to ${upperBound}, inclusive`, options); } - return x2; + return x3; } - if (!Number.isNaN(x2) && options.clamp) { - x2 = Math.min(Math.max(x2, lowerBound2), upperBound); - x2 = evenRound(x2); - return x2; + if (!Number.isNaN(x3) && options.clamp) { + x3 = Math.min(Math.max(x3, lowerBound2), upperBound); + x3 = evenRound(x3); + return x3; } - if (!Number.isFinite(x2) || x2 === 0) { + if (!Number.isFinite(x3) || x3 === 0) { return 0; } - x2 = integerPart(x2); - if (x2 >= lowerBound2 && x2 <= upperBound) { - return x2; + x3 = integerPart(x3); + if (x3 >= lowerBound2 && x3 <= upperBound) { + return x3; } - x2 = modulo(x2, twoToTheBitLength); - if (!unsigned && x2 >= twoToOneLessThanTheBitLength) { - return x2 - twoToTheBitLength; + x3 = modulo(x3, twoToTheBitLength); + if (!unsigned && x3 >= twoToOneLessThanTheBitLength) { + return x3 - twoToTheBitLength; } - return x2; + return x3; }; } function createLongLongConversion(bitLength, { unsigned }) { @@ -143328,27 +154730,27 @@ var require_lib = __commonJS((exports) => { const lowerBound2 = unsigned ? 0 : Number.MIN_SAFE_INTEGER; const asBigIntN = unsigned ? BigInt.asUintN : BigInt.asIntN; return (value, options = {}) => { - let x2 = toNumber2(value, options); - x2 = censorNegativeZero(x2); + let x3 = toNumber2(value, options); + x3 = censorNegativeZero(x3); if (options.enforceRange) { - if (!Number.isFinite(x2)) { + if (!Number.isFinite(x3)) { throw makeException(TypeError, "is not a finite number", options); } - x2 = integerPart(x2); - if (x2 < lowerBound2 || x2 > upperBound) { + x3 = integerPart(x3); + if (x3 < lowerBound2 || x3 > upperBound) { throw makeException(TypeError, `is outside the accepted range of ${lowerBound2} to ${upperBound}, inclusive`, options); } - return x2; + return x3; } - if (!Number.isNaN(x2) && options.clamp) { - x2 = Math.min(Math.max(x2, lowerBound2), upperBound); - x2 = evenRound(x2); - return x2; + if (!Number.isNaN(x3) && options.clamp) { + x3 = Math.min(Math.max(x3, lowerBound2), upperBound); + x3 = evenRound(x3); + return x3; } - if (!Number.isFinite(x2) || x2 === 0) { + if (!Number.isFinite(x3) || x3 === 0) { return 0; } - let xBigInt = BigInt(integerPart(x2)); + let xBigInt = BigInt(integerPart(x3)); xBigInt = asBigIntN(bitLength, xBigInt); return Number(xBigInt); }; @@ -143371,39 +154773,39 @@ var require_lib = __commonJS((exports) => { exports["long long"] = createLongLongConversion(64, { unsigned: false }); exports["unsigned long long"] = createLongLongConversion(64, { unsigned: true }); exports.double = (value, options = {}) => { - const x2 = toNumber2(value, options); - if (!Number.isFinite(x2)) { + const x3 = toNumber2(value, options); + if (!Number.isFinite(x3)) { throw makeException(TypeError, "is not a finite floating-point value", options); } - return x2; + return x3; }; exports["unrestricted double"] = (value, options = {}) => { - const x2 = toNumber2(value, options); - return x2; + const x3 = toNumber2(value, options); + return x3; }; exports.float = (value, options = {}) => { - const x2 = toNumber2(value, options); - if (!Number.isFinite(x2)) { + const x3 = toNumber2(value, options); + if (!Number.isFinite(x3)) { throw makeException(TypeError, "is not a finite floating-point value", options); } - if (Object.is(x2, -0)) { - return x2; + if (Object.is(x3, -0)) { + return x3; } - const y2 = Math.fround(x2); + const y2 = Math.fround(x3); if (!Number.isFinite(y2)) { throw makeException(TypeError, "is outside the range of a single-precision floating-point value", options); } return y2; }; exports["unrestricted float"] = (value, options = {}) => { - const x2 = toNumber2(value, options); - if (isNaN(x2)) { - return x2; + const x3 = toNumber2(value, options); + if (isNaN(x3)) { + return x3; } - if (Object.is(x2, -0)) { - return x2; + if (Object.is(x3, -0)) { + return x3; } - return Math.fround(x2); + return Math.fround(x3); }; exports.DOMString = (value, options = {}) => { if (options.treatNullAsEmptyString && value === null) { @@ -143416,34 +154818,34 @@ var require_lib = __commonJS((exports) => { return StringCtor(value); }; exports.ByteString = (value, options = {}) => { - const x2 = exports.DOMString(value, options); + const x3 = exports.DOMString(value, options); let c3; - for (let i2 = 0;(c3 = x2.codePointAt(i2)) !== undefined; ++i2) { + for (let i3 = 0;(c3 = x3.codePointAt(i3)) !== undefined; ++i3) { if (c3 > 255) { throw makeException(TypeError, "is not a valid ByteString", options); } } - return x2; + return x3; }; exports.USVString = (value, options = {}) => { - const S2 = exports.DOMString(value, options); - const n4 = S2.length; + const S3 = exports.DOMString(value, options); + const n4 = S3.length; const U2 = []; - for (let i2 = 0;i2 < n4; ++i2) { - const c3 = S2.charCodeAt(i2); + for (let i3 = 0;i3 < n4; ++i3) { + const c3 = S3.charCodeAt(i3); if (c3 < 55296 || c3 > 57343) { U2.push(String.fromCodePoint(c3)); } else if (56320 <= c3 && c3 <= 57343) { U2.push(String.fromCodePoint(65533)); - } else if (i2 === n4 - 1) { + } else if (i3 === n4 - 1) { U2.push(String.fromCodePoint(65533)); } else { - const d = S2.charCodeAt(i2 + 1); + const d = S3.charCodeAt(i3 + 1); if (56320 <= d && d <= 57343) { const a = c3 & 1023; const b2 = d & 1023; U2.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b2)); - ++i2; + ++i3; } else { U2.push(String.fromCodePoint(65533)); } @@ -143499,7 +154901,7 @@ var require_lib = __commonJS((exports) => { exports.DataView = (value, options = {}) => { try { dvByteLengthGetter.call(value); - } catch (e) { + } catch (e2) { throw makeException(TypeError, "is not a DataView", options); } if (!options.allowShared && isSharedArrayBuffer(value.buffer)) { @@ -143579,7 +154981,7 @@ var require_utils7 = __commonJS((exports, module) => { return typeof value === "object" && value !== null || typeof value === "function"; } var hasOwn2 = Function.prototype.call.bind(Object.prototype.hasOwnProperty); - function define(target, source) { + function define2(target, source) { for (const key of Reflect.ownKeys(source)) { const descriptor = Reflect.getOwnPropertyDescriptor(source, key); if (descriptor && !Reflect.defineProperty(target, key, descriptor)) { @@ -143640,12 +155042,12 @@ var require_utils7 = __commonJS((exports, module) => { if (typeof P2 !== "string") { return false; } - const i2 = P2 >>> 0; - if (i2 === 2 ** 32 - 1) { + const i3 = P2 >>> 0; + if (i3 === 2 ** 32 - 1) { return false; } - const s = `${i2}`; - if (P2 !== s) { + const s2 = `${i3}`; + if (P2 !== s2) { return false; } return true; @@ -143655,7 +155057,7 @@ var require_utils7 = __commonJS((exports, module) => { try { byteLengthGetter.call(value); return true; - } catch (e) { + } catch (e2) { return false; } } @@ -143692,7 +155094,7 @@ var require_utils7 = __commonJS((exports, module) => { module.exports = exports = { isObject: isObject4, hasOwn: hasOwn2, - define, + define: define2, newObjectInRealm, wrapperSymbol, implSymbol, @@ -143818,7 +155220,7 @@ var require_punycode = __commonJS((exports, module) => { var decode3 = function(input) { const output = []; const inputLength = input.length; - let i2 = 0; + let i3 = 0; let n4 = initialN; let bias = initialBias; let basic = input.lastIndexOf(delimiter); @@ -143832,7 +155234,7 @@ var require_punycode = __commonJS((exports, module) => { output.push(input.charCodeAt(j2)); } for (let index2 = basic > 0 ? basic + 1 : 0;index2 < inputLength; ) { - const oldi = i2; + const oldi = i3; for (let w = 1, k2 = base;; k2 += base) { if (index2 >= inputLength) { error91("invalid-input"); @@ -143841,32 +155243,32 @@ var require_punycode = __commonJS((exports, module) => { if (digit >= base) { error91("invalid-input"); } - if (digit > floor((maxInt - i2) / w)) { + if (digit > floor((maxInt - i3) / w)) { error91("overflow"); } - i2 += digit * w; - const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias; - if (digit < t2) { + i3 += digit * w; + const t3 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias; + if (digit < t3) { break; } - const baseMinusT = base - t2; + const baseMinusT = base - t3; if (w > floor(maxInt / baseMinusT)) { error91("overflow"); } w *= baseMinusT; } const out = output.length + 1; - bias = adapt(i2 - oldi, out, oldi == 0); - if (floor(i2 / out) > maxInt - n4) { + bias = adapt(i3 - oldi, out, oldi == 0); + if (floor(i3 / out) > maxInt - n4) { error91("overflow"); } - n4 += floor(i2 / out); - i2 %= out; - output.splice(i2++, 0, n4); + n4 += floor(i3 / out); + i3 %= out; + output.splice(i3++, 0, n4); } return String.fromCodePoint(...output); }; - var encode3 = function(input) { + var encode4 = function(input) { const output = []; input = ucs2decode(input); const inputLength = input.length; @@ -143884,18 +155286,18 @@ var require_punycode = __commonJS((exports, module) => { output.push(delimiter); } while (handledCPCount < inputLength) { - let m = maxInt; + let m2 = maxInt; for (const currentValue of input) { - if (currentValue >= n4 && currentValue < m) { - m = currentValue; + if (currentValue >= n4 && currentValue < m2) { + m2 = currentValue; } } const handledCPCountPlusOne = handledCPCount + 1; - if (m - n4 > floor((maxInt - delta) / handledCPCountPlusOne)) { + if (m2 - n4 > floor((maxInt - delta) / handledCPCountPlusOne)) { error91("overflow"); } - delta += (m - n4) * handledCPCountPlusOne; - n4 = m; + delta += (m2 - n4) * handledCPCountPlusOne; + n4 = m2; for (const currentValue of input) { if (currentValue < n4 && ++delta > maxInt) { error91("overflow"); @@ -143903,13 +155305,13 @@ var require_punycode = __commonJS((exports, module) => { if (currentValue === n4) { let q2 = delta; for (let k2 = base;; k2 += base) { - const t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias; - if (q2 < t2) { + const t3 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias; + if (q2 < t3) { break; } - const qMinusT = q2 - t2; - const baseMinusT = base - t2; - output.push(stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0))); + const qMinusT = q2 - t3; + const baseMinusT = base - t3; + output.push(stringFromCharCode(digitToBasic(t3 + qMinusT % baseMinusT, 0))); q2 = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q2, 0))); @@ -143930,7 +155332,7 @@ var require_punycode = __commonJS((exports, module) => { }; var toASCII = function(input) { return mapDomain(input, function(string7) { - return regexNonASCII.test(string7) ? "xn--" + encode3(string7) : string7; + return regexNonASCII.test(string7) ? "xn--" + encode4(string7) : string7; }); }; var punycode = { @@ -143940,7 +155342,7 @@ var require_punycode = __commonJS((exports, module) => { encode: ucs2encode }, decode: decode3, - encode: encode3, + encode: encode4, toASCII, toUnicode }; @@ -144100,17 +155502,17 @@ var require_tr46 = __commonJS((exports, module) => { } if (checkJoiners) { let last2 = 0; - for (const [i2, ch] of codePoints.entries()) { + for (const [i3, ch] of codePoints.entries()) { if (ch === "‌" || ch === "‍") { - if (i2 > 0) { - if (regexes.combiningClassVirama.test(codePoints[i2 - 1])) { + if (i3 > 0) { + if (regexes.combiningClassVirama.test(codePoints[i3 - 1])) { continue; } if (ch === "‌") { - const next = codePoints.indexOf("‌", i2 + 1); + const next = codePoints.indexOf("‌", i3 + 1); const test = next < 0 ? codePoints.slice(last2) : codePoints.slice(last2, next); if (regexes.validZWNJ.test(test.join(""))) { - last2 = i2 + 1; + last2 = i3 + 1; continue; } } @@ -144157,7 +155559,7 @@ var require_tr46 = __commonJS((exports, module) => { const labels = string7.split("."); const isBidi = isBidiDomain(labels); let error91 = false; - for (const [i2, origLabel] of labels.entries()) { + for (const [i3, origLabel] of labels.entries()) { let label = origLabel; let transitionalProcessingForThisLabel = options.transitionalProcessing; if (label.startsWith("xn--")) { @@ -144173,7 +155575,7 @@ var require_tr46 = __commonJS((exports, module) => { continue; } } - labels[i2] = label; + labels[i3] = label; if (label === "" || !containsNonASCII(label)) { error91 = true; } @@ -144229,8 +155631,8 @@ var require_tr46 = __commonJS((exports, module) => { if (total > 253 || total === 0) { result.error = true; } - for (let i2 = 0;i2 < labels.length; ++i2) { - if (labels[i2].length > 63 || labels[i2].length === 0) { + for (let i3 = 0;i3 < labels.length; ++i3) { + if (labels[i3].length > 63 || labels[i3].length === 0) { result.error = true; break; } @@ -144323,16 +155725,16 @@ var require_percent_encoding = __commonJS((exports, module) => { function percentDecodeBytes(input) { const output = new Uint8Array(input.byteLength); let outputIndex = 0; - for (let i2 = 0;i2 < input.byteLength; ++i2) { - const byte = input[i2]; + for (let i3 = 0;i3 < input.byteLength; ++i3) { + const byte = input[i3]; if (byte !== 37) { output[outputIndex++] = byte; - } else if (byte === 37 && (!isASCIIHex(input[i2 + 1]) || !isASCIIHex(input[i2 + 2]))) { + } else if (byte === 37 && (!isASCIIHex(input[i3 + 1]) || !isASCIIHex(input[i3 + 2]))) { output[outputIndex++] = byte; } else { - const bytePoint = parseInt(String.fromCodePoint(input[i2 + 1], input[i2 + 2]), 16); + const bytePoint = parseInt(String.fromCodePoint(input[i3 + 1], input[i3 + 2]), 16); output[outputIndex++] = bytePoint; - i2 += 2; + i3 += 2; } } return output.slice(0, outputIndex); @@ -144526,8 +155928,8 @@ var require_url_state_machine = __commonJS((exports, module) => { } numbers.push(n4); } - for (let i2 = 0;i2 < numbers.length - 1; ++i2) { - if (numbers[i2] > 255) { + for (let i3 = 0;i3 < numbers.length - 1; ++i3) { + if (numbers[i3] > 255) { return failure; } } @@ -144545,9 +155947,9 @@ var require_url_state_machine = __commonJS((exports, module) => { function serializeIPv4(address) { let output = ""; let n4 = address; - for (let i2 = 1;i2 <= 4; ++i2) { + for (let i3 = 1;i3 <= 4; ++i3) { output = String(n4 % 256) + output; - if (i2 !== 4) { + if (i3 !== 4) { output = `.${output}`; } n4 = Math.floor(n4 / 256); @@ -145496,10 +156898,10 @@ var require_urlencoded = __commonJS((exports, module) => { } function serializeUrlencoded(tuples) { let output = ""; - for (const [i2, tuple3] of tuples.entries()) { + for (const [i3, tuple3] of tuples.entries()) { const name = utf8PercentEncodeString(tuple3[0], isURLEncodedPercentEncode, true); const value = utf8PercentEncodeString(tuple3[1], isURLEncodedPercentEncode, true); - if (i2 !== 0) { + if (i3 !== 0) { output += "&"; } output += `${name}=${value}`; @@ -145509,11 +156911,11 @@ var require_urlencoded = __commonJS((exports, module) => { function strictlySplitByteSequence(buf, cp4) { const list = []; let last2 = 0; - let i2 = buf.indexOf(cp4); - while (i2 >= 0) { - list.push(buf.slice(last2, i2)); - last2 = i2 + 1; - i2 = buf.indexOf(cp4, last2); + let i3 = buf.indexOf(cp4); + while (i3 >= 0) { + list.push(buf.slice(last2, i3)); + last2 = i3 + 1; + i3 = buf.indexOf(cp4, last2); } if (last2 !== buf.length) { list.push(buf.slice(last2)); @@ -145521,10 +156923,10 @@ var require_urlencoded = __commonJS((exports, module) => { return list; } function replaceByteInByteSequence(buf, from, to) { - let i2 = buf.indexOf(from); - while (i2 >= 0) { - buf[i2] = to; - i2 = buf.indexOf(from, i2 + 1); + let i3 = buf.indexOf(from); + while (i3 >= 0) { + buf[i3] = to; + i3 = buf.indexOf(from, i3 + 1); } return buf; } @@ -145545,16 +156947,16 @@ var require_Function = __commonJS((exports) => { function invokeTheCallbackFunction(...args) { const thisArg = utils.tryWrapperForImpl(this); let callResult; - for (let i2 = 0;i2 < args.length; i2++) { - args[i2] = utils.tryWrapperForImpl(args[i2]); + for (let i3 = 0;i3 < args.length; i3++) { + args[i3] = utils.tryWrapperForImpl(args[i3]); } callResult = Reflect.apply(value, thisArg, args); callResult = conversions["any"](callResult, { context: context2, globals: globalObject }); return callResult; } invokeTheCallbackFunction.construct = (...args) => { - for (let i2 = 0;i2 < args.length; i2++) { - args[i2] = utils.tryWrapperForImpl(args[i2]); + for (let i3 = 0;i3 < args.length; i3++) { + args[i3] = utils.tryWrapperForImpl(args[i3]); } let callResult = Reflect.construct(value, args); callResult = conversions["any"](callResult, { context: context2, globals: globalObject }); @@ -145610,12 +157012,12 @@ var require_URLSearchParams_impl = __commonJS((exports) => { this._updateSteps(); } delete(name, value) { - let i2 = 0; - while (i2 < this._list.length) { - if (this._list[i2][0] === name && (value === undefined || this._list[i2][1] === value)) { - this._list.splice(i2, 1); + let i3 = 0; + while (i3 < this._list.length) { + if (this._list[i3][0] === name && (value === undefined || this._list[i3][1] === value)) { + this._list.splice(i3, 1); } else { - i2++; + i3++; } } this._updateSteps(); @@ -145647,18 +157049,18 @@ var require_URLSearchParams_impl = __commonJS((exports) => { } set(name, value) { let found = false; - let i2 = 0; - while (i2 < this._list.length) { - if (this._list[i2][0] === name) { + let i3 = 0; + while (i3 < this._list.length) { + if (this._list[i3][0] === name) { if (found) { - this._list.splice(i2, 1); + this._list.splice(i3, 1); } else { found = true; - this._list[i2][1] = value; - i2++; + this._list[i3][1] = value; + i3++; } } else { - i2++; + i3++; } } if (!found) { @@ -146033,12 +157435,12 @@ var require_URLSearchParams = __commonJS((exports) => { }); const thisArg = arguments[1]; let pairs = Array.from(this[implSymbol]); - let i2 = 0; - while (i2 < pairs.length) { - const [key, value] = pairs[i2].map(utils.tryWrapperForImpl); + let i3 = 0; + while (i3 < pairs.length) { + const [key, value] = pairs[i3].map(utils.tryWrapperForImpl); callback.call(thisArg, value, key, this); pairs = Array.from(this[implSymbol]); - i2++; + i3++; } } get size() { @@ -146709,20 +158111,20 @@ var require_whatwg_url = __commonJS((exports) => { // ../../node_modules/.pnpm/mongodb-connection-string-url@3.0.2/node_modules/mongodb-connection-string-url/lib/redact.js var require_redact = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m, k2, k22) { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - var desc = Object.getOwnPropertyDescriptor(m, k2); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + var desc = Object.getOwnPropertyDescriptor(m2, k2); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { - return m[k2]; + return m2[k2]; } }; } Object.defineProperty(o2, k22, desc); - } : function(o2, m, k2, k22) { + } : function(o2, m2, k2, k22) { if (k22 === undefined) k22 = k2; - o2[k22] = m[k2]; + o2[k22] = m2[k2]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o2, v) { Object.defineProperty(o2, "default", { enumerable: true, value: v }); @@ -147230,7 +158632,7 @@ var require_commands = __commonJS((exports) => { this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - for (let i2 = 0;i2 < this.numberReturned; i2++) { + for (let i3 = 0;i3 < this.numberReturned; i3++) { const bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; const section = this.data.subarray(this.index, this.index + bsonSize); this.sections.push(section); @@ -147450,7 +158852,7 @@ var require_compression = __commonJS((exports) => { exports.compressCommand = compressCommand; exports.decompressResponse = decompressResponse; var util_1 = __require("util"); - var zlib = __require("zlib"); + var zlib2 = __require("zlib"); var constants_1 = require_constants6(); var deps_1 = require_deps(); var error_1 = require_error2(); @@ -147475,8 +158877,8 @@ var require_compression = __commonJS((exports) => { "copydb" ]); var ZSTD_COMPRESSION_LEVEL = 3; - var zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib)); - var zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib)); + var zlibInflate = (0, util_1.promisify)(zlib2.inflate.bind(zlib2)); + var zlibDeflate = (0, util_1.promisify)(zlib2.deflate.bind(zlib2)); var zstd; var Snappy = null; function loadSnappy() { @@ -147602,8 +159004,8 @@ var require_crypto_callbacks = __commonJS((exports) => { if (final3.length > 0) { result = Buffer.concat([result, final3]); } - } catch (e) { - return e; + } catch (e2) { + return e2; } result.copy(output); return result.length; @@ -147612,8 +159014,8 @@ var require_crypto_callbacks = __commonJS((exports) => { function randomHook(buffer, count) { try { crypto3.randomFillSync(buffer, 0, count); - } catch (e) { - return e; + } catch (e2) { + return e2; } return count; } @@ -147621,8 +159023,8 @@ var require_crypto_callbacks = __commonJS((exports) => { let result; try { result = crypto3.createHash("sha256").update(input).digest(); - } catch (e) { - return e; + } catch (e2) { + return e2; } result.copy(output); return result.length; @@ -147632,8 +159034,8 @@ var require_crypto_callbacks = __commonJS((exports) => { let result; try { result = crypto3.createHmac(algorithm, key).update(input).digest(); - } catch (e) { - return e; + } catch (e2) { + return e2; } result.copy(output); return result.length; @@ -147648,8 +159050,8 @@ ${key.toString("base64")} -----END PRIVATE KEY----- `); result = signer.update(input).end().sign(privateKey); - } catch (e) { - return e; + } catch (e2) { + return e2; } result.copy(output); return result.length; @@ -147996,7 +159398,7 @@ var require_providers2 = __commonJS((exports) => { var require_state_machine = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.StateMachine = undefined; - var fs2 = __require("fs/promises"); + var fs3 = __require("fs/promises"); var net = __require("net"); var tls = __require("tls"); var bson_1 = require_bson2(); @@ -148261,11 +159663,11 @@ var require_state_machine = __commonJS((exports) => { options.secureContext = tlsOptions.secureContext; } if (tlsOptions.tlsCertificateKeyFile) { - const cert = await fs2.readFile(tlsOptions.tlsCertificateKeyFile); + const cert = await fs3.readFile(tlsOptions.tlsCertificateKeyFile); options.cert = options.key = cert; } if (tlsOptions.tlsCAFile) { - options.ca = await fs2.readFile(tlsOptions.tlsCAFile); + options.ca = await fs3.readFile(tlsOptions.tlsCAFile); } if (tlsOptions.tlsCertificateKeyFilePassword) { options.passphrase = tlsOptions.tlsCertificateKeyFilePassword; @@ -148372,9 +159774,9 @@ var require_client_encryption = __commonJS((exports) => { } let keyAltNames = undefined; if (options.keyAltNames && options.keyAltNames.length > 0) { - keyAltNames = options.keyAltNames.map((keyAltName, i2) => { + keyAltNames = options.keyAltNames.map((keyAltName, i3) => { if (typeof keyAltName !== "string") { - throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${i2} was of type ${typeof keyAltName}`); + throw new errors_1.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${i3} was of type ${typeof keyAltName}`); } return (0, bson_1.serialize)({ keyAltName }); }); @@ -148467,7 +159869,7 @@ var require_client_encryption = __commonJS((exports) => { } async removeKeyAltName(_id, keyAltName) { const { db: dbName, collection: collectionName } = utils_1.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace); - const pipeline = [ + const pipeline2 = [ { $set: { keyAltNames: { @@ -148489,7 +159891,7 @@ var require_client_encryption = __commonJS((exports) => { } } ]; - const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, pipeline, { + const value = await this._keyVaultClient.db(dbName).collection(collectionName).findOneAndUpdate({ _id }, pipeline2, { writeConcern: { w: "majority" }, returnDocument: "before", timeoutMS: this._timeoutMS @@ -150573,8 +161975,8 @@ var require_connection = __commonJS((exports) => { const session = options?.session; let clusterTime = this.clusterTime; if (this.serverApi) { - const { version: version5, strict, deprecationErrors } = this.serverApi; - cmd.apiVersion = version5; + const { version: version6, strict, deprecationErrors } = this.serverApi; + cmd.apiVersion = version6; if (strict != null) cmd.apiStrict = strict; if (deprecationErrors != null) @@ -151758,7 +163160,7 @@ var require_connection_pool = __commonJS((exports) => { return; } for (const event of [...constants_1.APM_EVENTS, connection_1.Connection.CLUSTER_TIME_RECEIVED]) { - connection.on(event, (e) => this.emit(event, e)); + connection.on(event, (e2) => this.emit(event, e2)); } if (this.loadBalanced) { connection.on(connection_1.Connection.PINNED, (pinType) => this.metrics.markPinned(pinType)); @@ -151929,7 +163331,7 @@ var require_server = __commonJS((exports) => { operationCount: 0 }; for (const event of [...constants_1.CMAP_EVENTS, ...constants_1.APM_EVENTS]) { - this.pool.on(event, (e) => this.emit(event, e)); + this.pool.on(event, (e2) => this.emit(event, e2)); } this.pool.on(connection_1.Connection.CLUSTER_TIME_RECEIVED, (clusterTime) => { this.clusterTime = clusterTime; @@ -151940,7 +163342,7 @@ var require_server = __commonJS((exports) => { } this.monitor = new monitor_1.Monitor(this, this.s.options); for (const event of constants_1.HEARTBEAT_EVENTS) { - this.monitor.on(event, (e) => this.emit(event, e)); + this.monitor.on(event, (e2) => this.emit(event, e2)); } this.monitor.on("resetServer", (error91) => markServerUnknown(this, error91)); this.monitor.on(Server.SERVER_HEARTBEAT_SUCCEEDED, (event) => { @@ -152041,9 +163443,9 @@ var require_server = __commonJS((exports) => { let cmd; try { cmd = operation.buildCommand(conn, session); - } catch (e) { + } catch (e2) { cleanup(); - throw e; + throw e2; } const options = operation.buildOptions(timeoutContext); const ns3 = operation.ns; @@ -152653,9 +164055,9 @@ var require_monitor = __commonJS((exports) => { if (this.length < 2) return 0; let min = this.rttSamples[0]; - for (let i2 = 1;i2 < this.length; i2++) { - if (this.rttSamples[i2] < min) - min = this.rttSamples[i2]; + for (let i3 = 1;i3 < this.length; i3++) { + if (this.rttSamples[i3] < min) + min = this.rttSamples[i3]; } return min; } @@ -152663,8 +164065,8 @@ var require_monitor = __commonJS((exports) => { if (this.length === 0) return 0; let sum = 0; - for (let i2 = 0;i2 < this.length; i2++) { - sum += this.rttSamples[i2]; + for (let i3 = 0;i3 < this.length; i3++) { + sum += this.rttSamples[i3]; } return sum / this.length; } @@ -152736,7 +164138,7 @@ var require_connection_string = __commonJS((exports) => { for (const { name } of addresses) { (0, utils_1.checkParentDomainMatch)(name, lookupAddress); } - const hostAddresses = addresses.map((r2) => utils_1.HostAddress.fromString(`${r2.name}:${r2.port ?? 27017}`)); + const hostAddresses = addresses.map((r3) => utils_1.HostAddress.fromString(`${r3.name}:${r3.port ?? 27017}`)); validateLoadBalancedOptions(hostAddresses, options, true); let record3; try { @@ -152922,7 +164324,7 @@ var require_connection_string = __commonJS((exports) => { } } checkTLSOptions(allProvidedOptions); - const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports.OPTIONS)).map((s) => s.toLowerCase())); + const unsupportedOptions = (0, utils_1.setDifference)(allProvidedKeys, Array.from(Object.keys(exports.OPTIONS)).map((s2) => s2.toLowerCase())); if (unsupportedOptions.size !== 0) { const optionWord = unsupportedOptions.size > 1 ? "options" : "option"; const isOrAre = unsupportedOptions.size > 1 ? "are" : "is"; @@ -153098,7 +164500,7 @@ var require_connection_string = __commonJS((exports) => { target: "credentials", transform({ options, values: [value] }) { const mechanisms = Object.values(providers_1.AuthMechanism); - const [mechanism] = mechanisms.filter((m) => m.match(RegExp(String.raw`\b${value}\b`, "i"))); + const [mechanism] = mechanisms.filter((m2) => m2.match(RegExp(String.raw`\b${value}\b`, "i"))); if (!mechanism) { throw new error_1.MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); } @@ -153164,8 +164566,8 @@ var require_connection_string = __commonJS((exports) => { }, serverApi: { target: "serverApi", - transform({ values: [version5] }) { - const serverApiToValidate = typeof version5 === "string" ? { version: version5 } : version5; + transform({ values: [version6] }) { + const serverApiToValidate = typeof version6 === "string" ? { version: version6 } : version6; const versionToValidate = serverApiToValidate && serverApiToValidate.version; if (!versionToValidate) { throw new error_1.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(mongo_client_1.ServerApiVersion).join('", "')}"]`); @@ -153877,11 +165279,11 @@ var require_indexes = __commonJS((exports) => { "bucketSize", "wildcardProjection" ]); - function isIndexDirection(x2) { - return typeof x2 === "number" || x2 === "2d" || x2 === "2dsphere" || x2 === "text" || x2 === "geoHaystack"; + function isIndexDirection(x3) { + return typeof x3 === "number" || x3 === "2d" || x3 === "2dsphere" || x3 === "text" || x3 === "geoHaystack"; } - function isSingleIndexTuple(t2) { - return Array.isArray(t2) && t2.length === 2 && isIndexDirection(t2[1]); + function isSingleIndexTuple(t3) { + return Array.isArray(t3) && t3.length === 2 && isIndexDirection(t3[1]); } function constructIndexDescriptionMap(indexSpec) { const key = new Map; @@ -154486,8 +165888,8 @@ var require_db = __commonJS((exports) => { signal: options?.signal }))); } - aggregate(pipeline = [], options) { - return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + aggregate(pipeline2 = [], options) { + return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline2, (0, utils_1.resolveOptions)(this, options)); } admin() { return new admin_1.Admin(this); @@ -154539,12 +165941,12 @@ var require_db = __commonJS((exports) => { async indexInformation(name, options) { return await this.collection(name).indexInformation((0, utils_1.resolveOptions)(this, options)); } - watch(pipeline = [], options = {}) { - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; + watch(pipeline2 = [], options = {}) { + if (!Array.isArray(pipeline2)) { + options = pipeline2; + pipeline2 = []; } - return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options)); } runCursorCommand(command, options) { return new run_command_cursor_1.RunCommandCursor(this, command, options); @@ -154976,7 +166378,7 @@ var require_token_cache = __commonJS((exports) => { class MongoOIDCError extends error_1.MongoDriverError { } - class TokenCache { + class TokenCache2 { get hasAccessToken() { return !!this.accessToken; } @@ -155019,14 +166421,14 @@ var require_token_cache = __commonJS((exports) => { this.refreshToken = undefined; } } - exports.TokenCache = TokenCache; + exports.TokenCache = TokenCache2; }); // ../../node_modules/.pnpm/mongodb@6.21.0_socks@2.8.9/node_modules/mongodb/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js var require_token_machine_workflow = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.callback = undefined; - var fs2 = __require("fs"); + var fs3 = __require("fs"); var error_1 = require_error2(); var TOKEN_MISSING_ERROR = "OIDC_TOKEN_FILE must be set in the environment."; var callback = async () => { @@ -155034,7 +166436,7 @@ var require_token_machine_workflow = __commonJS((exports) => { if (!tokenFile) { throw new error_1.MongoAWSError(TOKEN_MISSING_ERROR); } - const token = await fs2.promises.readFile(tokenFile, "utf8"); + const token = await fs3.promises.readFile(tokenFile, "utf8"); return { accessToken: token }; }; exports.callback = callback; @@ -155212,20 +166614,20 @@ var require_plain = __commonJS((exports) => { }); // ../../node_modules/.pnpm/@mongodb-js+saslprep@1.4.11/node_modules/@mongodb-js/saslprep/dist/index.js -var require_dist6 = __commonJS((exports, module) => { +var require_dist9 = __commonJS((exports, module) => { var getCodePoint = (character) => character.codePointAt(0); - var first2 = (x2) => x2[0]; - var last2 = (x2) => x2[x2.length - 1]; + var first2 = (x3) => x3[0]; + var last2 = (x3) => x3[x3.length - 1]; function toCodePoints(input) { const codepoints = []; const size = input.length; - for (let i2 = 0;i2 < size; i2 += 1) { - const before = input.charCodeAt(i2); - if (before >= 55296 && before <= 56319 && size > i2 + 1) { - const next = input.charCodeAt(i2 + 1); + for (let i3 = 0;i3 < size; i3 += 1) { + const before = input.charCodeAt(i3); + if (before >= 55296 && before <= 56319 && size > i3 + 1) { + const next = input.charCodeAt(i3 + 1); if (next >= 56320 && next <= 57343) { codepoints.push((before - 55296) * 1024 + next - 56320 + 65536); - i2 += 1; + i3 += 1; continue; } } @@ -155310,13 +166712,13 @@ var require_memory_pager = __commonJS((exports, module) => { page.updated = false; return page; }; - Pager.prototype._array = function(i2, noAllocate) { - if (i2 >= this.maxPages) { + Pager.prototype._array = function(i3, noAllocate) { + if (i3 >= this.maxPages) { if (noAllocate) return; - grow(this, i2); + grow(this, i3); } - factor(i2, this.path); + factor(i3, this.path); var arr3 = this.pages; for (var j2 = this.level;j2 > 0; j2--) { var p2 = this.path[j2]; @@ -155330,14 +166732,14 @@ var require_memory_pager = __commonJS((exports, module) => { } return arr3; }; - Pager.prototype.get = function(i2, noAllocate) { - var arr3 = this._array(i2, noAllocate); + Pager.prototype.get = function(i3, noAllocate) { + var arr3 = this._array(i3, noAllocate); var first2 = this.path[0]; var page = arr3 && arr3[first2]; if (!page && !noAllocate) { - page = arr3[first2] = new Page2(i2, alloc(this.pageSize)); - if (i2 >= this.length) - this.length = i2 + 1; + page = arr3[first2] = new Page2(i3, alloc(this.pageSize)); + if (i3 >= this.length) + this.length = i3 + 1; } if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { page.buffer = copy(page.buffer); @@ -155345,11 +166747,11 @@ var require_memory_pager = __commonJS((exports, module) => { } return page; }; - Pager.prototype.set = function(i2, buf) { - var arr3 = this._array(i2, false); + Pager.prototype.set = function(i3, buf) { + var arr3 = this._array(i3, false); var first2 = this.path[0]; - if (i2 >= this.length) - this.length = i2 + 1; + if (i3 >= this.length) + this.length = i3 + 1; if (!buf || this.zeros && buf.equals && buf.equals(this.zeros)) { arr3[first2] = undefined; return; @@ -155362,7 +166764,7 @@ var require_memory_pager = __commonJS((exports, module) => { if (page) page.buffer = b2; else - arr3[first2] = new Page2(i2, b2); + arr3[first2] = new Page2(i3, b2); }; Pager.prototype.toBuffer = function() { var list = new Array(this.length); @@ -155370,8 +166772,8 @@ var require_memory_pager = __commonJS((exports, module) => { var ptr = 0; while (ptr < list.length) { var arr3 = this._array(ptr, true); - for (var i2 = 0;i2 < 32768 && ptr < list.length; i2++) { - list[ptr++] = arr3 && arr3[i2] ? arr3[i2].buffer : empty; + for (var i3 = 0;i3 < 32768 && ptr < list.length; i3++) { + list[ptr++] = arr3 && arr3[i3] ? arr3[i3].buffer : empty; } } return Buffer.concat(list); @@ -155406,8 +166808,8 @@ var require_memory_pager = __commonJS((exports, module) => { buf.copy(cpy); return cpy; } - function Page2(i2, buf) { - this.offset = i2 * buf.length; + function Page2(i3, buf) { + this.offset = i3 * buf.length; this.buffer = buf; this.updated = false; this.deduplicate = 0; @@ -155440,50 +166842,50 @@ var require_sparse_bitfield = __commonJS((exports, module) => { this._trackUpdates = !!opts.trackUpdates; this._pageMask = this.pageSize - 1; if (opts.buffer) { - for (var i2 = 0;i2 < opts.buffer.length; i2 += this.pageSize) { - this.pages.set(i2 / this.pageSize, opts.buffer.slice(i2, i2 + this.pageSize)); + for (var i3 = 0;i3 < opts.buffer.length; i3 += this.pageSize) { + this.pages.set(i3 / this.pageSize, opts.buffer.slice(i3, i3 + this.pageSize)); } this.byteLength = opts.buffer.length; this.length = 8 * this.byteLength; } } - Bitfield.prototype.get = function(i2) { - var o2 = i2 & 7; - var j2 = (i2 - o2) / 8; + Bitfield.prototype.get = function(i3) { + var o2 = i3 & 7; + var j2 = (i3 - o2) / 8; return !!(this.getByte(j2) & 128 >> o2); }; - Bitfield.prototype.getByte = function(i2) { - var o2 = i2 & this._pageMask; - var j2 = (i2 - o2) / this.pageSize; + Bitfield.prototype.getByte = function(i3) { + var o2 = i3 & this._pageMask; + var j2 = (i3 - o2) / this.pageSize; var page = this.pages.get(j2, true); return page ? page.buffer[o2 + this.pageOffset] : 0; }; - Bitfield.prototype.set = function(i2, v) { - var o2 = i2 & 7; - var j2 = (i2 - o2) / 8; + Bitfield.prototype.set = function(i3, v) { + var o2 = i3 & 7; + var j2 = (i3 - o2) / 8; var b2 = this.getByte(j2); return this.setByte(j2, v ? b2 | 128 >> o2 : b2 & (255 ^ 128 >> o2)); }; Bitfield.prototype.toBuffer = function() { var all = alloc(this.pages.length * this.pageSize); - for (var i2 = 0;i2 < this.pages.length; i2++) { - var next = this.pages.get(i2, true); - var allOffset = i2 * this.pageSize; + for (var i3 = 0;i3 < this.pages.length; i3++) { + var next = this.pages.get(i3, true); + var allOffset = i3 * this.pageSize; if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize); } return all; }; - Bitfield.prototype.setByte = function(i2, b2) { - var o2 = i2 & this._pageMask; - var j2 = (i2 - o2) / this.pageSize; + Bitfield.prototype.setByte = function(i3, b2) { + var o2 = i3 & this._pageMask; + var j2 = (i3 - o2) / this.pageSize; var page = this.pages.get(j2, false); o2 += this.pageOffset; if (page.buffer[o2] === b2) return false; page.buffer[o2] = b2; - if (i2 >= this.byteLength) { - this.byteLength = i2 + 1; + if (i3 >= this.byteLength) { + this.byteLength = i3 + 1; this.length = this.byteLength * 8; } if (this._trackUpdates) @@ -155497,8 +166899,8 @@ var require_sparse_bitfield = __commonJS((exports, module) => { b2.fill(0); return b2; } - function powerOfTwo(x2) { - return !(x2 & x2 - 1); + function powerOfTwo(x3) { + return !(x3 & x3 - 1); } }); @@ -155548,7 +166950,7 @@ var require_node2 = __commonJS((exports, module) => { var __importDefault = exports && exports.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { default: mod }; }; - var index_1 = __importDefault(require_dist6()); + var index_1 = __importDefault(require_dist9()); var memory_code_points_1 = require_memory_code_points(); var code_points_data_1 = __importDefault(require_code_points_data()); var codePoints = (0, memory_code_points_1.createMemoryCodePoints)(code_points_data_1.default); @@ -155682,17 +167084,17 @@ var require_scram = __commonJS((exports) => { conversationId: response.conversationId, payload: new bson_1.Binary(Buffer.from(clientFinal)) }; - const r2 = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined); - const parsedResponse = parsePayload(r2.payload); + const r3 = await connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined); + const parsedResponse = parsePayload(r3.payload); if (!compareDigest(Buffer.from(parsedResponse.v, "base64"), serverSignature)) { throw new error_1.MongoRuntimeError("Server returned an invalid signature"); } - if (r2.done !== false) { + if (r3.done !== false) { return; } const retrySaslContinueCmd = { saslContinue: 1, - conversationId: r2.conversationId, + conversationId: r3.conversationId, payload: Buffer.alloc(0) }; await connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined); @@ -155701,8 +167103,8 @@ var require_scram = __commonJS((exports) => { const payloadStr = payload.toString("utf8"); const dict = {}; const parts = payloadStr.split(","); - for (let i2 = 0;i2 < parts.length; i2++) { - const valueParts = (parts[i2].match(/^([^=]*)=(.*)$/) ?? []).slice(1); + for (let i3 = 0;i3 < parts.length; i3++) { + const valueParts = (parts[i3].match(/^([^=]*)=(.*)$/) ?? []).slice(1); dict[valueParts[0]] = valueParts[1]; } return dict; @@ -155738,8 +167140,8 @@ var require_scram = __commonJS((exports) => { } const length = Math.max(a.length, b2.length); const res = []; - for (let i2 = 0;i2 < length; i2 += 1) { - res.push(a[i2] ^ b2[i2]); + for (let i3 = 0;i3 < length; i3 += 1) { + res.push(a[i3] ^ b2[i3]); } return Buffer.from(res).toString("base64"); } @@ -155780,8 +167182,8 @@ var require_scram = __commonJS((exports) => { return crypto3.timingSafeEqual(lhs, rhs); } let result = 0; - for (let i2 = 0;i2 < lhs.length; i2++) { - result |= lhs[i2] ^ rhs[i2]; + for (let i3 = 0;i3 < lhs.length; i3++) { + result |= lhs[i3] ^ rhs[i3]; } return result === 0; } @@ -156551,7 +167953,7 @@ var require_srv_polling = __commonJS((exports) => { this.srvRecords = srvRecords; } hostnames() { - return new Set(this.srvRecords.map((r2) => utils_1.HostAddress.fromSrvRecord(r2).toString())); + return new Set(this.srvRecords.map((r3) => utils_1.HostAddress.fromSrvRecord(r3).toString())); } } exports.SrvPollingEvent = SrvPollingEvent; @@ -157041,7 +168443,7 @@ var require_topology = __commonJS((exports) => { topology.emitAndLog(Topology.SERVER_OPENING, new events_1.ServerOpeningEvent(topology.s.id, serverDescription.address)); const server = new server_1.Server(topology, serverDescription, topology.s.options); for (const event of constants_1.SERVER_RELAY_EVENTS) { - server.on(event, (e) => topology.emit(event, e)); + server.on(event, (e2) => topology.emit(event, e2)); } server.on(server_1.Server.DESCRIPTION_RECEIVED, (description) => topology.serverUpdateHandler(description)); server.connect(); @@ -157107,7 +168509,7 @@ var require_topology = __commonJS((exports) => { const isSharded = topology.description.type === common_1.TopologyType.Sharded; const serverDescriptions = Array.from(topology.description.servers.values()); const membersToProcess = topology.waitQueue.length; - for (let i2 = 0;i2 < membersToProcess; ++i2) { + for (let i3 = 0;i3 < membersToProcess; ++i3) { const waitQueueMember = topology.waitQueue.shift(); if (!waitQueueMember) { continue; @@ -157520,12 +168922,12 @@ var require_mongo_client = __commonJS((exports) => { } } } - watch(pipeline = [], options = {}) { - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; + watch(pipeline2 = [], options = {}) { + if (!Array.isArray(pipeline2)) { + options = pipeline2; + pipeline2 = []; } - return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options)); } } exports.MongoClient = MongoClient; @@ -158274,9 +169676,9 @@ var require_aggregation_cursor = __commonJS((exports) => { var explainable_cursor_1 = require_explainable_cursor(); class AggregationCursor extends explainable_cursor_1.ExplainableCursor { - constructor(client2, namespace, pipeline = [], options = {}) { + constructor(client2, namespace, pipeline2 = [], options = {}) { super(client2, namespace, options); - this.pipeline = pipeline; + this.pipeline = pipeline2; this.aggregateOptions = options; const lastStage = this.pipeline[this.pipeline.length - 1]; if (this.cursorOptions.timeoutMS != null && this.cursorOptions.timeoutMode === abstract_cursor_1.CursorTimeoutMode.ITERATION && (lastStage?.$merge != null || lastStage?.$out != null)) @@ -158614,8 +170016,8 @@ var require_find_cursor = __commonJS((exports) => { async getMore(batchSize) { const numReturned = this.numReturned; if (numReturned) { - const limit = this.findOptions.limit; - batchSize = limit && limit > 0 && numReturned + batchSize > limit ? limit - numReturned : batchSize; + const limit2 = this.findOptions.limit; + batchSize = limit2 && limit2 > 0 && numReturned + batchSize > limit2 ? limit2 - numReturned : batchSize; if (batchSize <= 0) { try { await this.close(); @@ -158839,8 +170241,8 @@ var require_list_search_indexes_cursor = __commonJS((exports) => { class ListSearchIndexesCursor extends aggregation_cursor_1.AggregationCursor { constructor({ fullNamespace: ns3, client: client2 }, name, options = {}) { - const pipeline = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }]; - super(client2, ns3, pipeline, options); + const pipeline2 = name == null ? [{ $listSearchIndexes: {} }] : [{ $listSearchIndexes: { name } }]; + super(client2, ns3, pipeline2, options); } } exports.ListSearchIndexesCursor = ListSearchIndexesCursor; @@ -159418,16 +170820,16 @@ var require_collection = __commonJS((exports) => { return await (0, execute_operation_1.executeOperation)(this.client, new estimated_document_count_1.EstimatedDocumentCountOperation(this, (0, utils_1.resolveOptions)(this, options))); } async countDocuments(filter = {}, options = {}) { - const pipeline = []; - pipeline.push({ $match: filter }); + const pipeline2 = []; + pipeline2.push({ $match: filter }); if (typeof options.skip === "number") { - pipeline.push({ $skip: options.skip }); + pipeline2.push({ $skip: options.skip }); } if (typeof options.limit === "number") { - pipeline.push({ $limit: options.limit }); + pipeline2.push({ $limit: options.limit }); } - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - const cursor = this.aggregate(pipeline, options); + pipeline2.push({ $group: { _id: 1, n: { $sum: 1 } } }); + const cursor = this.aggregate(pipeline2, options); const doc3 = await cursor.next(); await cursor.close(); return doc3?.n ?? 0; @@ -159453,18 +170855,18 @@ var require_collection = __commonJS((exports) => { async findOneAndUpdate(filter, update, options) { return await (0, execute_operation_1.executeOperation)(this.client, new find_and_modify_1.FindOneAndUpdateOperation(this, filter, update, (0, utils_1.resolveOptions)(this, options))); } - aggregate(pipeline = [], options) { - if (!Array.isArray(pipeline)) { + aggregate(pipeline2 = [], options) { + if (!Array.isArray(pipeline2)) { throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); } - return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + return new aggregation_cursor_1.AggregationCursor(this.client, this.s.namespace, pipeline2, (0, utils_1.resolveOptions)(this, options)); } - watch(pipeline = [], options = {}) { - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; + watch(pipeline2 = [], options = {}) { + if (!Array.isArray(pipeline2)) { + options = pipeline2; + pipeline2 = []; } - return new change_stream_1.ChangeStream(this, pipeline, (0, utils_1.resolveOptions)(this, options)); + return new change_stream_1.ChangeStream(this, pipeline2, (0, utils_1.resolveOptions)(this, options)); } initializeUnorderedBulkOp(options) { return new unordered_1.UnorderedBulkOperation(this, (0, utils_1.resolveOptions)(this, options)); @@ -159509,9 +170911,9 @@ var require_change_stream_cursor = __commonJS((exports) => { var abstract_cursor_1 = require_abstract_cursor(); class ChangeStreamCursor extends abstract_cursor_1.AbstractCursor { - constructor(client2, namespace, pipeline = [], options = {}) { + constructor(client2, namespace, pipeline2 = [], options = {}) { super(client2, namespace, { ...options, tailable: true, awaitData: true }); - this.pipeline = pipeline; + this.pipeline = pipeline2; this.changeStreamCursorOptions = options; this._resumeToken = null; this.startAtOperationTime = options.startAtOperationTime ?? null; @@ -159633,9 +171035,9 @@ var require_change_stream = __commonJS((exports) => { async asyncDispose() { await this.close(); } - constructor(parent, pipeline = [], options = {}) { + constructor(parent, pipeline2 = [], options = {}) { super(); - this.pipeline = pipeline; + this.pipeline = pipeline2; this.options = { ...options }; let serverSelectionTimeoutMS; delete this.options.writeConcern; @@ -159822,17 +171224,17 @@ var require_change_stream = __commonJS((exports) => { if (this.type === CHANGE_DOMAIN_TYPES.CLUSTER) { changeStreamStageOptions.allChangesForCluster = true; } - const pipeline = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; + const pipeline2 = [{ $changeStream: changeStreamStageOptions }, ...this.pipeline]; const client2 = this.type === CHANGE_DOMAIN_TYPES.CLUSTER ? this.parent : this.type === CHANGE_DOMAIN_TYPES.DATABASE ? this.parent.client : this.type === CHANGE_DOMAIN_TYPES.COLLECTION ? this.parent.client : null; if (client2 == null) { throw new error_1.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`); } - const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client2, this.namespace, pipeline, { + const changeStreamCursor = new change_stream_cursor_1.ChangeStreamCursor(client2, this.namespace, pipeline2, { ...options, timeoutContext: this.timeoutContext ? new abstract_cursor_1.CursorTimeoutContext(this.timeoutContext, this.contextOwner) : undefined }); for (const event of CHANGE_STREAM_EVENTS) { - changeStreamCursor.on(event, (e) => this.emit(event, e)); + changeStreamCursor.on(event, (e2) => this.emit(event, e2)); } if (this.listenerCount(ChangeStream.CHANGE) > 0) { this._streamEvents(changeStreamCursor); @@ -159884,8 +171286,8 @@ var require_change_stream = __commonJS((exports) => { return; if (cursorInitialized && ((0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion) || changeStreamError instanceof error_1.MongoOperationTimeoutError)) { this._endStream(); - this.cursor.close().then(() => this._resume(changeStreamError), (e) => { - (0, utils_1.squashError)(e); + this.cursor.close().then(() => this._resume(changeStreamError), (e2) => { + (0, utils_1.squashError)(e2); return this._resume(changeStreamError); }).then(() => { if (changeStreamError instanceof error_1.MongoOperationTimeoutError) @@ -161068,7 +172470,7 @@ var require_lib3 = __commonJS((exports) => { } }); }); -// ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.18/node_modules/@hono/node-server/dist/index.mjs +// ../../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs import { createServer as createServerHTTP } from "http"; import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2"; import { Http2ServerRequest } from "http2"; @@ -161686,7 +173088,7 @@ var serve = (options, listeningListener) => { return server; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/compose.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js var compose = (middleware, onError, onNotFound) => { return (context, next) => { let index = -1; @@ -161730,7 +173132,7 @@ var compose = (middleware, onError, onNotFound) => { }; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/http-exception.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/http-exception.js var HTTPException = class extends Error { res; status; @@ -161753,10 +173155,10 @@ var HTTPException = class extends Error { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/request/constants.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/utils/body.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => { const { all = false, dot = false } = options; const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; @@ -161827,7 +173229,7 @@ var handleParsingNestedValues = (form, key, value) => { }); }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/utils/url.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js var splitPath = (path) => { const paths = path.split("/"); if (paths[0] === "") { @@ -162027,7 +173429,7 @@ var getQueryParams = (url, key) => { }; var decodeURIComponent_ = decodeURIComponent; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/request.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_); var HonoRequest = class { raw; @@ -162109,6 +173511,9 @@ var HonoRequest = class { arrayBuffer() { return this.#cachedBody("arrayBuffer"); } + bytes() { + return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer)); + } blob() { return this.#cachedBody("blob"); } @@ -162138,7 +173543,7 @@ var HonoRequest = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/utils/html.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js var HtmlEscapedCallbackPhase = { Stringify: 1, BeforeStream: 2, @@ -162176,7 +173581,7 @@ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/context.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js var TEXT_PLAIN = "text/plain; charset=UTF-8"; var setDefaultContentType = (contentType, headers) => { return { @@ -162343,7 +173748,7 @@ var Context = class { }; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js var METHOD_NAME_ALL = "ALL"; var METHOD_NAME_ALL_LOWERCASE = "all"; var METHODS = ["get", "post", "put", "delete", "options", "patch"]; @@ -162351,10 +173756,10 @@ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is var UnsupportedPathError = class extends Error { }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/utils/constants.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/hono-base.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js var notFoundHandler = (c) => { return c.text("404 Not Found", 404); }; @@ -162445,7 +173850,7 @@ var Hono = class _Hono { handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res; handler[COMPOSED_HANDLER] = r.handler; } - subApp.#addRoute(r.method, r.path, handler); + subApp.#addRoute(r.method, r.path, handler, r.basePath); }); return this; } @@ -162492,7 +173897,7 @@ var Hono = class _Hono { const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; return (request) => { const url = new URL(request.url); - url.pathname = url.pathname.slice(pathPrefixLength) || "/"; + url.pathname = this.getPath(request).slice(pathPrefixLength) || "/"; return new Request(url, request); }; })(); @@ -162506,10 +173911,15 @@ var Hono = class _Hono { this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler); return this; } - #addRoute(method, path, handler) { + #addRoute(method, path, handler, baseRoutePath) { method = method.toUpperCase(); path = mergePath(this._basePath, path); - const r = { basePath: this._basePath, path, method, handler }; + const r = { + basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath, + path, + method, + handler + }; this.router.add(method, path, [handler, r]); this.routes.push(r); } @@ -162573,7 +173983,7 @@ var Hono = class _Hono { }; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/matcher.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/matcher.js var emptyParam = []; function match(method, path) { const matchers = this.buildAllMatchers(); @@ -162594,7 +174004,7 @@ function match(method, path) { return match2(method, path); } -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/node.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/node.js var LABEL_REG_EXP_STR = "[^/]+"; var ONLY_WILDCARD_REG_EXP_STR = ".*"; var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; @@ -162698,7 +174108,7 @@ var Node = class _Node { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/trie.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/trie.js var Trie = class { #context = { varIndex: 0 }; #root = new Node; @@ -162754,7 +174164,7 @@ var Trie = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/router.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/router.js var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); function buildWildcardRegExp(path) { @@ -162919,7 +174329,7 @@ var RegExpRouter = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/reg-exp-router/prepared-router.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/reg-exp-router/prepared-router.js var PreparedRegExpRouter = class { name = "PreparedRegExpRouter"; #matchers; @@ -162991,7 +174401,7 @@ var PreparedRegExpRouter = class { match = match; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/smart-router/router.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/smart-router/router.js var SmartRouter = class { name = "SmartRouter"; #routers = []; @@ -163046,7 +174456,7 @@ var SmartRouter = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/trie-router/node.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/node.js var emptyParams = /* @__PURE__ */ Object.create(null); var hasChildren = (children) => { for (const _ in children) { @@ -163215,7 +174625,7 @@ var Node2 = class _Node2 { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/router/trie-router/router.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/trie-router/router.js var TrieRouter = class { name = "TrieRouter"; #node; @@ -163237,7 +174647,7 @@ var TrieRouter = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/hono.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono.js var Hono2 = class extends Hono { constructor(options = {}) { super(options); @@ -164330,7 +175740,7 @@ function sessionsRoute(ctx) { return app; } -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/utils/stream.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/stream.js var StreamingApi = class { writer; encoder; @@ -164353,7 +175763,9 @@ var StreamingApi = class { done ? controller.close() : controller.enqueue(value); }, cancel: () => { - this.abort(); + if (!this.closed) { + this.abort(); + } } }); } @@ -164375,10 +175787,10 @@ var StreamingApi = class { return new Promise((res) => setTimeout(res, ms)); } async close() { + this.closed = true; try { await this.writer.close(); } catch {} - this.closed = true; } async pipe(body) { this.writer.releaseLock(); @@ -164396,7 +175808,7 @@ var StreamingApi = class { } }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/helper/streaming/utils.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/helper/streaming/utils.js var isOldBunVersion = () => { const version2 = typeof Bun !== "undefined" ? Bun.version : undefined; if (version2 === undefined) { @@ -164407,7 +175819,7 @@ var isOldBunVersion = () => { return result; }; -// ../../node_modules/.pnpm/hono@4.12.18/node_modules/hono/dist/helper/streaming/sse.js +// ../../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/helper/streaming/sse.js var SSEStreamingApi = class extends StreamingApi { constructor(writable, readable) { super(writable, readable); @@ -165181,6 +176593,28 @@ function deriveEngineUuid(sessionId) { return v5_default(sessionId, NAMESPACE_COMPUTERAGENT_SESSION); } +// ../engine-claude-agent-sdk/dist/pin-session-store-key.js +function pinSessionStoreKey(store, sessionId) { + const pin = (key) => ({ ...key, sessionId }); + const wrapped = { + append: (key, entries) => store.append(pin(key), entries), + load: (key) => store.load(pin(key)) + }; + if (store.listSessions) { + wrapped.listSessions = (projectKey) => store.listSessions(projectKey); + } + if (store.listSessionSummaries) { + wrapped.listSessionSummaries = (projectKey) => store.listSessionSummaries(projectKey); + } + if (store.delete) { + wrapped.delete = (key) => store.delete(pin(key)); + } + if (store.listSubkeys) { + wrapped.listSubkeys = (key) => store.listSubkeys(pin(key)); + } + return wrapped; +} + // ../engine-claude-agent-sdk/dist/engine.js var CAPABILITIES = { streamingInput: true, @@ -165208,14 +176642,15 @@ class ClaudeAgentEngine { const engineUuid = deriveEngineUuid(ctx.sessionId); let storeOpts = {}; if (ctx.sessionStore) { - const prior = await ctx.sessionStore.load({ + const store = pinSessionStoreKey(ctx.sessionStore, ctx.sessionId); + const prior = await store.load({ projectKey: PROJECT_KEY, sessionId: engineUuid }); if (prior && prior.length > 0) { - storeOpts = { sessionStore: ctx.sessionStore, resume: engineUuid }; + storeOpts = { sessionStore: store, resume: engineUuid }; } else { - storeOpts = { sessionStore: ctx.sessionStore, sessionId: engineUuid }; + storeOpts = { sessionStore: store, sessionId: engineUuid }; } } const flatTemperature = ctx.options.temperature; @@ -165224,13 +176659,42 @@ class ClaudeAgentEngine { const options = { ...stripFlatTemperature(ctx.options), cwd: ctx.workdir, - env: { ...inheritEssentialHostEnv(), ...ctx.envs }, + env: { IS_SANDBOX: "1", ...inheritEssentialHostEnv(), ...ctx.envs }, includePartialMessages: true, abortController, canUseTool: buildCanUseTool(ctx.onPermissionRequest), ...ctx.budget?.maxUsd !== undefined ? { maxBudgetUsd: ctx.budget.maxUsd } : {}, ...storeOpts }; + if (ctx.policyActive) { + options["hooks"] = { + PreToolUse: [ + { + hooks: [ + async (input, toolUseId) => { + const pre = input; + const result = await ctx.onPermissionRequest({ + callId: toolUseId ?? `hook-${pre.tool_name ?? "tool"}`, + toolName: pre.tool_name ?? "", + input: pre.tool_input ?? {} + }); + if (result.behavior === "deny") { + log.info("policy.hook_deny", { sessionId: ctx.sessionId, toolName: pre.tool_name }); + return { + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: result.message ?? "blocked by policy" + } + }; + } + return {}; + } + ] + } + ] + }; + } try { for await (const message of query({ prompt, options })) { if (ctx.abortSignal.aborted) @@ -165677,9 +177141,9 @@ class DeepAgentsEngine { async* startSession(ctx) { const log2 = ctx.logger ?? nopLogger; const [{ createDeepAgent: createDeepAgent2, LocalShellBackend: LocalShellBackend3 }, { ChatAnthropic: ChatAnthropic2 }, { MemorySaver: MemorySaver2 }] = await Promise.all([ - Promise.resolve().then(() => (init_dist8(), exports_dist2)), - Promise.resolve().then(() => (init_dist9(), exports_dist3)), - Promise.resolve().then(() => (init_dist10(), exports_dist4)) + Promise.resolve().then(() => (init_dist9(), exports_dist2)), + Promise.resolve().then(() => (init_dist10(), exports_dist3)), + Promise.resolve().then(() => (init_dist4(), exports_dist)) ]); const modelName = ctx.options.model ?? "claude-sonnet-4-5-20250929"; const apiKey = ctx.envs.ANTHROPIC_API_KEY ?? (typeof process !== "undefined" ? process.env.ANTHROPIC_API_KEY : undefined); @@ -165876,7 +177340,7 @@ import { cp as cp2, mkdir as mkdir6, stat as stat4, writeFile as writeFile3 } fr import { join as join4 } from "node:path"; // ../../node_modules/.pnpm/simple-git@3.36.0/node_modules/simple-git/dist/esm/index.js -var import_file_exists = __toESM(require_dist4(), 1); +var import_file_exists = __toESM(require_dist5(), 1); // ../../node_modules/.pnpm/@simple-git+args-pathspec@1.0.3/node_modules/@simple-git/args-pathspec/dist/index.mjs var t = /* @__PURE__ */ new WeakMap; @@ -165894,7 +177358,7 @@ function o(n4) { // ../../node_modules/.pnpm/simple-git@3.36.0/node_modules/simple-git/dist/esm/index.js var import_debug5 = __toESM(require_src(), 1); import { spawn as spawn2 } from "child_process"; -var import_promise_deferred = __toESM(require_dist5(), 1); +var import_promise_deferred = __toESM(require_dist6(), 1); import { normalize as normalize3 } from "node:path"; // ../../node_modules/.pnpm/@simple-git+argv-parser@1.1.1/node_modules/@simple-git/argv-parser/dist/index.mjs @@ -166332,7 +177796,7 @@ function ne(e, t2) { } // ../../node_modules/.pnpm/simple-git@3.36.0/node_modules/simple-git/dist/esm/index.js -var import_promise_deferred2 = __toESM(require_dist5(), 1); +var import_promise_deferred2 = __toESM(require_dist6(), 1); import { EventEmitter as EventEmitter2 } from "node:events"; var __defProp4 = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -166726,7 +178190,7 @@ function parseStringResponse(result, parsers12, texts, trim = true) { } return lines[i2 + offset]; }; - parsers12.some(({ parse: parse15 }) => parse15(line, result)); + parsers12.some(({ parse: parse16 }) => parse16(line, result)); } }); return result; @@ -166782,7 +178246,7 @@ __export2(utils_exports, { trailingFunctionArgument: () => trailingFunctionArgument, trailingOptionsArgument: () => trailingOptionsArgument }); -var init_utils19 = __esm2({ +var init_utils20 = __esm2({ "src/lib/utils/index.ts"() { init_argument_filters(); init_exit_codes(); @@ -166844,7 +178308,7 @@ var onError2; var parser; var init_check_is_repo = __esm2({ "src/lib/tasks/check-is-repo.ts"() { - init_utils19(); + init_utils20(); CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { CheckRepoActions2["BARE"] = "bare"; CheckRepoActions2["IN_TREE"] = "tree"; @@ -166878,7 +178342,7 @@ var dryRunRemovalRegexp; var isFolderRegexp; var init_CleanSummary = __esm2({ "src/lib/responses/CleanSummary.ts"() { - init_utils19(); + init_utils20(); CleanResponse = class { constructor(dryRun) { this.dryRun = dryRun; @@ -167024,7 +178488,7 @@ var CleanOptionValues; var init_clean = __esm2({ "src/lib/tasks/clean.ts"() { init_CleanSummary(); - init_utils19(); + init_utils20(); init_task(); CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; @@ -167096,7 +178560,7 @@ function* configParser(text, requestedKey = null) { var ConfigList; var init_ConfigList = __esm2({ "src/lib/responses/ConfigList.ts"() { - init_utils19(); + init_utils20(); ConfigList = class { constructor() { this.files = []; @@ -167195,7 +178659,7 @@ var GitConfigScope; var init_config4 = __esm2({ "src/lib/tasks/config.ts"() { init_ConfigList(); - init_utils19(); + init_utils20(); GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { GitConfigScope2["system"] = "system"; GitConfigScope2["global"] = "global"; @@ -167277,7 +178741,7 @@ var _a4; var GrepQuery; var init_grep = __esm2({ "src/lib/tasks/grep.ts"() { - init_utils19(); + init_utils20(); init_task(); disallowedOptions = ["-h"]; Query = Symbol("grepQuery"); @@ -167333,7 +178797,7 @@ var ResetMode; var validResetModes; var init_reset = __esm2({ "src/lib/tasks/reset.ts"() { - init_utils19(); + init_utils20(); init_task(); ResetMode = /* @__PURE__ */ ((ResetMode2) => { ResetMode2["MIXED"] = "mixed"; @@ -167396,7 +178860,7 @@ function createLogger2(label, verbose, initialStep, infoDebugger = createLog()) } var init_git_logger = __esm2({ "src/lib/git-logger.ts"() { - init_utils19(); + init_utils20(); import_debug5.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); import_debug5.default.formatters.B = (value) => { if (Buffer.isBuffer(value)) { @@ -167495,7 +178959,7 @@ var init_git_executor_chain = __esm2({ "src/lib/runners/git-executor-chain.ts"() { init_git_error(); init_task(); - init_utils19(); + init_utils20(); init_tasks_pending_queue(); GitExecutorChain = class { constructor(_executor, _scheduler, _plugins) { @@ -167713,7 +179177,7 @@ function addDeprecationNoticeToError(err) { var init_task_callback = __esm2({ "src/lib/task-callback.ts"() { init_git_response_error(); - init_utils19(); + init_utils20(); } }); function changeWorkingDirectoryTask(directory, root) { @@ -167726,7 +179190,7 @@ function changeWorkingDirectoryTask(directory, root) { } var init_change_working_directory = __esm2({ "src/lib/tasks/change-working-directory.ts"() { - init_utils19(); + init_utils20(); init_task(); } }); @@ -167752,7 +179216,7 @@ function checkout_default() { } var init_checkout = __esm2({ "src/lib/tasks/checkout.ts"() { - init_utils19(); + init_utils20(); init_task(); } }); @@ -167784,7 +179248,7 @@ function count_objects_default() { var parser2; var init_count_objects = __esm2({ "src/lib/tasks/count-objects.ts"() { - init_utils19(); + init_utils20(); parser2 = new LineParser(/([a-z-]+): (\d+)$/, (result, [key, value]) => { const property = asCamelCase(key); if (Object.hasOwn(result, property)) { @@ -167810,7 +179274,7 @@ function parseCommitResult(stdOut) { var parsers; var init_parse_commit = __esm2({ "src/lib/parsers/parse-commit.ts"() { - init_utils19(); + init_utils20(); parsers = [ new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => { result.branch = branch; @@ -167878,7 +179342,7 @@ function commit_default() { var init_commit = __esm2({ "src/lib/tasks/commit.ts"() { init_parse_commit(); - init_utils19(); + init_utils20(); init_task(); } }); @@ -167891,7 +179355,7 @@ function first_commit_default() { } var init_first_commit = __esm2({ "src/lib/tasks/first-commit.ts"() { - init_utils19(); + init_utils20(); init_task(); } }); @@ -168012,7 +179476,7 @@ var init_parse_diff_summary = __esm2({ init_log_format(); init_DiffSummary(); init_diff_name_status(); - init_utils19(); + init_utils20(); statParser = [ new LineParser(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, (result, [file3, changes, alterations = ""]) => { result.files.push({ @@ -168130,7 +179594,7 @@ var SPLITTER; var defaultFieldNames; var init_parse_list_log_summary = __esm2({ "src/lib/parsers/parse-list-log-summary.ts"() { - init_utils19(); + init_utils20(); init_parse_diff_summary(); init_log_format(); START_BOUNDARY = "òòòòòò "; @@ -168255,7 +179719,7 @@ var init_log2 = __esm2({ "src/lib/tasks/log.ts"() { init_log_format(); init_parse_list_log_summary(); - init_utils19(); + init_utils20(); init_task(); init_diff(); excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { @@ -168372,7 +179836,7 @@ function asObjectCount(source) { var remoteMessagesObjectParsers; var init_parse_remote_objects = __esm2({ "src/lib/parsers/parse-remote-objects.ts"() { - init_utils19(); + init_utils20(); remoteMessagesObjectParsers = [ new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, (result, [action, count]) => { const key = action.toLowerCase(); @@ -168400,7 +179864,7 @@ var parsers2; var RemoteMessageSummary; var init_parse_remote_messages = __esm2({ "src/lib/parsers/parse-remote-messages.ts"() { - init_utils19(); + init_utils20(); init_parse_remote_objects(); parsers2 = [ new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => { @@ -168440,7 +179904,7 @@ var parsePullResult; var init_parse_pull = __esm2({ "src/lib/parsers/parse-pull.ts"() { init_PullSummary(); - init_utils19(); + init_utils20(); init_parse_remote_messages(); FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; @@ -168493,7 +179957,7 @@ var parseMergeDetail; var init_parse_merge = __esm2({ "src/lib/parsers/parse-merge.ts"() { init_MergeSummary(); - init_utils19(); + init_utils20(); init_parse_pull(); parsers4 = [ new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { @@ -168562,7 +180026,7 @@ var parsePushResult; var parsePushDetail; var init_parse_push = __esm2({ "src/lib/parsers/parse-push.ts"() { - init_utils19(); + init_utils20(); init_parse_remote_messages(); parsers5 = [ new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { @@ -168640,7 +180104,7 @@ function pushTask(ref = {}, customArgs) { var init_push = __esm2({ "src/lib/tasks/push.ts"() { init_parse_push(); - init_utils19(); + init_utils20(); } }); function show_default() { @@ -168660,7 +180124,7 @@ function show_default() { } var init_show = __esm2({ "src/lib/tasks/show.ts"() { - init_utils19(); + init_utils20(); init_task(); } }); @@ -168722,7 +180186,7 @@ var parsers6; var parseStatusSummary; var init_StatusSummary = __esm2({ "src/lib/responses/StatusSummary.ts"() { - init_utils19(); + init_utils20(); init_FileStatusSummary(); StatusSummary = class { constructor() { @@ -168895,7 +180359,7 @@ var NOT_INSTALLED; var parsers7; var init_version3 = __esm2({ "src/lib/tasks/version.ts"() { - init_utils19(); + init_utils20(); NOT_INSTALLED = "installed=false"; parsers7 = [ new LineParser(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, (result, [major, minor, patch, agent = ""]) => { @@ -168928,7 +180392,7 @@ var cloneMirrorTask; var init_clone = __esm2({ "src/lib/tasks/clone.ts"() { init_task(); - init_utils19(); + init_utils20(); cloneTask = (repo, directory, customArgs) => { const commands = ["clone", ...customArgs]; filterString(repo) && commands.push(c(repo)); @@ -168965,7 +180429,7 @@ var init_simple_git_api = __esm2({ init_status(); init_task(); init_version3(); - init_utils19(); + init_utils20(); init_clone(); SimpleGitApi = class { constructor(_executor) { @@ -169040,7 +180504,7 @@ var createScheduledTask; var Scheduler; var init_scheduler = __esm2({ "src/lib/runners/scheduler.ts"() { - init_utils19(); + init_utils20(); init_git_logger(); createScheduledTask = /* @__PURE__ */ (() => { let id = 0; @@ -169135,7 +180599,7 @@ var parseBranchDeletions; var init_parse_branch_delete = __esm2({ "src/lib/parsers/parse-branch-delete.ts"() { init_BranchDeleteSummary(); - init_utils19(); + init_utils20(); deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; deleteErrorRegex = /^error[^']+'([^']+)'/m; parsers8 = [ @@ -169194,7 +180658,7 @@ var currentBranchParser; var init_parse_branch = __esm2({ "src/lib/parsers/parse-branch.ts"() { init_BranchSummary(); - init_utils19(); + init_utils20(); parsers9 = [ new LineParser(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, (result, [current, name, commit, label]) => { result.push(branchStatus(current), true, name, commit, label); @@ -169286,7 +180750,7 @@ var init_branch2 = __esm2({ init_git_response_error(); init_parse_branch_delete(); init_parse_branch(); - init_utils19(); + init_utils20(); } }); function toPath(input) { @@ -169331,7 +180795,7 @@ function parseFetchResult(stdOut, stdErr) { var parsers10; var init_parse_fetch = __esm2({ "src/lib/parsers/parse-fetch.ts"() { - init_utils19(); + init_utils20(); parsers10 = [ new LineParser(/From (.+)$/, (result, [remote]) => { result.remote = remote; @@ -169398,7 +180862,7 @@ function parseMoveResult(stdOut) { var parsers11; var init_parse_move = __esm2({ "src/lib/parsers/parse-move.ts"() { - init_utils19(); + init_utils20(); parsers11 = [ new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { result.moves.push({ from, to }); @@ -169420,7 +180884,7 @@ function moveTask(from, to) { var init_move = __esm2({ "src/lib/tasks/move.ts"() { init_parse_move(); - init_utils19(); + init_utils20(); } }); var pull_exports = {}; @@ -169451,7 +180915,7 @@ var init_pull = __esm2({ "src/lib/tasks/pull.ts"() { init_git_response_error(); init_parse_pull(); - init_utils19(); + init_utils20(); } }); function parseGetRemotes(text) { @@ -169479,7 +180943,7 @@ function forEach(text, handler) { } var init_GetRemoteSummary = __esm2({ "src/lib/responses/GetRemoteSummary.ts"() { - init_utils19(); + init_utils20(); } }); var remote_exports = {}; @@ -169686,7 +181150,7 @@ var require_git = __commonJS2({ getTrailingOptions: getTrailingOptions2, trailingFunctionArgument: trailingFunctionArgument2, trailingOptionsArgument: trailingOptionsArgument2 - } = (init_utils19(), __toCommonJS(utils_exports)); + } = (init_utils20(), __toCommonJS(utils_exports)); var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports)); var { branchTask: branchTask2, @@ -169984,7 +181448,7 @@ function blockUnsafeOperationsPlugin(options = {}) { } }; } -init_utils19(); +init_utils20(); function commandConfigPrefixingPlugin(configuration) { const prefix = prefixedArray(configuration, "-c"); return { @@ -169994,7 +181458,7 @@ function commandConfigPrefixingPlugin(configuration) { } }; } -init_utils19(); +init_utils20(); var never3 = import_promise_deferred2.deferred().promise; function completionDetectionPlugin({ onClose = true, @@ -170058,7 +181522,7 @@ function completionDetectionPlugin({ } }; } -init_utils19(); +init_utils20(); var WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`; var WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`; function isBadArgument(arg) { @@ -170127,7 +181591,7 @@ function errorDetectionPlugin(config3) { } }; } -init_utils19(); +init_utils20(); var PluginStore = class { constructor() { this.plugins = /* @__PURE__ */ new Set; @@ -170161,7 +181625,7 @@ var PluginStore = class { return output; } }; -init_utils19(); +init_utils20(); function progressMonitorPlugin(progress) { const progressCommand = "--progress"; const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; @@ -170200,7 +181664,7 @@ function progressMonitorPlugin(progress) { function progressEventStage(input) { return String(input.toLowerCase().split(" ", 1)) || "unknown"; } -init_utils19(); +init_utils20(); function spawnOptionsPlugin(spawnOptions) { const options = pick3(spawnOptions, ["uid", "gid"]); return { @@ -170269,7 +181733,7 @@ function suffixPathsPlugin() { } }; } -init_utils19(); +init_utils20(); var Git = require_git(); function gitInstanceFactory(baseDir, options) { const plugins = new PluginStore; @@ -170455,7 +181919,7 @@ function buildScriptTool(t2, workdir) { ...script.env ?? {} }; for (const [k2, v] of Object.entries(args)) { - env2[k2.toUpperCase()] = stringify4(v); + env2[k2.toUpperCase()] = stringify6(v); } const { stdout, stderr, code } = await runProcess({ command: script.command, @@ -170546,7 +182010,7 @@ function jsonSchemaToZodShape(parameters) { } return shape; } -function stringify4(v) { +function stringify6(v) { if (typeof v === "string") return v; if (v === null || v === undefined) @@ -171046,8 +182510,8 @@ class MongoSessionStore { const coll = await this.collection(); const doc3 = await coll.findOne({ _id: key.sessionId }); const existing = doc3?.entries ?? []; - const seenUuids = new Set(existing.map((e) => e.uuid).filter((u) => typeof u === "string")); - const fresh = entries.filter((e) => !e.uuid || !seenUuids.has(e.uuid)); + const seenUuids = new Set(existing.map((e2) => e2.uuid).filter((u) => typeof u === "string")); + const fresh = entries.filter((e2) => !e2.uuid || !seenUuids.has(e2.uuid)); if (fresh.length === 0) return; await coll.updateOne({ _id: key.sessionId }, {